tokensafe 4.6.1 → 4.6.3

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/retrofit.py CHANGED
@@ -9,120 +9,281 @@ import json
9
9
  import time
10
10
  from typing import Dict, Any, List, Optional, Tuple
11
11
 
12
+ # Top-level directories that hold frontend source in a repo-root app (as opposed to
13
+ # scripts/, tooling/ and configs, which are .ts/.js but not OUMV-observable).
14
+ _FRONTEND_SOURCE_DIRS = frozenset({
15
+ "src", "app", "pages", "components", "hooks", "lib", "features",
16
+ "views", "stores", "store", "utils", "layouts", "router", "routes", "api",
17
+ })
18
+
19
+
20
+ def _detect_package_json_entry(pkg_json_path: str, rel_dir: str = ".") -> Tuple[Optional[Dict[str, Any]], Optional[Dict[str, Any]], List[str]]:
21
+ """Inspects a single package.json for frontend or Node.js backend stack."""
22
+ fe_out: Optional[Dict[str, Any]] = None
23
+ be_out: Optional[Dict[str, Any]] = None
24
+ managers: List[str] = []
25
+ try:
26
+ with open(pkg_json_path, "r", encoding="utf-8") as f:
27
+ pkg_data = json.load(f)
28
+ deps = {
29
+ **pkg_data.get("dependencies", {}),
30
+ **pkg_data.get("devDependencies", {}),
31
+ }
32
+
33
+ state_managers = []
34
+ if "zustand" in deps:
35
+ state_managers.append("zustand")
36
+ if "redux" in deps or "@reduxjs/toolkit" in deps:
37
+ state_managers.append("redux")
38
+ if "pinia" in deps:
39
+ state_managers.append("pinia")
40
+ if "jotai" in deps:
41
+ state_managers.append("jotai")
42
+
43
+ fe_info: Dict[str, Any] = {
44
+ "state_managers": state_managers,
45
+ "orm": "prisma" if "@prisma/client" in deps or "prisma" in deps else ("drizzle" if "drizzle-orm" in deps else None),
46
+ "vite": "vite" in deps,
47
+ "root": rel_dir,
48
+ }
49
+
50
+ if "next" in deps:
51
+ fe_info.update({"framework": "nextjs", "provider": "react", "adapter": "tokensafe-ui/oumv/react", "version": deps.get("next"), "oumv_supported": True, "status": "ready"})
52
+ elif "react" in deps:
53
+ fe_info.update({"framework": "react", "provider": "react", "adapter": "tokensafe-ui/oumv/react", "version": deps.get("react"), "oumv_supported": True, "status": "ready"})
54
+ elif "vue" in deps:
55
+ fe_info.update({"framework": "vue", "provider": "vue", "adapter": "tokensafe-ui/oumv/vue", "version": deps.get("vue"), "oumv_supported": True, "status": "ready"})
56
+ elif "solid-js" in deps or "@tokensafe-ui/core" in deps:
57
+ fe_info.update({"framework": "solid", "provider": "solid", "adapter": "tokensafe-ui/core", "version": deps.get("solid-js") or deps.get("@tokensafe-ui/core"), "oumv_supported": True, "status": "ready"})
58
+ elif "svelte" in deps:
59
+ fe_info.update({"framework": "svelte", "provider": "svelte", "adapter": "tokensafe-ui/core", "version": deps.get("svelte"), "oumv_supported": True, "status": "ready"})
60
+
61
+ if "framework" in fe_info:
62
+ fe_out = fe_info
63
+
64
+ # Node.js backend frameworks (adapter status: planned / unsupported yet)
65
+ node_fw = None
66
+ if "@nestjs/core" in deps:
67
+ node_fw = "nestjs"
68
+ elif "fastify" in deps:
69
+ node_fw = "fastify"
70
+ elif "express" in deps:
71
+ node_fw = "express"
72
+ elif "hono" in deps:
73
+ node_fw = "hono"
74
+ elif "koa" in deps:
75
+ node_fw = "koa"
76
+
77
+ if node_fw:
78
+ be_out = {
79
+ "framework": node_fw,
80
+ "provider": "node",
81
+ "adapter": "tokensafe-backend/node",
82
+ "language": "node",
83
+ "root": rel_dir,
84
+ "oumv_supported": False,
85
+ "status": "planned",
86
+ }
87
+
88
+ if isinstance(pkg_data.get("workspaces"), (list, dict)):
89
+ managers.append("workspaces")
90
+ except Exception:
91
+ pass
92
+ return fe_out, be_out, managers
93
+
94
+
95
+ def _iter_monorepo_package_dirs(workspace_dir: str) -> List[str]:
96
+ """Returns shallow package subdirectories (depth <= 2) for monorepo stack discovery."""
97
+ skip = {"node_modules", ".git", "dist", "build", ".next", ".venv", "venv", "__pycache__", ".tokensafe"}
98
+ candidates: List[str] = []
99
+ container_names = {"apps", "packages", "services", "frontend", "web", "client", "ui", "backend", "api", "server", "go", "python"}
100
+ try:
101
+ for entry in sorted(os.listdir(workspace_dir)):
102
+ if entry in skip or entry.startswith("."):
103
+ continue
104
+ full = os.path.join(workspace_dir, entry)
105
+ if not os.path.isdir(full):
106
+ continue
107
+ if entry in container_names or os.path.isfile(os.path.join(full, "package.json")) or os.path.isfile(os.path.join(full, "go.mod")) or os.path.isfile(os.path.join(full, "pyproject.toml")):
108
+ candidates.append(full)
109
+ if entry in ("apps", "packages", "services"):
110
+ try:
111
+ for sub in sorted(os.listdir(full)):
112
+ if sub in skip or sub.startswith("."):
113
+ continue
114
+ sub_full = os.path.join(full, sub)
115
+ if os.path.isdir(sub_full):
116
+ candidates.append(sub_full)
117
+ except OSError:
118
+ pass
119
+ except OSError:
120
+ pass
121
+ return candidates
122
+
12
123
 
