tokensafe 4.6.3 → 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/src/cli.py CHANGED
@@ -9,6 +9,7 @@ Used by:
9
9
 
10
10
  import sys
11
11
  import os
12
+ import shutil
12
13
  import subprocess
13
14
  from typing import Optional, List, Dict, Any
14
15
 
@@ -99,11 +100,13 @@ def _print_help():
99
100
  print("Commands:")
100
101
  print(" dev [dir] [--port N] [--host H] [--open] Start Vite+React DevServer with OUMV (zero repo footprint)")
101
102
  print(" integrate [--dry-run] Retrofit OUMV into existing project (React, Vue, FastAPI, Go)")
103
+ print(" inject [status|apply|revert] Auto-wire adapters with zero repo footprint (add --dry-run)")
102
104
  print(" adapters [list] Catalog of frontend/backend OUMV runtime adapters")
103
105
  print(" oumv doctor / status Diagnose OUMV configuration, ports, and permissions")
104
106
  print(" create <name> [--template ...] Greenfield project scaffolder (tokensafe-ui + tokensafe-backend)")
105
107
  print(" init [--template ...] Initialize TokenSafe stack in current directory")
106
108
  print(" stats / markdown / html Savings analytics (terminal / .md report / dashboard)")
109
+ print(" savings [--json] Canonical totals + last event (cite these numbers, never guess)")
107
110
  print(" status One-screen health check: hooks, weekly savings, tier, sync")
108
111
  print(" budget [--transcript=...] Context Window Budget HUD & Context Quality Score (Grade S-F)")
109
112
  print(" compact <transcript.jsonl> Fold conversation transcript into Consolidated State Ledger")
@@ -335,6 +338,27 @@ def main(argv: Optional[List[str]] = None):
335
338
  print(ledger)
336
339
  print()
337
340
 
341
+ elif command in ("savings", "saved"):
342
+ # Canonical, machine-readable savings numbers. Agents must cite this
343
+ # command instead of guessing (see the footer rule in AGENTS.md).
344
+ from src.savings import build_savings_report
345
+
346
+ report = build_savings_report()
347
+ if "--json" in args:
348
+ import json as _json
349
+ print(_json.dumps(report, indent=2, ensure_ascii=False))
350
+ else:
351
+ last = report.get("last_event") or {}
352
+ print("\n\033[1m\033[36m⚡ TOKENSAFE SAVINGS (canonical) ⚡\033[0m\n")
353
+ print(f" Data dir: {report['data_dir']}")
354
+ print(f" Events / sessions: {report['total_events']} / {report['sessions']}")
355
+ print(f" Saved (live): {report['saved_tokens_live']:,} tokens")
356
+ print(f" Saved (pruned+sync): {report['pruned_synced_saved_tokens']:,} tokens")
357
+ print(f" Cumulative: {report['cumulative_saved_tokens']:,} tokens (≈${report['usd_saved_approx']:.2f})")
358
+ if last:
359
+ print(f" Last event: {last.get('event_type')} — {last.get('saved_tokens'):,} tokens at {last.get('timestamp')}")
360
+ print()
361
+
338
362
  elif command in ("stats", "dashboard"):
339
363
  tracker = MetricsTracker()
340
364
  dashboard = Dashboard(tracker)
@@ -573,6 +597,16 @@ def main(argv: Optional[List[str]] = None):
573
597
  template = "fullstack"
574
598
  force = False
575
599
 
600
+ if "--list" in args:
601
+ print("\nAvailable recipes:")
602
+ print(" react-fastapi React 18 + Vite + FastAPI (recommended)")
603
+ print(" react-go React 18 + Vite + Go/Gin")
604
+ print(" vue-gin Vue 3 + Vite + Go/Gin")
605
+ print(" react / vue frontend only (OUMV via `tokensafe dev`)")
606
+ print(" fastapi / gin backend only (auto-mount)")
607
+ print(" backend, ui, fullstack legacy TokenSafe-native templates\n")
608
+ return
609
+
576
610
  i = 1
