tokensafe 4.6.2 → 4.6.4
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 +38 -5
- package/hooks/claude_code_hook.py +22 -0
- package/hooks/kimi_hook.py +20 -0
- package/hooks/pre_tool_use.py +0 -9
- package/hooks/session_start.py +16 -4
- package/kimi.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/src/adapter_core.py +57 -21
- package/src/auto_inject.py +517 -0
- package/src/batch_editor.py +36 -2
- package/src/batch_search.py +31 -5
- package/src/cli.py +152 -10
- package/src/command_sanitizer.py +92 -6
- package/src/guard.py +75 -11
- package/src/installer.py +6 -0
- package/src/mcp_server.py +84 -25
- package/src/oumv_gateway.py +168 -19
- package/src/paths.py +58 -0
- package/src/retrofit.py +219 -45
- package/src/savings.py +81 -0
- package/src/scaffold.py +190 -8
- package/src/session_brief.py +154 -0
- package/src/snapshot.py +3 -2
- package/src/telemetry_sync.py +98 -26
- package/src/transcript_analyzer.py +13 -9
- package/src/version_checker.py +1 -1
- package/hooks/__pycache__/claude_code_hook.cpython-312.pyc +0 -0
- package/hooks/__pycache__/cursor_hook.cpython-312.pyc +0 -0
- package/hooks/__pycache__/kimi_hook.cpython-312.pyc +0 -0
- package/hooks/__pycache__/pre_invocation.cpython-312.pyc +0 -0
- package/hooks/__pycache__/pre_tool_use.cpython-312.pyc +0 -0
- package/hooks/__pycache__/session_start.cpython-312.pyc +0 -0
- package/hooks/__pycache__/stop_hook.cpython-312.pyc +0 -0
- package/hooks/__pycache__/zcode_hook.cpython-312.pyc +0 -0
package/src/retrofit.py
CHANGED
|
@@ -9,6 +9,13 @@ 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
|
+
|
|
12
19
|
|
|
13
20
|
def _detect_package_json_entry(pkg_json_path: str, rel_dir: str = ".") -> Tuple[Optional[Dict[str, Any]], Optional[Dict[str, Any]], List[str]]:
|
|
14
21
|
"""Inspects a single package.json for frontend or Node.js backend stack."""
|
|
@@ -125,16 +132,29 @@ def detect_project_stack(workspace_dir: str) -> Dict[str, Any]:
|
|
|
125
132
|
"packages": [],
|
|
126
133
|
}
|
|
127
134
|
|
|
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
|
+
|
|
128
148
|
def _scan_dir(target_dir: str):
|
|
129
149
|
rel = os.path.relpath(target_dir, workspace_dir) or "."
|
|
130
150
|
pkg_json_path = os.path.join(target_dir, "package.json")
|
|
131
151
|
if os.path.isfile(pkg_json_path):
|
|
132
|
-
|
|
152
|
+
_add_detected(os.path.relpath(pkg_json_path, workspace_dir))
|
|
133
153
|
fe_info, be_info, _ = _detect_package_json_entry(pkg_json_path, rel_dir=rel)
|
|
134
154
|
if fe_info:
|
|
135
155
|
if not stack["frontend"]:
|
|
136
156
|
stack["frontend"] = fe_info
|
|
137
|
-
|
|
157
|
+
_add_package({
|
|
138
158
|
"role": "frontend",
|
|
139
159
|
"path": rel,
|
|
140
160
|
"framework": fe_info["framework"],
|
|
@@ -147,7 +167,7 @@ def detect_project_stack(workspace_dir: str) -> Dict[str, Any]:
|
|
|
147
167
|
if be_info:
|
|
148
168
|
if not stack["backend"]:
|
|
149
169
|
stack["backend"] = be_info
|
|
150
|
-
|
|
170
|
+
_add_package({
|
|
151
171
|
"role": "backend",
|
|
152
172
|
"path": rel,
|
|
153
173
|
"framework": be_info["framework"],
|
|
@@ -163,8 +183,7 @@ def detect_project_stack(workspace_dir: str) -> Dict[str, Any]:
|
|
|
163
183
|
go_mod_path = os.path.join(target_dir, "go", "go.mod")
|
|
164
184
|
if os.path.isfile(go_mod_path):
|
|
165
185
|
rel_mod = os.path.relpath(go_mod_path, workspace_dir)
|
|
166
|
-
|
|
167
|
-
stack["detected_files"].append(rel_mod)
|
|
186
|
+
_add_detected(rel_mod)
|
|
168
187
|
if "go" not in stack["package_managers"]:
|
|
169
188
|
stack["package_managers"].append("go")
|
|
170
189
|
framework = "net/http"
|
|
@@ -190,7 +209,7 @@ def detect_project_stack(workspace_dir: str) -> Dict[str, Any]:
|
|
|
190
209
|
}
|
|
191
210
|
if not stack["backend"] or not stack["backend"].get("oumv_supported", False):
|
|
192
211
|
stack["backend"] = go_entry
|
|
193
|
-
|
|
212
|
+
_add_package({
|
|
194
213
|
"role": "backend",
|
|
195
214
|
"path": go_entry["root"],
|
|
196
215
|
"framework": framework,
|
|
@@ -210,8 +229,7 @@ def detect_project_stack(workspace_dir: str) -> Dict[str, Any]:
|
|
|
210
229
|
for pf in py_files:
|
|
211
230
|
if os.path.isfile(pf):
|
|
212
231
|
rel_pf = os.path.relpath(pf, workspace_dir)
|
|
213
|
-
|
|
214
|
-
stack["detected_files"].append(rel_pf)
|
|
232
|
+
_add_detected(rel_pf)
|
|
215
233
|
if "pip/python" not in stack["package_managers"]:
|
|
216
234
|
stack["package_managers"].append("pip/python")
|
|
217
235
|
try:
|
|
@@ -236,9 +254,11 @@ def detect_project_stack(workspace_dir: str) -> Dict[str, Any]:
|
|
|
236
254
|
"oumv_supported": supported,
|
|
237
255
|
"status": "ready" if supported else "planned",
|
|
238
256
|
}
|
|
239
|
-
|
|
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):
|
|
240
260
|
stack["backend"] = py_entry
|
|
241
|
-
|
|
261
|
+
_add_package({
|
|
242
262
|
"role": "backend",
|
|
243
263
|
"path": py_entry["root"],
|
|
244
264
|
"framework": framework,
|
|
@@ -253,7 +273,7 @@ def detect_project_stack(workspace_dir: str) -> Dict[str, Any]:
|
|
|
253
273
|
|
|
254
274
|
_scan_dir(workspace_dir)
|
|
255
275
|
if os.path.isfile(os.path.join(workspace_dir, "pnpm-workspace.yaml")):
|
|
256
|
-
|
|
276
|
+
_add_detected("pnpm-workspace.yaml")
|
|
257
277
|
|
|
258
278
|
for lock, pm in [("pnpm-lock.yaml", "pnpm"), ("bun.lockb", "bun"), ("bun.lock", "bun"), ("yarn.lock", "yarn"), ("package-lock.json", "npm")]:
|
|
259
279
|
if os.path.isfile(os.path.join(workspace_dir, lock)):
|
|
@@ -333,6 +353,13 @@ def generate_config(
|
|
|
333
353
|
os.makedirs(target_dir, exist_ok=True)
|
|
334
354
|
with open(target_file, "w", encoding="utf-8") as f:
|
|
335
355
|
json.dump(config, f, indent=2)
|
|
356
|
+
# The manifest must never show up as an untracked change: ignore it via
|
|
357
|
+
# .git/info/exclude (local-only) instead of editing the tracked .gitignore.
|
|
358
|
+
try:
|
|
359
|
+
from src.paths import ensure_local_git_exclude
|
|
360
|
+
ensure_local_git_exclude(workspace_dir)
|
|
361
|
+
except Exception:
|
|
362
|
+
pass
|
|
336
363
|
|
|
337
364
|
return config, target_file, True
|
|
338
365
|
|
|
@@ -448,7 +475,7 @@ def get_adapters_catalog() -> List[Dict[str, Any]]:
|
|
|
448
475
|
"technology": {
|
|
449
476
|
"language": "python",
|
|
450
477
|
"framework": "fastapi",
|
|
451
|
-
"package": {"manager": "pip", "name": "tokensafe-python", "install":
|
|
478
|
+
"package": {"manager": "pip", "name": "tokensafe-backend-python", "install": 'pip install "tokensafe-backend-python @ git+https://github.com/tokensafe-dev/tokensafe-backend.git#subdirectory=python"'},
|
|
452
479
|
},
|
|
453
480
|
"capabilities": [
|
|
454
481
|
{"name": "observe.resources", "constraints": {"readOnly": True, "developmentOnly": False}},
|
|
@@ -470,8 +497,54 @@ def get_adapters_catalog() -> List[Dict[str, Any]]:
|
|
|
470
497
|
]
|
|
471
498
|
|
|
472
499
|
|
|
500
|
+
def _adapter_presence(workspace_dir: str, profile: str, provider: str, framework: str) -> Dict[str, Any]:
|
|
501
|
+
"""Best-effort, side-effect-free check whether an adapter is available locally.
|
|
502
|
+
|
|
503
|
+
Returns {"installed": bool, "evidence": str} where evidence names what was
|
|
504
|
+
actually found — never a bare True.
|
|
505
|
+
"""
|
|
506
|
+
ws = os.path.abspath(workspace_dir)
|
|
507
|
+
if profile == "frontend":
|
|
508
|
+
pkg_json = os.path.join(ws, "node_modules", "tokensafe-ui", "package.json")
|
|
509
|
+
if os.path.isfile(pkg_json):
|
|
510
|
+
return {"installed": True, "evidence": "node_modules/tokensafe-ui"}
|
|
511
|
+
return {"installed": False, "evidence": "node_modules/tokensafe-ui missing (run: npm install -D tokensafe-ui)"}
|
|
512
|
+
|
|
513
|
+
if provider == "fastapi":
|
|
514
|
+
try:
|
|
515
|
+
import importlib.util
|
|
516
|
+
if importlib.util.find_spec("tokensafe_python") is not None:
|
|
517
|
+
return {"installed": True, "evidence": "tokensafe_python importable"}
|
|
518
|
+
except Exception:
|
|
519
|
+
pass
|
|
520
|
+
for req in ("requirements.txt", "pyproject.toml"):
|
|
521
|
+
path = os.path.join(ws, req)
|
|
522
|
+
try:
|
|
523
|
+
if os.path.isfile(path):
|
|
524
|
+
with open(path, encoding="utf-8", errors="replace") as fh:
|
|
525
|
+
if "tokensafe" in fh.read():
|
|
526
|
+
return {"installed": True, "evidence": f"{req} declares tokensafe"}
|
|
527
|
+
except Exception:
|
|
528
|
+
pass
|
|
529
|
+
return {"installed": False, "evidence": 'tokensafe_python not importable (run: pip install "tokensafe-backend-python @ git+https://github.com/tokensafe-dev/tokensafe-backend.git#subdirectory=python")'}
|
|
530
|
+
|
|
531
|
+
if provider == "go":
|
|
532
|
+
for rel in ("go.mod", os.path.join("go", "go.mod")):
|
|
533
|
+
path = os.path.join(ws, rel)
|
|
534
|
+
try:
|
|
535
|
+
if os.path.isfile(path):
|
|
536
|
+
with open(path, encoding="utf-8", errors="replace") as fh:
|
|
537
|
+
if "tokensafe-backend/go" in fh.read():
|
|
538
|
+
return {"installed": True, "evidence": f"{rel} requires tokensafe-backend/go"}
|
|
539
|
+
except Exception:
|
|
540
|
+
pass
|
|
541
|
+
return {"installed": False, "evidence": "tokensafe-backend/go not in go.mod (run: go get github.com/tokensafe-dev/tokensafe-backend/go@vX.Y.Z)"}
|
|
542
|
+
|
|
543
|
+
return {"installed": False, "evidence": f"no adapter published for {provider}/{framework}"}
|
|
544
|
+
|
|
545
|
+
|
|
473
546
|
def run_doctor(workspace_dir: str) -> Dict[str, Any]:
|
|
474
|
-
"""Diagnostics
|
|
547
|
+
"""Diagnostics for OUMV configuration, detected adapters and agent readiness."""
|
|
475
548
|
stack = detect_project_stack(workspace_dir)
|
|
476
549
|
conf_path = os.path.join(workspace_dir, ".tokensafe", "oumv.json")
|
|
477
550
|
runtime_paths = [
|
|
@@ -502,6 +575,34 @@ def run_doctor(workspace_dir: str) -> Dict[str, Any]:
|
|
|
502
575
|
except Exception:
|
|
503
576
|
pass
|
|
504
577
|
|
|
578
|
+
# Per-profile readiness: a config file alone is not "ready for agent".
|
|
579
|
+
readiness: Dict[str, Any] = {}
|
|
580
|
+
for profile, key in (("frontend", "frontend"), ("backend", "backend")):
|
|
581
|
+
detected = stack.get(key)
|
|
582
|
+
if not detected:
|
|
583
|
+
continue
|
|
584
|
+
provider = detected.get("provider", "")
|
|
585
|
+
framework = detected.get("framework", "")
|
|
586
|
+
presence = _adapter_presence(workspace_dir, profile, provider, framework)
|
|
587
|
+
live = has_runtime and runtime_data.get("type", profile) in (profile, None)
|
|
588
|
+
readiness[profile] = {
|
|
589
|
+
"provider": provider,
|
|
590
|
+
"framework": framework,
|
|
591
|
+
"installed": presence["installed"],
|
|
592
|
+
"evidence": presence["evidence"],
|
|
593
|
+
"live": bool(live),
|
|
594
|
+
"ready": bool(presence["installed"] or live),
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
permissions = config_data.get("permissions", {"observe": True, "mutate": True})
|
|
598
|
+
config_enabled = bool(config_data.get("oumv", {}).get("enabled", has_config))
|
|
599
|
+
ready_for_agent = bool(
|
|
600
|
+
has_config
|
|
601
|
+
and config_enabled
|
|
602
|
+
and permissions.get("observe", True)
|
|
603
|
+
and all(item["ready"] for item in readiness.values())
|
|
604
|
+
)
|
|
605
|
+
|
|
505
606
|
return {
|
|
506
607
|
"workspace": workspace_dir,
|
|
507
608
|
"detected_stack": stack,
|
|
@@ -509,8 +610,14 @@ def run_doctor(workspace_dir: str) -> Dict[str, Any]:
|
|
|
509
610
|
"config": config_data,
|
|
510
611
|
"runtime_beacon_present": has_runtime,
|
|
511
612
|
"runtime_beacon": runtime_data,
|
|
512
|
-
"permissions":
|
|
513
|
-
"
|
|
613
|
+
"permissions": permissions,
|
|
614
|
+
"adapter_readiness": readiness,
|
|
615
|
+
"ready_for_agent": ready_for_agent,
|
|
616
|
+
"blocking": [
|
|
617
|
+
f"{profile}: {item['evidence']}"
|
|
618
|
+
for profile, item in readiness.items()
|
|
619
|
+
if not item["ready"]
|
|
620
|
+
],
|
|
514
621
|
}
|
|
515
622
|
|
|
516
623
|
|
|
@@ -577,51 +684,88 @@ class OUMVProjectContext:
|
|
|
577
684
|
return "auto"
|
|
578
685
|
|
|
579
686
|
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
687
|
+
_UI_CLI_CACHE: Dict[str, Tuple[float, Optional[Tuple[List[str], str]]]] = {}
|
|
688
|
+
_UI_CLI_CACHE_TTL: float = 60.0
|
|
689
|
+
|
|
690
|
+
|
|
691
|
+
def _resolve_tokensafe_ui_cli_uncached(workspace_dir: str) -> Optional[Tuple[List[str], str]]:
|
|
692
|
+
"""Finds an installed tokensafe-ui CLI without touching the network.
|
|
693
|
+
|
|
694
|
+
Returns (argv prefix, human source) or None when the companion CLI is absent.
|
|
695
|
+
"""
|
|
587
696
|
import shutil
|
|
588
697
|
import subprocess
|
|
589
698
|
|
|
590
699
|
ws = os.path.abspath(workspace_dir)
|
|
591
|
-
cli_flags: List[str] = []
|
|
592
|
-
if port is not None:
|
|
593
|
-
cli_flags.append(f"--port={port}")
|
|
594
|
-
if host:
|
|
595
|
-
cli_flags.append(f"--host={host}")
|
|
596
|
-
if open_browser:
|
|
597
|
-
cli_flags.append("--open")
|
|
598
700
|
|
|
599
|
-
# 1.
|
|
701
|
+
# 1. Explicit override wins: lets CI pin a checkout without a global install.
|
|
702
|
+
env_cli = os.environ.get("TOKENSAFE_UI_CLI")
|
|
703
|
+
if env_cli and os.path.isfile(env_cli):
|
|
704
|
+
return (["node", env_cli], "TOKENSAFE_UI_CLI")
|
|
705
|
+
|
|
706
|
+
# 2. Local project node_modules/.bin/tokensafe-ui (if present)
|
|
600
707
|
local_bin = os.path.join(ws, "node_modules", ".bin", "tokensafe-ui")
|
|
601
708
|
if os.path.isfile(local_bin):
|
|
602
|
-
return ([local_bin
|
|
709
|
+
return ([local_bin], "local node_modules")
|
|
603
710
|
|
|
604
|
-
#
|
|
711
|
+
# 3. Global tokensafe-ui binary on PATH
|
|
605
712
|
global_bin = shutil.which("tokensafe-ui")
|
|
606
713
|
if global_bin:
|
|
607
|
-
return ([global_bin
|
|
714
|
+
return ([global_bin], "global PATH")
|
|
608
715
|
|
|
609
|
-
#
|
|
716
|
+
# 4. npm global root package (nvm-style installs whose bin dir is not on PATH)
|
|
610
717
|
try:
|
|
611
718
|
res = subprocess.run(["npm", "root", "-g"], capture_output=True, text=True, timeout=3)
|
|
612
719
|
if res.returncode == 0:
|
|
613
|
-
|
|
614
|
-
cli_js = os.path.join(global_root, "tokensafe-ui", "bin", "cli.js")
|
|
720
|
+
cli_js = os.path.join(res.stdout.strip(), "tokensafe-ui", "bin", "cli.js")
|
|
615
721
|
if os.path.isfile(cli_js):
|
|
616
|
-
return (["node", cli_js
|
|
722
|
+
return (["node", cli_js], "npm global root")
|
|
617
723
|
except Exception:
|
|
618
724
|
pass
|
|
725
|
+
return None
|
|
726
|
+
|
|
727
|
+
|
|
728
|
+
def resolve_tokensafe_ui_cli(workspace_dir: str) -> Optional[Tuple[List[str], str]]:
|
|
729
|
+
"""Cached resolver for the tokensafe-ui CLI (60s TTL per workspace).
|
|
730
|
+
|
|
731
|
+
Called from the command sanitizer, which runs per shell command; the npm-root
|
|
732
|
+
probe alone costs ~200 ms, so it must not repeat on every invocation.
|
|
733
|
+
"""
|
|
734
|
+
ws = os.path.abspath(workspace_dir)
|
|
735
|
+
now = time.time()
|
|
736
|
+
hit = _UI_CLI_CACHE.get(ws)
|
|
737
|
+
if hit and (now - hit[0]) < _UI_CLI_CACHE_TTL:
|
|
738
|
+
return hit[1]
|
|
739
|
+
resolved = _resolve_tokensafe_ui_cli_uncached(ws)
|
|
740
|
+
_UI_CLI_CACHE[ws] = (now, resolved)
|
|
741
|
+
return resolved
|
|
619
742
|
|
|
620
|
-
# 4. Explicit override or npx fallback (zero edits to workspace package.json)
|
|
621
|
-
env_cli = os.environ.get("TOKENSAFE_UI_CLI")
|
|
622
|
-
if env_cli and os.path.isfile(env_cli):
|
|
623
|
-
return (["node", env_cli, "dev", ws, *cli_flags], "TOKENSAFE_UI_CLI")
|
|
624
743
|
|
|
744
|
+
def resolve_zero_footprint_vite_command(
|
|
745
|
+
workspace_dir: str,
|
|
746
|
+
port: Optional[int] = None,
|
|
747
|
+
host: Optional[str] = None,
|
|
748
|
+
open_browser: bool = False,
|
|
749
|
+
) -> Tuple[List[str], str]:
|
|
750
|
+
"""Resolves zero-footprint tokensafe-ui Vite+React runner command without editing repo files."""
|
|
751
|
+
import shutil
|
|
752
|
+
|
|
753
|
+
ws = os.path.abspath(workspace_dir)
|
|
754
|
+
cli_flags: List[str] = []
|
|
755
|
+
if port is not None:
|
|
756
|
+
cli_flags.append(f"--port={port}")
|
|
757
|
+
if host:
|
|
758
|
+
cli_flags.append(f"--host={host}")
|
|
759
|
+
if open_browser:
|
|
760
|
+
cli_flags.append("--open")
|
|
761
|
+
|
|
762
|
+
resolved = resolve_tokensafe_ui_cli(ws)
|
|
763
|
+
if resolved:
|
|
764
|
+
prefix, source = resolved
|
|
765
|
+
return ([*prefix, "dev", ws, *cli_flags], source)
|
|
766
|
+
|
|
767
|
+
# Explicit `tokensafe dev` may bootstrap the companion package via npx; the
|
|
768
|
+
# command sanitizer never rewrites to this path (see CommandSanitizer).
|
|
625
769
|
npx_bin = shutil.which("npx") or "npx"
|
|
626
770
|
return ([npx_bin, "--yes", "tokensafe-ui", "dev", ws, *cli_flags], "npx tokensafe-ui")
|
|
627
771
|
|
|
@@ -676,7 +820,27 @@ def format_oumv_workspace_brief(workspace_dir: str, include_live: bool = False)
|
|
|
676
820
|
return "[TokenSafe OUMV Workspace Matrix | " + " | ".join(parts) + "]"
|
|
677
821
|
|
|
678
822
|
|
|
679
|
-
|
|
823
|
+
_STACK_CACHE: Dict[str, Tuple[float, Dict[str, Any]]] = {}
|
|
824
|
+
_STACK_CACHE_TTL: float = 60.0
|
|
825
|
+
|
|
826
|
+
|
|
827
|
+
def detect_project_stack_cached(workspace_dir: str, ttl: float = _STACK_CACHE_TTL) -> Dict[str, Any]:
|
|
828
|
+
"""Short-TTL cache for hot paths (read/edit hooks run per tool call).
|
|
829
|
+
|
|
830
|
+
Direct callers keep using detect_project_stack() so tests that mutate
|
|
831
|
+
manifests between calls always see fresh results.
|
|
832
|
+
"""
|
|
833
|
+
ws = os.path.realpath(os.path.abspath(workspace_dir))
|
|
834
|
+
now = time.time()
|
|
835
|
+
hit = _STACK_CACHE.get(ws)
|
|
836
|
+
if hit and (now - hit[0]) < ttl:
|
|
837
|
+
return hit[1]
|
|
838
|
+
stack = detect_project_stack(workspace_dir)
|
|
839
|
+
_STACK_CACHE[ws] = (now, stack)
|
|
840
|
+
return stack
|
|
841
|
+
|
|
842
|
+
|
|
843
|
+
def is_path_in_supported_oumv_scope(workspace_dir: str, file_path: str, use_cache: bool = False) -> Optional[Dict[str, Any]]:
|
|
680
844
|
"""Returns the supported stack entry owning `file_path`, or None if unsupported (e.g. backend/node)."""
|
|
681
845
|
if not workspace_dir or not file_path:
|
|
682
846
|
return None
|
|
@@ -686,7 +850,7 @@ def is_path_in_supported_oumv_scope(workspace_dir: str, file_path: str) -> Optio
|
|
|
686
850
|
return None
|
|
687
851
|
|
|
688
852
|
rel = os.path.relpath(f_abs, ws_abs).replace(os.sep, "/")
|
|
689
|
-
stack = detect_project_stack(ws_abs)
|
|
853
|
+
stack = detect_project_stack_cached(ws_abs) if use_cache else detect_project_stack(ws_abs)
|
|
690
854
|
packages = stack.get("packages") or []
|
|
691
855
|
# Match most specific package path first
|
|
692
856
|
sorted_pkgs = sorted(
|
|
@@ -701,8 +865,18 @@ def is_path_in_supported_oumv_scope(workspace_dir: str, file_path: str) -> Optio
|
|
|
701
865
|
return None
|
|
702
866
|
ext = os.path.splitext(f_abs)[1].lower()
|
|
703
867
|
role = pkg.get("role")
|
|
704
|
-
if role == "frontend"
|
|
705
|
-
|
|
868
|
+
if role == "frontend":
|
|
869
|
+
if ext in (".tsx", ".jsx", ".vue"):
|
|
870
|
+
return pkg
|
|
871
|
+
if ext in (".ts", ".js"):
|
|
872
|
+
# A repository-root frontend also owns scripts/, configs and
|
|
873
|
+
# tooling in .ts/.js; only nudge files under source-like dirs.
|
|
874
|
+
if p_rel != ".":
|
|
875
|
+
return pkg
|
|
876
|
+
top = rel.split("/", 1)[0].lower()
|
|
877
|
+
if "/" in rel and top in _FRONTEND_SOURCE_DIRS:
|
|
878
|
+
return pkg
|
|
879
|
+
return None
|
|
706
880
|
if role == "backend" and ext in (".go", ".py"):
|
|
707
881
|
return pkg
|
|
708
882
|
return None
|
package/src/savings.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""Canonical savings report for agents and hooks.
|
|
2
|
+
|
|
3
|
+
Agents must never quote savings from a guess or from a stray database file: the
|
|
4
|
+
one source of truth is the canonical data dir resolved by ``src.paths``
|
|
5
|
+
(``TOKENSAFE_DATA_DIR`` or ``~/.tokensafe/data``). This module exposes it as a
|
|
6
|
+
single JSON-able report, including the difference between:
|
|
7
|
+
* live events still in ``events`` / ``lifetime_aggregates``, and
|
|
8
|
+
* totals already pruned from the local DB but counted in the cloud mirror
|
|
9
|
+
(``pruned_synced_*``).
|
|
10
|
+
|
|
11
|
+
Repository-local ``data/metrics.db`` files are legacy/test artifacts and are NOT
|
|
12
|
+
read here.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import sqlite3
|
|
18
|
+
from typing import Any, Dict, Optional
|
|
19
|
+
|
|
20
|
+
from src.metrics import MetricsTracker
|
|
21
|
+
from src.paths import resolve_data_dir
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _pruned_synced(db_path: str) -> Dict[str, int]:
|
|
25
|
+
try:
|
|
26
|
+
conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True)
|
|
27
|
+
try:
|
|
28
|
+
row = conn.execute(
|
|
29
|
+
"SELECT pruned_synced_orig_tokens, pruned_synced_saved_tokens FROM lifetime_aggregates WHERE id = 1"
|
|
30
|
+
).fetchone()
|
|
31
|
+
finally:
|
|
32
|
+
conn.close()
|
|
33
|
+
if not row:
|
|
34
|
+
return {"original_tokens": 0, "saved_tokens": 0}
|
|
35
|
+
return {"original_tokens": int(row[0] or 0), "saved_tokens": int(row[1] or 0)}
|
|
36
|
+
except Exception:
|
|
37
|
+
return {"original_tokens": 0, "saved_tokens": 0}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def build_savings_report(tracker: Optional[MetricsTracker] = None) -> Dict[str, Any]:
|
|
41
|
+
"""Returns canonical totals, last event, and the cumulative explanation."""
|
|
42
|
+
tracker = tracker or MetricsTracker()
|
|
43
|
+
summary = tracker.get_summary()
|
|
44
|
+
last_events = tracker.get_recent_events(limit=1)
|
|
45
|
+
|
|
46
|
+
live_saved = int(summary.get("total_saved_tokens", 0))
|
|
47
|
+
pruned = _pruned_synced(tracker.db_path)
|
|
48
|
+
cumulative = live_saved + pruned["saved_tokens"]
|
|
49
|
+
|
|
50
|
+
last_event = None
|
|
51
|
+
if last_events:
|
|
52
|
+
event = last_events[0]
|
|
53
|
+
last_event = {
|
|
54
|
+
"timestamp": event.get("timestamp"),
|
|
55
|
+
"event_type": event.get("event_type"),
|
|
56
|
+
"tool": event.get("event_type"),
|
|
57
|
+
"session_id": event.get("session_id"),
|
|
58
|
+
"saved_tokens": int(event.get("saved_tokens") or 0),
|
|
59
|
+
"original_tokens": int(event.get("original_tokens") or 0),
|
|
60
|
+
"optimized_tokens": int(event.get("optimized_tokens") or 0),
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
return {
|
|
64
|
+
"source": "canonical",
|
|
65
|
+
"data_dir": resolve_data_dir(),
|
|
66
|
+
"db_path": tracker.db_path,
|
|
67
|
+
"total_events": int(summary.get("total_events", 0)),
|
|
68
|
+
"sessions": int(summary.get("session_count", 0)),
|
|
69
|
+
"saved_tokens_live": live_saved,
|
|
70
|
+
"saved_tokens_measured": int(summary.get("total_saved_tokens_measured", 0)),
|
|
71
|
+
"saved_tokens_estimated": int(summary.get("total_saved_tokens_estimated", 0)),
|
|
72
|
+
"pruned_synced_saved_tokens": pruned["saved_tokens"],
|
|
73
|
+
"cumulative_saved_tokens": cumulative,
|
|
74
|
+
"usd_saved_approx": summary.get("total_usd_saved", 0.0),
|
|
75
|
+
"reduction_pct": summary.get("overall_reduction_pct", 0.0),
|
|
76
|
+
"last_event": last_event,
|
|
77
|
+
"note": (
|
|
78
|
+
"cumulative = live events + totals pruned locally but already synced; "
|
|
79
|
+
"per-turn delta must be read from last_event, never guessed"
|
|
80
|
+
),
|
|
81
|
+
}
|