13
124
  def detect_project_stack(workspace_dir: str) -> Dict[str, Any]:
14
- """Inspects workspace manifests to detect frontend and backend frameworks."""
125
+ """Inspects workspace and monorepo manifests to detect frontend and backend frameworks."""
15
126
  stack: Dict[str, Any] = {
16
127
  "workspace": workspace_dir,
17
128
  "frontend": None,
18
129
  "backend": None,
19
130
  "package_managers": [],
20
131
  "detected_files": [],
132
+ "packages": [],
21
133
  }
22
134
 
23
- # 1. Frontend detection (package.json)
24
- pkg_json_path = os.path.join(workspace_dir, "package.json")
25
- if os.path.isfile(pkg_json_path):
26
- stack["detected_files"].append("package.json")
27
- try:
28
- with open(pkg_json_path, "r", encoding="utf-8") as f:
29
- pkg_data = json.load(f)
30
- deps = {
31
- **pkg_data.get("dependencies", {}),
32
- **pkg_data.get("devDependencies", {}),
33
- }
34
-
35
- state_managers = []
36
- if "zustand" in deps:
37
- state_managers.append("zustand")
38
- if "redux" in deps or "@reduxjs/toolkit" in deps:
39
- state_managers.append("redux")
40
- if "pinia" in deps:
41
- state_managers.append("pinia")
42
- if "jotai" in deps:
43
- state_managers.append("jotai")
44
-
45
- fe_info: Dict[str, Any] = {
46
- "state_managers": state_managers,
47
- "orm": "prisma" if "@prisma/client" in deps or "prisma" in deps else ("drizzle" if "drizzle-orm" in deps else None),
48
- }
49
-
50
- if "next" in deps:
51
- fe_info.update({"framework": "nextjs", "provider": "react", "adapter": "tokensafe-ui/oumv/react", "version": deps.get("next")})
52
- elif "react" in deps:
53
- fe_info.update({"framework": "react", "provider": "react", "adapter": "tokensafe-ui/oumv/react", "version": deps.get("react")})
54
- elif "vue" in deps:
55
- fe_info.update({"framework": "vue", "provider": "vue", "adapter": "tokensafe-ui/oumv/vue", "version": deps.get("vue")})
56
- elif "solid-js" in deps or "@tokensafe-ui/core" in deps:
57
- fe_info.update({"framework": "solid", "provider": "solid", "adapter": "tokensafe-ui/core", "version": deps.get("solid-js") or deps.get("@tokensafe-ui/core")})
58
- elif "svelte" in deps:
59
- fe_info.update({"framework": "svelte", "provider": "svelte", "adapter": "tokensafe-ui/core", "version": deps.get("svelte")})
60
-
61
- if "framework" in fe_info:
62
- stack["frontend"] = fe_info
63
- except Exception:
64
- pass
65
-
66
- # Lockfiles
67
- for lock, pm in [("pnpm-lock.yaml", "pnpm"), ("bun.lockb", "bun"), ("bun.lock", "bun"), ("yarn.lock", "yarn"), ("package-lock.json", "npm")]:
68
- if os.path.isfile(os.path.join(workspace_dir, lock)):
69
- stack["package_managers"].append(pm)
70
- stack["detected_files"].append(lock)
71
-
72
- # 2. Go Backend detection (go.mod)
73
- go_mod_path = os.path.join(workspace_dir, "go.mod")
74
- if not os.path.isfile(go_mod_path) and os.path.isfile(os.path.join(workspace_dir, "go", "go.mod")):
75
- go_mod_path = os.path.join(workspace_dir, "go", "go.mod")
76
-
77
- if os.path.isfile(go_mod_path):
78
- stack["detected_files"].append(os.path.relpath(go_mod_path, workspace_dir))
79
- stack["package_managers"].append("go")
80
- framework = "net/http"
81
- try:
82
- with open(go_mod_path, "r", encoding="utf-8") as f:
83
- content = f.read()
84
- if "github.com/gin-gonic/gin" in content:
85
- framework = "gin"
86
- elif "github.com/go-chi/chi" in content:
87
- framework = "chi"
88
- elif "github.com/labstack/echo" in content:
89
- framework = "echo"
90
- stack["backend"] = {"framework": framework, "provider": "go", "adapter": "tokensafe-backend/go", "language": "go"}
91
- except Exception:
92
- stack["backend"] = {"framework": "go", "provider": "go", "adapter": "tokensafe-backend/go", "language": "go"}
93
-
94
- # 3. Python Backend detection (pyproject.toml, requirements.txt, setup.py)
95
- py_files = [
96
- os.path.join(workspace_dir, "pyproject.toml"),
97
- os.path.join(workspace_dir, "python", "pyproject.toml"),
98
- os.path.join(workspace_dir, "requirements.txt"),
99
- ]
100
- for pf in py_files:
101
- if os.path.isfile(pf):
102
- stack["detected_files"].append(os.path.relpath(pf, workspace_dir))
103
- stack["package_managers"].append("pip/python")
104
- try:
105
- with open(pf, "r", encoding="utf-8") as f:
106
- c = f.read().lower()
107
- framework = "python"
108
- if "fastapi" in c:
109
- framework = "fastapi"
110
- elif "django" in c:
111
- framework = "django"
112
- elif "flask" in c:
113
- framework = "flask"
114
- elif "starlette" in c:
115
- framework = "starlette"
135
+ def _add_detected(rel_path: str) -> None:
136
+ if rel_path not in stack["detected_files"]:
137
+ stack["detected_files"].append(rel_path)
138
+
139
+ def _add_package(entry: Dict[str, Any]) -> None:
140
+ """Adds a package once: the same manifest is reachable from the root scan
141
+ (e.g. python/pyproject.toml) and from monorepo discovery."""
142
+ key = (entry.get("role"), entry.get("path"), entry.get("framework"))
143
+ for existing in stack["packages"]:
144
+ if (existing.get("role"), existing.get("path"), existing.get("framework")) == key:
145
+ return
146
+ stack["packages"].append(entry)
147
+
148
+ def _scan_dir(target_dir: str):
149
+ rel = os.path.relpath(target_dir, workspace_dir) or "."
150
+ pkg_json_path = os.path.join(target_dir, "package.json")
151
+ if os.path.isfile(pkg_json_path):
152
+ _add_detected(os.path.relpath(pkg_json_path, workspace_dir))
153
+ fe_info, be_info, _ = _detect_package_json_entry(pkg_json_path, rel_dir=rel)
154
+ if fe_info:
155
+ if not stack["frontend"]:
156
+ stack["frontend"] = fe_info
157
+ _add_package({
158
+ "role": "frontend",
159
+ "path": rel,
160
+ "framework": fe_info["framework"],
161
+ "provider": fe_info["provider"],
162
+ "adapter": fe_info["adapter"],
163
+ "vite": fe_info.get("vite", False),
164
+ "oumvSupported": bool(fe_info.get("oumv_supported", True)),
165
+ "status": fe_info.get("status", "ready"),
166
+ })
167
+ if be_info:
116
168
  if not stack["backend"]:
117
- stack["backend"] = {
169
+ stack["backend"] = be_info
170
+ _add_package({
171
+ "role": "backend",
172
+ "path": rel,
173
+ "framework": be_info["framework"],
174
+ "provider": be_info["provider"],
175
+ "adapter": be_info["adapter"],
176
+ "oumvSupported": bool(be_info.get("oumv_supported", False)),
177
+ "status": be_info.get("status", "planned"),
178
+ })
179
+
180
+ # Go Backend detection
181
+ go_mod_path = os.path.join(target_dir, "go.mod")
182
+ if rel == "." and not os.path.isfile(go_mod_path) and os.path.isfile(os.path.join(target_dir, "go", "go.mod")):
183
+ go_mod_path = os.path.join(target_dir, "go", "go.mod")
184
+ if os.path.isfile(go_mod_path):
185
+ rel_mod = os.path.relpath(go_mod_path, workspace_dir)
186
+ _add_detected(rel_mod)
187
+ if "go" not in stack["package_managers"]:
188
+ stack["package_managers"].append("go")
189
+ framework = "net/http"
190
+ try:
191
+ with open(go_mod_path, "r", encoding="utf-8") as f:
192
+ content = f.read()
193
+ if "github.com/gin-gonic/gin" in content:
194
+ framework = "gin"
195
+ elif "github.com/go-chi/chi" in content:
196
+ framework = "chi"
197
+ elif "github.com/labstack/echo" in content:
198
+ framework = "echo"
199
+ except Exception:
200
+ pass
201
+ go_entry = {
202
+ "framework": framework,
203
+ "provider": "go",
204
+ "adapter": "tokensafe-backend/go",
205
+ "language": "go",
206
+ "root": os.path.dirname(rel_mod) or ".",
207
+ "oumv_supported": True,
208
+ "status": "ready",
209
+ }
210
+ if not stack["backend"] or not stack["backend"].get("oumv_supported", False):
211
+ stack["backend"] = go_entry
212
+ _add_package({
213
+ "role": "backend",
214
+ "path": go_entry["root"],
215
+ "framework": framework,
216
+ "provider": "go",
217
+ "adapter": "tokensafe-backend/go",
218
+ "oumvSupported": True,
219
+ "status": "ready",
220
+ })
221
+
222
+ # Python Backend detection
223
+ py_files = [
224
+ os.path.join(target_dir, "pyproject.toml"),
225
+ os.path.join(target_dir, "requirements.txt"),
226
+ ]
227
+ if rel == ".":
228
+ py_files.insert(1, os.path.join(target_dir, "python", "pyproject.toml"))
229
+ for pf in py_files:
230
+ if os.path.isfile(pf):
231
+ rel_pf = os.path.relpath(pf, workspace_dir)
232
+ _add_detected(rel_pf)
233
+ if "pip/python" not in stack["package_managers"]:
234
+ stack["package_managers"].append("pip/python")
235
+ try:
236
+ with open(pf, "r", encoding="utf-8") as f:
237
+ c = f.read().lower()
238
+ framework = "python"
239
+ if "fastapi" in c:
240
+ framework = "fastapi"
241
+ elif "django" in c:
242
+ framework = "django"
243
+ elif "flask" in c:
244
+ framework = "flask"
245
+ elif "starlette" in c:
246
+ framework = "starlette"
247
+ supported = framework in ("fastapi", "starlette")
248
+ py_entry = {
118
249
  "framework": framework,
119
250
  "provider": "fastapi" if framework == "fastapi" else "python",
120
251
  "adapter": "tokensafe-backend/python",
121
252
  "language": "python",
253
+ "root": os.path.dirname(rel_pf) or ".",
254
+ "oumv_supported": supported,
255
+ "status": "ready" if supported else "planned",
122
256
  }
123
- except Exception:
124
- pass
125
- break
257
+ # A supported Python backend outranks an unsupported Node one,
258
+ # mirroring the Go precedence rule above.
259
+ if not stack["backend"] or not stack["backend"].get("oumv_supported", False):
260
+ stack["backend"] = py_entry
261
+ _add_package({
262
+ "role": "backend",
263
+ "path": py_entry["root"],
264
+ "framework": framework,
265
+ "provider": py_entry["provider"],
266
+ "adapter": "tokensafe-backend/python",
267
+ "oumvSupported": supported,
268
+ "status": py_entry["status"],
269
+ })
270
+ except Exception:
271
+ pass
272
+ break
273
+
274
+ _scan_dir(workspace_dir)
275
+ if os.path.isfile(os.path.join(workspace_dir, "pnpm-workspace.yaml")):
276
+ _add_detected("pnpm-workspace.yaml")
277
+
278
+ for lock, pm in [("pnpm-lock.yaml", "pnpm"), ("bun.lockb", "bun"), ("bun.lock", "bun"), ("yarn.lock", "yarn"), ("package-lock.json", "npm")]:
279
+ if os.path.isfile(os.path.join(workspace_dir, lock)):
280
+ if pm not in stack["package_managers"]:
281
+ stack["package_managers"].append(pm)
282
+ if lock not in stack["detected_files"]:
283
+ stack["detected_files"].append(lock)
284
+
285
+ for sub_dir in _iter_monorepo_package_dirs(workspace_dir):
286
+ _scan_dir(sub_dir)
126
287
 
127
288
  return stack
128
289
 
@@ -333,7 +494,15 @@ def run_doctor(workspace_dir: str) -> Dict[str, Any]:
333
494
  """Diagnostics check for OUMV configuration, ports, lockfiles, and permissions."""
334
495
  stack = detect_project_stack(workspace_dir)
335
496
  conf_path = os.path.join(workspace_dir, ".tokensafe", "oumv.json")
336
- runtime_path = os.path.join(workspace_dir, ".tokensafe", "runtime.json")
497
+ runtime_paths = [
498
+ os.path.join(workspace_dir, ".tokensafe", "runtime.json"),
499
+ ]
500
+ try:
501
+ from src.oumv_gateway import OUMVGateway
502
+ runtime_paths.insert(0, OUMVGateway.global_runtime_file(workspace_dir))
503
+ except Exception:
504
+ pass
505
+ runtime_path = next((p for p in runtime_paths if os.path.isfile(p)), runtime_paths[-1])
337
506
 
338
507
  has_config = os.path.isfile(conf_path)
339
508
  config_data: Dict[str, Any] = {}
@@ -426,3 +595,202 @@ class OUMVProjectContext:
426
595
  if any(target.startswith(c) for c in ["#", ".", "[", "button", "input"]) or target.startswith("<") or target.endswith(".tsx") or target.endswith(".jsx"):
427
596
  return "frontend"
428
597
  return "auto"
598
+
599
+
600
+ _UI_CLI_CACHE: Dict[str, Tuple[float, Optional[Tuple[List[str], str]]]] = {}
601
+ _UI_CLI_CACHE_TTL: float = 60.0
602
+
603
+
604
+ def _resolve_tokensafe_ui_cli_uncached(workspace_dir: str) -> Optional[Tuple[List[str], str]]:
605
+ """Finds an installed tokensafe-ui CLI without touching the network.
606
+
607
+ Returns (argv prefix, human source) or None when the companion CLI is absent.
608
+ """
609
+ import shutil
610
+ import subprocess
611
+
612
+ ws = os.path.abspath(workspace_dir)
613
+
614
+ # 1. Explicit override wins: lets CI pin a checkout without a global install.
615
+ env_cli = os.environ.get("TOKENSAFE_UI_CLI")
616
+ if env_cli and os.path.isfile(env_cli):
617
+ return (["node", env_cli], "TOKENSAFE_UI_CLI")
618
+
619
+ # 2. Local project node_modules/.bin/tokensafe-ui (if present)
620
+ local_bin = os.path.join(ws, "node_modules", ".bin", "tokensafe-ui")
621
+ if os.path.isfile(local_bin):
622
+ return ([local_bin], "local node_modules")
623
+
624
+ # 3. Global tokensafe-ui binary on PATH
625
+ global_bin = shutil.which("tokensafe-ui")
626
+ if global_bin:
627
+ return ([global_bin], "global PATH")
628
+
629
+ # 4. npm global root package (nvm-style installs whose bin dir is not on PATH)
630
+ try:
631
+ res = subprocess.run(["npm", "root", "-g"], capture_output=True, text=True, timeout=3)
632
+ if res.returncode == 0:
633
+ cli_js = os.path.join(res.stdout.strip(), "tokensafe-ui", "bin", "cli.js")
634
+ if os.path.isfile(cli_js):
635
+ return (["node", cli_js], "npm global root")
636
+ except Exception:
637
+ pass
638
+ return None
639
+
640
+
641
+ def resolve_tokensafe_ui_cli(workspace_dir: str) -> Optional[Tuple[List[str], str]]:
642
+ """Cached resolver for the tokensafe-ui CLI (60s TTL per workspace).
643
+
644
+ Called from the command sanitizer, which runs per shell command; the npm-root
645
+ probe alone costs ~200 ms, so it must not repeat on every invocation.
646
+ """
647
+ ws = os.path.abspath(workspace_dir)
648
+ now = time.time()
649
+ hit = _UI_CLI_CACHE.get(ws)
650
+ if hit and (now - hit[0]) < _UI_CLI_CACHE_TTL:
651
+ return hit[1]
652
+ resolved = _resolve_tokensafe_ui_cli_uncached(ws)
653
+ _UI_CLI_CACHE[ws] = (now, resolved)
654
+ return resolved
655
+
656
+
657
+ def resolve_zero_footprint_vite_command(
658
+ workspace_dir: str,
659
+ port: Optional[int] = None,
660
+ host: Optional[str] = None,
661
+ open_browser: bool = False,
662
+ ) -> Tuple[List[str], str]:
663
+ """Resolves zero-footprint tokensafe-ui Vite+React runner command without editing repo files."""
664
+ import shutil
665
+
666
+ ws = os.path.abspath(workspace_dir)
667
+ cli_flags: List[str] = []
668
+ if port is not None:
669
+ cli_flags.append(f"--port={port}")
670
+ if host:
671
+ cli_flags.append(f"--host={host}")
672
+ if open_browser:
673
+ cli_flags.append("--open")
674
+
675
+ resolved = resolve_tokensafe_ui_cli(ws)
676
+ if resolved:
677
+ prefix, source = resolved
678
+ return ([*prefix, "dev", ws, *cli_flags], source)
679
+
680
+ # Explicit `tokensafe dev` may bootstrap the companion package via npx; the
681
+ # command sanitizer never rewrites to this path (see CommandSanitizer).
682
+ npx_bin = shutil.which("npx") or "npx"
683
+ return ([npx_bin, "--yes", "tokensafe-ui", "dev", ws, *cli_flags], "npx tokensafe-ui")
684
+
685
+
686
+ def format_oumv_workspace_brief(workspace_dir: str, include_live: bool = False) -> str:
687
+ """Builds a compact OUMV capability matrix banner for SessionStart and tokensafe-proxy.
688
+
689
+ Explicitly separates supported profiles (React+Vite, Vue, Solid, Go, FastAPI)
690
+ from unsupported stacks (e.g. Node.js express/fastify/nest in a monorepo), so agents
691
+ use OUMV where available without wasting turns probing unsupported subprojects.
692
+ """
693
+ if not workspace_dir or not os.path.isdir(workspace_dir):
694
+ return ""
695
+ stack = detect_project_stack(workspace_dir)
696
+ packages = stack.get("packages") or []
697
+ parts: List[str] = []
698
+ seen_labels = set()
699
+
700
+ for pkg in packages:
701
+ loc = f" ({pkg['path']})" if pkg.get("path") and pkg["path"] != "." else ""
702
+ label = f"{pkg.get('provider')}/{pkg.get('framework')}{loc}"
703
+ if label in seen_labels:
704
+ continue
705
+ seen_labels.add(label)
706
+ if pkg.get("oumvSupported"):
707
+ run_hint = "; start live bridge via 'tokensafe dev'" if pkg.get("vite") else ""
708
+ parts.append(
709
+ f"{label}: OUMV SUPPORTED (use tokensafe:oumv observe/understand/mutate{run_hint})"
710
+ )
711
+ else:
712
+ parts.append(
713
+ f"{label}: OUMV UNSUPPORTED yet (planned — use repo_map/smart_read_file/scoped_search instead of oumv)"
714
+ )
715
+
716
+ if not parts:
717
+ return ""
718
+
719
+ if include_live:
720
+ try:
721
+ from src.oumv_gateway import OUMVGateway
722
+ fe, be = OUMVGateway.get_endpoints(workspace_dir=workspace_dir)
723
+ live_bits = []
724
+ if fe:
725
+ live_bits.append(f"FE LIVE {fe.get('url')}")
726
+ if be:
727
+ live_bits.append(f"BE LIVE {be.get('url')}")
728
+ if live_bits:
729
+ parts.append("LIVE RUNTIMES: " + ", ".join(live_bits) + " -> MUST inspect/verify via tokensafe:oumv")
730
+ except Exception:
731
+ pass
732
+
733
+ return "[TokenSafe OUMV Workspace Matrix | " + " | ".join(parts) + "]"
734
+
735
+
736
+ _STACK_CACHE: Dict[str, Tuple[float, Dict[str, Any]]] = {}
737
+ _STACK_CACHE_TTL: float = 60.0
738
+
739
+
740
+ def detect_project_stack_cached(workspace_dir: str, ttl: float = _STACK_CACHE_TTL) -> Dict[str, Any]:
741
+ """Short-TTL cache for hot paths (read/edit hooks run per tool call).
742
+
743
+ Direct callers keep using detect_project_stack() so tests that mutate
744
+ manifests between calls always see fresh results.
745
+ """
746
+ ws = os.path.realpath(os.path.abspath(workspace_dir))
747
+ now = time.time()
748
+ hit = _STACK_CACHE.get(ws)
749
+ if hit and (now - hit[0]) < ttl:
750
+ return hit[1]
751
+ stack = detect_project_stack(workspace_dir)
752
+ _STACK_CACHE[ws] = (now, stack)
753
+ return stack
754
+
755
+
756
+ def is_path_in_supported_oumv_scope(workspace_dir: str, file_path: str, use_cache: bool = False) -> Optional[Dict[str, Any]]:
757
+ """Returns the supported stack entry owning `file_path`, or None if unsupported (e.g. backend/node)."""
758
+ if not workspace_dir or not file_path:
759
+ return None
760
+ ws_abs = os.path.realpath(os.path.abspath(workspace_dir))
761
+ f_abs = os.path.realpath(os.path.abspath(file_path if os.path.isabs(file_path) else os.path.join(ws_abs, file_path)))
762
+ if not (f_abs == ws_abs or f_abs.startswith(ws_abs + os.sep)):
763
+ return None
764
+
765
+ rel = os.path.relpath(f_abs, ws_abs).replace(os.sep, "/")
766
+ stack = detect_project_stack_cached(ws_abs) if use_cache else detect_project_stack(ws_abs)
767
+ packages = stack.get("packages") or []
768
+ # Match most specific package path first
769
+ sorted_pkgs = sorted(
770
+ packages,
771
+ key=lambda p: (0 if p.get("path", ".") == "." else len(str(p.get("path", ".")))),
772
+ reverse=True,
773
+ )
774
+ for pkg in sorted_pkgs:
775
+ p_rel = str(pkg.get("path") or ".").replace(os.sep, "/").strip("/")
776
+ if p_rel == "." or rel == p_rel or rel.startswith(p_rel + "/"):
777
+ if not pkg.get("oumvSupported"):
778
+ return None
779
+ ext = os.path.splitext(f_abs)[1].lower()
780
+ role = pkg.get("role")
781
+ if role == "frontend":
782
+ if ext in (".tsx", ".jsx", ".vue"):
783
+ return pkg
784
+ if ext in (".ts", ".js"):
785
+ # A repository-root frontend also owns scripts/, configs and
786
+ # tooling in .ts/.js; only nudge files under source-like dirs.
787
+ if p_rel != ".":
788
+ return pkg
789
+ top = rel.split("/", 1)[0].lower()
790
+ if "/" in rel and top in _FRONTEND_SOURCE_DIRS:
791
+ return pkg
792
+ return None
793
+ if role == "backend" and ext in (".go", ".py"):
794
+ return pkg
795
+ return None
796
+ return None
package/src/snapshot.py CHANGED
@@ -286,8 +286,9 @@ def build_workspace_snapshot(workspace_dir: str, max_bytes: int = 1400) -> Optio
286
286
 
287
287
  sections = ["[TokenSafe Workspace Snapshot]"]
288
288
 
289
- # 1. Git summary
290
- git_sum = _get_git_summary(workspace_dir)
289
+ # 1. Git summary. SessionStart blocks on this, and it issues three sequential
290
+ # git calls: keep the per-call budget at 0.6s (<=1.8s total), not 2s each.
291
+ git_sum = _get_git_summary(workspace_dir, timeout_sec=0.6)
291
292
  if git_sum:
292
293
  sections.append(git_sum)
293
294
 
@@ -249,7 +249,7 @@ class TelemetrySync:
249
249
  current_last_id = last_id
250
250
  headers = {
251
251
  "Content-Type": "application/json",
252
- "User-Agent": "TokenSafe-Sync/4.6.1"
252
+ "User-Agent": "TokenSafe-Sync/4.6.3"
253
253
  }
254
254
  if active_key:
255
255
  headers["Authorization"] = f"Bearer {active_key}"
@@ -316,7 +316,11 @@ class TelemetrySync:
316
316
  "model": "aggregate",
317
317
  "timestamp": int(time.time()),
318
318
  # Rolled-up historical mass of mixed provenance: conservatively estimated.
319
- "measurement": "estimated"
319
+ "measurement": "estimated",
320
+ # Idempotency key: the cumulative total at emit time.
321
+ # A replay (state loss) repeats the same key and the
322
+ # server collapses it; a newer total is a real delta.
323
+ "client_event_id": f"rollup:{current_rollup_tokens}",
320
324
  })
321
325
  except Exception:
322
326
  pass