577
611
  while i < len(args):
578
612
  arg = args[i]
@@ -581,13 +615,17 @@ def main(argv: Optional[List[str]] = None):
581
615
  print("Usage:")
582
616
  print(" tokensafe create <project-name> [options]\n")
583
617
  print("Options:")
584
- print(" --template <type> fullstack (default), ui, backend, python, go")
618
+ print(" --template <type> recipe or stack:")
619
+ print(" react-fastapi (recommended), react-go, vue-gin,")
620
+ print(" react, vue, fastapi, gin, backend, ui, fullstack")
585
621
  print(" --force, -f Overwrite existing files")
586
622
  print(" --help, -h Show this help screen\n")
587
623
  print("Examples:")
588
624
  print(" tokensafe create my-app")
589
625
  print(" tokensafe create my-dashboard --template ui")
590
- print(" tokensafe create store-api --template backend\n")
626
+ print(" tokensafe create store-api --template fastapi")
627
+ print(" tokensafe create shop --template react-fastapi")
628
+ print(" tokensafe create edge-api --template gin\n")
591
629
  return
592
630
  elif arg in ("--template", "-t") and i + 1 < len(args):
593
631
  template = args[i + 1]
@@ -644,7 +682,9 @@ def main(argv: Optional[List[str]] = None):
644
682
  print("Usage:")
645
683
  print(" tokensafe init [options]\n")
646
684
  print("Options:")
647
- print(" --template <type> fullstack (default), ui, backend, python, go")
685
+ print(" --template <type> recipe or stack:")
686
+ print(" react-fastapi (recommended), react-go, vue-gin,")
687
+ print(" react, vue, fastapi, gin, backend, ui, fullstack")
648
688
  print(" --force, -f Overwrite existing files\n")
649
689
  return
650
690
  elif arg in ("--template", "-t") and i + 1 < len(args):
@@ -708,6 +748,72 @@ def main(argv: Optional[List[str]] = None):
708
748
  else:
709
749
  print(f" ✔ Existing configuration preserved: \033[1m{conf_file}\033[0m (use --force to overwrite)\n")
710
750
 
751
+ elif command in ("run-backend", "run_backend"):
752
+ # Executes the user's dev-server command with the OUMV autoload hook active.
753
+ # Nothing is written into the repository: the hook lives in ~/.tokensafe.
754
+ from src.auto_inject import backend_env, ensure_python_autoload
755
+
756
+ argv_rest = [a for a in args[1:]]
757
+ if not argv_rest:
758
+ print("usage: tokensafe run-backend <command...> e.g. tokensafe run-backend uvicorn app:app --reload")
759
+ return
760
+ ensure_python_autoload()
761
+ env = backend_env()
762
+ tool = argv_rest[0]
763
+ resolved = shutil.which(tool)
764
+ if not resolved:
765
+ print(f"tokensafe run-backend: `{tool}` not found on PATH")
766
+ return
767
+ os.execvpe(resolved, argv_rest, env)
768
+
769
+ elif command in ("inject", "wire"):
770
+ from src import auto_inject
771
+
772
+ if "--status" in args:
773
+ sub = "status"
774
+ elif "--revert" in args:
775
+ sub = "revert"
776
+ else:
777
+ positional = [a for a in args[1:] if not a.startswith("-")]
778
+ sub = positional[0] if positional and positional[0] in ("status", "apply", "revert") else "apply"
779
+ dry_run = "--dry-run" in args
780
+ workspace = os.getcwd()
781
+
782
+ if sub == "status":
783
+ data = auto_inject.plan(workspace)
784
+ print(f"\n\033[1m\033[36m⚡ TOKENSAFE OUMV INJECT PLAN ⚡\033[0m\n")
785
+ print(f" Profiles: {', '.join(data['profiles']) or 'none detected'}")
786
+ for action in data["actions"]:
787
+ writes = "writes repo" if action["writes_repo"] else "zero repo footprint"
788
+ print(f" - {action['kind']:<24} {action['profile']:<9} {writes}")
789
+ if action.get("entrypoint"):
790
+ print(f" entrypoint: {action['entrypoint']} (patched: {action.get('already_patched')})")
791
+ if action.get("install"):
792
+ print(f" install: {action['install']}")
793
+ if action.get("run"):
794
+ print(f" run: {action['run']}")
795
+ print(f" Python autoload: {'✔ installed' if data['python_autoload_present'] else '○ not installed'}")
796
+ print(f" Revertable: {'✔ yes' if data['revertable'] else '○ no'}\n")
797
+ elif sub == "revert":
798
+ result = auto_inject.revert(workspace)
799
+ state = result.get("go", {}).get("status", "nothing-to-revert")
800
+ print(f" Go patch: {state}")
801
+ if result.get("go", {}).get("entrypoint"):
802
+ print(f" Restored: {result['go']['entrypoint']}")
803
+ else:
804
+ result = auto_inject.apply(workspace, dry_run=dry_run, include_go=True)
805
+ prefix = "[DRY-RUN] " if dry_run else ""
806
+ cfg = result.get("config", {})
807
+ print(f"\n{prefix}OUMV config: {cfg.get('path')} ({'created' if cfg.get('created') else 'preserved'}), mutate={cfg.get('mutate')}")
808
+ for action in result.get("actions", []):
809
+ status = action.get("status", "?")
810
+ print(f" {prefix}{action['kind']}: {status}")
811
+ if action.get("run"):
812
+ print(f" run: {action['run']}")
813
+ if action.get("reason"):
814
+ print(f" reason: {action['reason']}")
815
+ print()
816
+
711
817
  elif command in ("adapters", "adapter"):
712
818
  from src.retrofit import get_adapters_catalog
713
819
  catalog = get_adapters_catalog()
@@ -731,8 +837,16 @@ def main(argv: Optional[List[str]] = None):
731
837
  be = doc['detected_stack'].get('backend')
732
838
  print(f" Detected Frontend: {fe['framework'] if fe else 'None'}")
733
839
  print(f" Detected Backend: {be['framework'] if be else 'None'}")
734
- mut = doc['permissions'].get('mutate', False)
735
- print(f" Mutation Permission: {'✔ Enabled' if mut else '○ Read-Only (Default safe)'}\n")
840
+ mut = doc['permissions'].get('mutate', True)
841
+ print(f" Mutation Permission: {'✔ Enabled (out-of-the-box, guarded)' if mut else '○ Read-only (mutate: false)'}")
842
+ for profile, item in (doc.get('adapter_readiness') or {}).items():
843
+ state = "✔ ready" if item["ready"] else "○ not ready"
844
+ live = " (live)" if item["live"] else ""
845
+ print(f" Adapter {profile:<10} {state}{live}: {item['provider']}/{item['framework']} — {item['evidence']}")
846
+ print(f" Ready for agent: {'✔ yes' if doc.get('ready_for_agent') else '○ no'}")
847
+ for reason in doc.get('blocking') or []:
848
+ print(f" - {reason}")
849
+ print()
736
850
  else:
737
851
  from src.oumv_gateway import OUMVGateway
738
852
  status = OUMVGateway.status()
@@ -387,6 +387,12 @@ class CommandSanitizer:
387
387
  if dev_guard:
388
388
  return dev_guard
389
389
 
390
+ # FastAPI dev servers: run through `tokensafe run-backend` so the global
391
+ # autoload hook mounts OUMV without editing the project.
392
+ py_dev_guard = cls._optimize_python_dev_stage(stage, cwd)
393
+ if py_dev_guard:
394
+ return py_dev_guard
395
+
390
396
  # find: prune unbounded recursion on simple directory crawls (avoid breaking -o / -exec / -delete expressions)
391
397
  if cmd_tok == "find" and "node_modules" not in stage and ".git" not in stage:
392
398
  has_complex = any(a in ("-o", "-or", "-exec", "-execdir", "-delete", "(") for a in cmd_args)
@@ -695,6 +701,54 @@ class CommandSanitizer:
695
701
  except Exception:
696
702
  return False
697
703
 
704
+ @classmethod
705
+ def _is_fastapi_workspace(cls, cwd: Optional[str]) -> bool:
706
+ """Cheap, side-effect-free FastAPI detection for the rewrite decision."""
707
+ if not cwd or not os.path.isdir(cwd):
708
+ return False
709
+ for name in ("pyproject.toml", "requirements.txt", "main.py", "app.py"):
710
+ path = os.path.join(cwd, name)
711
+ try:
712
+ if os.path.isfile(path):
713
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
714
+ if "fastapi" in f.read().lower():
715
+ return True
716
+ except OSError:
717
+ continue
718
+ app_dir = os.path.join(cwd, "app")
719
+ for name in ("main.py", "app.py"):
720
+ path = os.path.join(app_dir, name)
721
+ try:
722
+ if os.path.isfile(path):
723
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
724
+ if "fastapi" in f.read().lower():
725
+ return True
726
+ except OSError:
727
+ continue
728
+ return False
729
+
730
+ @classmethod
731
+ def _optimize_python_dev_stage(cls, stage: str, cwd: Optional[str] = None) -> Optional[Tuple[str, int, str, None]]:
732
+ """Rewrites `uvicorn ...` / `python -m uvicorn ...` into `tokensafe run-backend ...`.
733
+
734
+ The wrapper only sets PYTHONPATH/TOKENSAFE_OUMV_AUTOMOUNT and execs the same
735
+ command, so the agent keeps control of ports/flags and the repository stays
736
+ untouched.
737
+ """
738
+ stripped = stage.strip()
739
+ if "tokensafe run-backend" in stripped or "tokensafe inject" in stripped:
740
+ return None
741
+ if not re.match(r"^(?:[A-Za-z_]\w*=\S*\s+)*(?:sudo\s+)?(?:python[0-9.]*\s+-m\s+)?uvicorn\b", stripped):
742
+ return None
743
+ if not cls._is_fastapi_workspace(cwd):
744
+ return None
745
+ return (
746
+ f"tokensafe run-backend {stripped}",
747
+ 1400,
748
+ "Routed FastAPI dev server through `tokensafe run-backend` (auto-mounts OUMV, no repo changes)",
749
+ None,
750
+ )
751
+
698
752
  @classmethod
699
753
  def _optimize_vite_dev_stage(cls, stage: str, cwd: Optional[str] = None) -> Optional[Tuple[str, int, str, None]]:
700
754
  """
package/src/guard.py CHANGED
@@ -23,6 +23,64 @@ from src.command_sanitizer import CommandSanitizer
23
23
 
24
24
  _TOKENSAFE_SRC_DIR = os.path.dirname(os.path.abspath(__file__))
25
25
 
26
+ # --------------------------------------------------------------------------- #
27
+ # Network data-exfiltration detection (shell-flow aware)
28
+ #
29
+ # The previous single regex matched `-d` inside `tokensafe-dev` together with the
30
+ # word `token` inside `tokensafe-python`, across a `;` separator, so read-only
31
+ # checks like `curl … https://pypi.org/… ; gh secret list -R org/repo` were
32
+ # blocked. It also flagged any script that merely quoted such a command in a
33
+ # heredoc. Detection is now per shell segment and only fires on a sensitive
34
+ # *file* actually being uploaded.
35
+ # --------------------------------------------------------------------------- #
36
+
37
+ _EXFIL_SENSITIVE_PATH = (
38
+ r"(?:\.env(?:\.[\w-]+)?|id_rsa|id_ed25519|credentials\.json|service_account\.json|"
39
+ r"\.npmrc|\.pypirc|[\w.-]*\.(?:pem|key)|secrets?\.(?:json|ya?ml|toml|env))"
40
+ )
41
+ _EXFIL_FILE = rf"(?:[\w./~-]*/)?{_EXFIL_SENSITIVE_PATH}"
42
+ _EXFIL_NET = r"(?:sudo\s+)?(?:curl|wget|nc|ncat|netcat)"
43
+
44
+ _EXFIL_PATTERNS = (
45
+ rf"\b{_EXFIL_NET}\b[^;|&\n]*(?:--data(?:-binary|-raw)?|--post-file|-d|-T|--upload-file)(?:[=\s]+)@?['\"]?{_EXFIL_FILE}",
46
+ rf"\b{_EXFIL_NET}\b[^;|&\n]*(?:-F|--form)\s+[^=\s]*=@['\"]?{_EXFIL_FILE}",
47
+ rf"\b{_EXFIL_NET}\b[^;|&\n]*<\s*['\"]?{_EXFIL_FILE}",
48
+ rf"\bcat\s+['\"]?{_EXFIL_FILE}['\"]?\s*\|\s*{_EXFIL_NET}\b",
49
+ # command substitution / backticks reading a sensitive file into the URL
50
+ rf"\b{_EXFIL_NET}\b[^;|&\n]*\$\(\s*(?:cat\s+)?['\"]?{_EXFIL_FILE}",
51
+ rf"\b{_EXFIL_NET}\b[^;|&\n]*`cat\s+['\"]?{_EXFIL_FILE}",
52
+ )
53
+ _EXFIL_COMPILED = tuple(re.compile(p, re.IGNORECASE) for p in _EXFIL_PATTERNS)
54
+
55
+
56
+ def _strip_heredocs(command: str) -> str:
57
+ """Drops heredoc bodies: their text is data for an interpreter, not shell flow."""
58
+ lines = command.splitlines()
59
+ kept = []
60
+ i = 0
61
+ while i < len(lines):
62
+ line = lines[i]
63
+ kept.append(line)
64
+ match = re.search(r"<<-?\s*['\"]?([A-Za-z_]\w*)['\"]?", line)
65
+ if match:
66
+ tag = match.group(1)
67
+ i += 1
68
+ while i < len(lines) and lines[i].strip() != tag:
69
+ i += 1
70
+ i += 1
71
+ return "\n".join(kept)
72
+
73
+
74
+ def _detect_shell_exfiltration(command: str):
75
+ """Returns the offending fragment when a sensitive file is sent to a network client."""
76
+ shell = _strip_heredocs(command or "")
77
+ for pattern in _EXFIL_COMPILED:
78
+ match = pattern.search(shell)
79
+ if match:
80
+ return match.group(0)
81
+ return None
82
+
83
+
26
84
  class GuardResult(NamedTuple):
27
85
  blocked: bool
28
86
  reason: Optional[str] = None
@@ -536,20 +594,15 @@ class TokenSafeGuard:
536
594
  ),
537
595
  )
538
596
 
539
- # 3. Network Data Exfiltration Prevention (piping or posting secrets to curl/wget/nc)
540
- _SENS_EXFIL = r"(?:\.env(?:\.[\w-]+)?|id_rsa|id_ed25519|\.key|\.pem|credentials\.json|service_account\.json|secret|password|token)"
541
- exfil_pattern = re.search(
542
- rf"""(?:\b(?:curl|wget|nc|ncat|netcat)\b.*?(?:\$\(\s*(?:cat\s+)?<?\s*[^)]*{_SENS_EXFIL}[^)]*\)|`cat\s+[^`]*{_SENS_EXFIL}[^`]*`|(?:-d|--data|--data-binary|--data-raw|-T|--upload-file)[=\s]*@?[^\s]*{_SENS_EXFIL}|-F\s+[^=]*=@[^\s]*{_SENS_EXFIL}|--post-file[=\s]+[^\s]*{_SENS_EXFIL}|<\s*[^\s]*{_SENS_EXFIL})|\bcat\s+[^\s|]*{_SENS_EXFIL}\s*\|\s*(?:curl|wget|nc|ncat|netcat)\b)""",
543
- cmd,
544
- re.IGNORECASE
545
- )
546
- if exfil_pattern:
597
+ # 3. Network Data Exfiltration Prevention (uploading sensitive FILES to a network client)
598
+ exfil_hit = _detect_shell_exfiltration(cmd)
599
+ if exfil_hit:
547
600
  return GuardResult(
548
601
  blocked=True,
549
602
  check_name="DATA_EXFILTRATION",
550
603
  reason=(
551
- f"Blocked potential credential exfiltration via network command: '{cmd}'. "
552
- f"Piping or posting local sensitive files (.env / private keys) to remote endpoints is prohibited."
604
+ f"Blocked potential credential exfiltration via network command: '{exfil_hit}'. "
605
+ f"Uploading local sensitive files (.env / private keys) to remote endpoints is prohibited."
553
606
  )
554
607
  )
555
608
 
package/src/mcp_server.py CHANGED
@@ -42,7 +42,7 @@ from src.paths import get_active_workspace, is_plugin_or_system_dir
42
42
 
43
43
  SERVER_INFO = {
44
44
  "name": "tokensafe-mcp",
45
- "version": "4.6.3"
45
+ "version": "4.6.4"
46
46
  }
47
47
 
48
48
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -3173,6 +3173,15 @@ def run_mcp_server():
3173
3173
  "capabilities": {"tools": {}},
3174
3174
  "serverInfo": SERVER_INFO
3175
3175
  }
3176
+ # Routing brief (MCP `instructions`): which stacks this workspace
3177
+ # works through OUMV and which through the TokenSafe tools.
3178
+ try:
3179
+ from src.session_brief import build_workspace_brief
3180
+ brief = build_workspace_brief(os.getcwd(), include_live=False)
3181
+ if brief:
3182
+ response["result"]["instructions"] = brief
3183
+ except Exception:
3184
+ pass
3176
3185
  elif method == "tools/list":
3177
3186
  _TOOLS_LISTED = True
3178
3187
  profile = os.environ.get("TOKENSAFE_MCP_PROFILE", "").strip().lower()
package/src/paths.py CHANGED
@@ -205,6 +205,64 @@ def ensure_tokensafe_gitignore(project_root: Optional[str]) -> bool:
205
205
  return updated
206
206
 
207
207
 
208
+ def ensure_local_git_exclude(project_root: Optional[str]) -> bool:
209
+ """Ignores ``.tokensafe/`` WITHOUT editing any tracked file.
210
+
211
+ ``ensure_tokensafe_gitignore`` appends to the project's ``.gitignore``, which
212
+ is a tracked file — a visible diff in the user's repository. For the
213
+ zero-trace injection flow we instead write to ``$GIT_DIR/info/exclude``
214
+ (local-only, never committed) and drop a self-ignoring
215
+ ``.tokensafe/.gitignore`` so the directory stays invisible even if a future
216
+ ``git add -f`` picks it up.
217
+ """
218
+ if not project_root or not os.path.isdir(project_root):
219
+ return False
220
+
221
+ updated = False
222
+ proj_tokensafe = os.path.join(project_root, ".tokensafe")
223
+ if os.path.isdir(proj_tokensafe):
224
+ inner_ignore = os.path.join(proj_tokensafe, ".gitignore")
225
+ if not os.path.isfile(inner_ignore):
226
+ try:
227
+ with open(inner_ignore, "w", encoding="utf-8") as f:
228
+ f.write("# TokenSafe local runtime artifacts & caches\n*\n!.gitignore\n")
229
+ updated = True
230
+ except Exception:
231
+ pass
232
+
233
+ git_dir = os.path.join(project_root, ".git")
234
+ if os.path.isfile(git_dir):
235
+ # Worktrees/submodules: .git is a file pointing at the real git dir.
236
+ try:
237
+ with open(git_dir, "r", encoding="utf-8") as f:
238
+ pointer = f.read().strip()
239
+ if pointer.startswith("gitdir:"):
240
+ git_dir = os.path.abspath(os.path.join(project_root, pointer.split(":", 1)[1].strip()))
241
+ except Exception:
242
+ pass
243
+ elif not os.path.isdir(git_dir):
244
+ return updated
245
+
246
+ exclude_path = os.path.join(git_dir, "info", "exclude")
247
+ try:
248
+ content = ""
249
+ if os.path.isfile(exclude_path):
250
+ with open(exclude_path, "r", encoding="utf-8", errors="replace") as f:
251
+ content = f.read()
252
+ entries = {ln.strip() for ln in content.splitlines()}
253
+ if not ({".tokensafe/", ".tokensafe"} & entries):
254
+ os.makedirs(os.path.dirname(exclude_path), exist_ok=True)
255
+ with open(exclude_path, "a", encoding="utf-8") as f:
256
+ if content and not content.endswith("\n"):
257
+ f.write("\n")
258
+ f.write("# TokenSafe local runtime artifacts (local-only, never committed)\n.tokensafe/\n")
259
+ updated = True
260
+ except Exception:
261
+ pass
262
+
263
+ return updated
264
+
265
+
208
266
  _PROJECT_MARKER_FILES = (
209
267
  "package.json", "pyproject.toml", "setup.py", "setup.cfg", "requirements.txt",
210
268
  "go.mod", "Cargo.toml", "pom.xml", "build.gradle", "build.gradle.kts",
package/src/retrofit.py CHANGED
@@ -353,6 +353,13 @@ def generate_config(
353
353
  os.makedirs(target_dir, exist_ok=True)
354
354
  with open(target_file, "w", encoding="utf-8") as f:
355
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
356
363
 
357
364
  return config, target_file, True
358
365
 
@@ -468,7 +475,7 @@ def get_adapters_catalog() -> List[Dict[str, Any]]:
468
475
  "technology": {
469
476
  "language": "python",
470
477
  "framework": "fastapi",
471
- "package": {"manager": "pip", "name": "tokensafe-python", "install": "pip install tokensafe-python"},
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"'},
472
479
  },
473
480
  "capabilities": [
474
481
  {"name": "observe.resources", "constraints": {"readOnly": True, "developmentOnly": False}},
@@ -490,8 +497,54 @@ def get_adapters_catalog() -> List[Dict[str, Any]]:
490
497
  ]
491
498
 
492
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
+
493
546
  def run_doctor(workspace_dir: str) -> Dict[str, Any]:
494
- """Diagnostics check for OUMV configuration, ports, lockfiles, and permissions."""
547
+ """Diagnostics for OUMV configuration, detected adapters and agent readiness."""
495
548
  stack = detect_project_stack(workspace_dir)
496
549
  conf_path = os.path.join(workspace_dir, ".tokensafe", "oumv.json")
497
550
  runtime_paths = [
@@ -522,6 +575,34 @@ def run_doctor(workspace_dir: str) -> Dict[str, Any]:
522
575
  except Exception:
523
576
  pass
524
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
+
525
606
  return {
526
607
  "workspace": workspace_dir,
527
608
  "detected_stack": stack,
@@ -529,8 +610,14 @@ def run_doctor(workspace_dir: str) -> Dict[str, Any]:
529
610
  "config": config_data,
530
611
  "runtime_beacon_present": has_runtime,
531
612
  "runtime_beacon": runtime_data,
532
- "permissions": config_data.get("permissions", {"observe": True, "mutate": False}),
533
- "ready_for_agent": True,
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
+ ],
534
621
  }
535
622
 
536
623
 
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
+ }