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
|
@@ -0,0 +1,517 @@
|
|
|
1
|
+
"""Automatic, reversible OUMV adapter wiring ("works out of the box").
|
|
2
|
+
|
|
3
|
+
Two very different injection strategies live here, because the runtimes differ:
|
|
4
|
+
|
|
5
|
+
* **Frontend (React/Vue + Vite)** — nothing is written into the repository. The
|
|
6
|
+
bridge is served by ``tokensafe dev`` (a zero-footprint Vite server with an
|
|
7
|
+
inline config) and discovered through ``~/.tokensafe/runtimes/<hash>.json``.
|
|
8
|
+
* **Python (FastAPI)** — a global ``sitecustomize.py`` in ``~/.tokensafe/pyhooks``
|
|
9
|
+
patches ``uvicorn.importer.import_from_string`` so ``mount_tokensafe(app)`` runs
|
|
10
|
+
as soon as the app object is imported. Zero repository changes; activated only
|
|
11
|
+
by ``TOKENSAFE_OUMV_AUTOMOUNT=1``, which our command wrapper sets.
|
|
12
|
+
* **Go (Gin/Chi/net/http)** — there is no in-process hook, so one line plus one
|
|
13
|
+
import is inserted between ``// tokensafe:oumv:begin/end`` markers. The original
|
|
14
|
+
file is backed up under ``~/.tokensafe/inject/<hash>/`` and ``revert`` restores
|
|
15
|
+
it byte-for-byte. The edited file is validated with ``go build`` before we keep
|
|
16
|
+
it; a failed build reverts automatically.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import hashlib
|
|
22
|
+
import json
|
|
23
|
+
import os
|
|
24
|
+
import re
|
|
25
|
+
import shutil
|
|
26
|
+
import subprocess
|
|
27
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
28
|
+
|
|
29
|
+
from src.retrofit import detect_project_stack, generate_config, get_adapters_catalog
|
|
30
|
+
|
|
31
|
+
_PYHOOKS_DIRNAME = "pyhooks"
|
|
32
|
+
_INJECT_DIRNAME = "inject"
|
|
33
|
+
_MARK_BEGIN = "// tokensafe:oumv:begin"
|
|
34
|
+
_MARK_END = "// tokensafe:oumv:end"
|
|
35
|
+
|
|
36
|
+
_GO_ADAPTERS = {
|
|
37
|
+
"gin": (
|
|
38
|
+
"oumvgin",
|
|
39
|
+
"github.com/tokensafe-dev/tokensafe-backend/go/pkg/adapters/gin",
|
|
40
|
+
"gin.New()",
|
|
41
|
+
"gin.Default()",
|
|
42
|
+
"\toumvgin.AutoMount(r)\n",
|
|
43
|
+
),
|
|
44
|
+
"chi": (
|
|
45
|
+
"oumvchi",
|
|
46
|
+
"github.com/tokensafe-dev/tokensafe-backend/go/pkg/adapters/chi",
|
|
47
|
+
"chi.NewRouter()",
|
|
48
|
+
None,
|
|
49
|
+
"\t_, _ = oumvchi.AutoMount(r)\n",
|
|
50
|
+
),
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _tokensafe_home() -> str:
|
|
55
|
+
return os.environ.get("TOKENSAFE_HOME") or os.path.expanduser("~/.tokensafe")
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _workspace_id(workspace: str) -> str:
|
|
59
|
+
return hashlib.sha256(os.path.realpath(workspace).encode("utf-8")).hexdigest()[:16]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _inject_dir(workspace: str) -> str:
|
|
63
|
+
return os.path.join(_tokensafe_home(), _INJECT_DIRNAME, _workspace_id(workspace))
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def pyhooks_dir() -> str:
|
|
67
|
+
return os.path.join(_tokensafe_home(), _PYHOOKS_DIRNAME)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
# --------------------------------------------------------------------------- #
|
|
71
|
+
# Python autoload (no repository changes)
|
|
72
|
+
# --------------------------------------------------------------------------- #
|
|
73
|
+
|
|
74
|
+
_SITECUSTOMIZE = '''"""TokenSafe OUMV autoload (generated) — see `tokensafe inject --status`.
|
|
75
|
+
|
|
76
|
+
Mounts `mount_tokensafe(app)` on a FastAPI app the moment uvicorn resolves it.
|
|
77
|
+
Inert unless TOKENSAFE_OUMV_AUTOMOUNT=1, which `tokensafe run-backend` sets.
|
|
78
|
+
"""
|
|
79
|
+
import os
|
|
80
|
+
|
|
81
|
+
if os.environ.get("TOKENSAFE_OUMV_AUTOMOUNT") == "1":
|
|
82
|
+
def _install():
|
|
83
|
+
try:
|
|
84
|
+
from tokensafe_python.adapters.fastapi import mount_tokensafe as _mount
|
|
85
|
+
except Exception: # tokensafe-python not installed — nothing to do
|
|
86
|
+
return
|
|
87
|
+
|
|
88
|
+
import uvicorn.importer as _importer
|
|
89
|
+
|
|
90
|
+
if getattr(_importer.import_from_string, "_tokensafe_wrapped", False):
|
|
91
|
+
return
|
|
92
|
+
|
|
93
|
+
_original = _importer.import_from_string
|
|
94
|
+
|
|
95
|
+
def _patched(import_str, *args, **kwargs):
|
|
96
|
+
app = _original(import_str, *args, **kwargs)
|
|
97
|
+
try:
|
|
98
|
+
_mount(app)
|
|
99
|
+
except Exception as exc: # never break the user's server
|
|
100
|
+
import sys
|
|
101
|
+
print(f"[tokensafe] OUMV autoload skipped: {exc}", file=sys.stderr)
|
|
102
|
+
return app
|
|
103
|
+
|
|
104
|
+
_patched._tokensafe_wrapped = True
|
|
105
|
+
_importer.import_from_string = _patched
|
|
106
|
+
|
|
107
|
+
# uvicorn/config.py binds the function by name at import time, so patching
|
|
108
|
+
# the module attribute alone is not enough.
|
|
109
|
+
try:
|
|
110
|
+
import uvicorn.config as _config
|
|
111
|
+
_config.import_from_string = _patched
|
|
112
|
+
except Exception:
|
|
113
|
+
pass
|
|
114
|
+
|
|
115
|
+
_install()
|
|
116
|
+
'''
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def ensure_python_autoload() -> Dict[str, Any]:
|
|
120
|
+
"""Writes the global sitecustomize hook. Returns what was done."""
|
|
121
|
+
target_dir = pyhooks_dir()
|
|
122
|
+
target = os.path.join(target_dir, "sitecustomize.py")
|
|
123
|
+
os.makedirs(target_dir, exist_ok=True)
|
|
124
|
+
current = None
|
|
125
|
+
if os.path.isfile(target):
|
|
126
|
+
with open(target, "r", encoding="utf-8") as f:
|
|
127
|
+
current = f.read()
|
|
128
|
+
if current == _SITECUSTOMIZE:
|
|
129
|
+
return {"status": "unchanged", "path": target}
|
|
130
|
+
with open(target, "w", encoding="utf-8") as f:
|
|
131
|
+
f.write(_SITECUSTOMIZE)
|
|
132
|
+
return {"status": "written", "path": target}
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def python_autoload_present() -> bool:
|
|
136
|
+
target = os.path.join(pyhooks_dir(), "sitecustomize.py")
|
|
137
|
+
try:
|
|
138
|
+
with open(target, "r", encoding="utf-8") as f:
|
|
139
|
+
return f.read() == _SITECUSTOMIZE
|
|
140
|
+
except OSError:
|
|
141
|
+
return False
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def backend_env(env: Optional[Dict[str, str]] = None) -> Dict[str, str]:
|
|
145
|
+
"""Environment that activates the Python autoload hook without touching the repo."""
|
|
146
|
+
base = dict(env if env is not None else os.environ)
|
|
147
|
+
existing = base.get("PYTHONPATH", "")
|
|
148
|
+
hook = pyhooks_dir()
|
|
149
|
+
base["PYTHONPATH"] = f"{hook}{os.pathsep}{existing}" if existing else hook
|
|
150
|
+
base["TOKENSAFE_OUMV_AUTOMOUNT"] = "1"
|
|
151
|
+
return base
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def python_run_hint(workspace: str) -> str:
|
|
155
|
+
"""The command an agent should use to start a FastAPI dev server with OUMV."""
|
|
156
|
+
return (
|
|
157
|
+
f'TOKENSAFE_OUMV_AUTOMOUNT=1 PYTHONPATH="{pyhooks_dir()}:$PYTHONPATH" '
|
|
158
|
+
"uvicorn <module:app> --reload"
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
# --------------------------------------------------------------------------- #
|
|
163
|
+
# Go one-line patch (reversible)
|
|
164
|
+
# --------------------------------------------------------------------------- #
|
|
165
|
+
|
|
166
|
+
def _go_candidates(workspace: str) -> List[str]:
|
|
167
|
+
candidates: List[str] = [os.path.join(workspace, "main.go")]
|
|
168
|
+
for root, dirs, files in os.walk(workspace):
|
|
169
|
+
dirs[:] = [d for d in dirs if d not in {"node_modules", ".git", "vendor", "testdata"}]
|
|
170
|
+
if "main.go" in files and os.sep + "cmd" + os.sep in root + os.sep:
|
|
171
|
+
candidates.append(os.path.join(root, "main.go"))
|
|
172
|
+
return [c for c in candidates if os.path.isfile(c)]
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def find_go_entrypoint(workspace: str, framework: Optional[str] = None) -> Tuple[Optional[str], Optional[str]]:
|
|
176
|
+
"""Returns (path, framework) for the first main.go that looks mountable."""
|
|
177
|
+
for path in _go_candidates(workspace):
|
|
178
|
+
try:
|
|
179
|
+
with open(path, "r", encoding="utf-8", errors="replace") as f:
|
|
180
|
+
source = f.read()
|
|
181
|
+
except OSError:
|
|
182
|
+
continue
|
|
183
|
+
detected = framework
|
|
184
|
+
if not detected:
|
|
185
|
+
if "gin-gonic/gin" in source:
|
|
186
|
+
detected = "gin"
|
|
187
|
+
elif "go-chi/chi" in source:
|
|
188
|
+
detected = "chi"
|
|
189
|
+
elif "tokensafe-dev/tokensafe-backend/go/pkg/adapters/stdhttp" in source:
|
|
190
|
+
detected = "stdhttp"
|
|
191
|
+
# stdhttp's mux is constructed by the adapter itself, so there is no anchor
|
|
192
|
+
# line to patch; those projects get the generated-project recipe instead.
|
|
193
|
+
if detected and detected in _GO_ADAPTERS and "func main(" in source:
|
|
194
|
+
return path, detected
|
|
195
|
+
return None, None
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _go_anchor(source: str, framework: str) -> Optional[int]:
|
|
199
|
+
"""Insertion point: immediately before the server starts listening.
|
|
200
|
+
|
|
201
|
+
Mounting must happen after every route is registered, otherwise L1/L2 observe
|
|
202
|
+
discovers nothing. Fall back to the router-construction line if the entrypoint
|
|
203
|
+
starts the server indirectly.
|
|
204
|
+
"""
|
|
205
|
+
for marker in ("r.Run(", ".ListenAndServe(", "ListenAndServeTLS("):
|
|
206
|
+
idx = source.find(marker)
|
|
207
|
+
if idx != -1:
|
|
208
|
+
return source.rfind("\n", 0, idx) + 1
|
|
209
|
+
|
|
210
|
+
_, _, anchor_a, anchor_b, _ = _GO_ADAPTERS[framework]
|
|
211
|
+
for anchor in (anchor_a, anchor_b):
|
|
212
|
+
if not anchor:
|
|
213
|
+
continue
|
|
214
|
+
idx = source.find(anchor)
|
|
215
|
+
if idx == -1:
|
|
216
|
+
continue
|
|
217
|
+
line_end = source.find("\n", idx)
|
|
218
|
+
return line_end if line_end != -1 else len(source)
|
|
219
|
+
return None
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def go_patch_state(workspace: str) -> Dict[str, Any]:
|
|
223
|
+
path, framework = find_go_entrypoint(workspace)
|
|
224
|
+
if not path:
|
|
225
|
+
return {"patched": False, "entrypoint": None, "framework": None}
|
|
226
|
+
with open(path, "r", encoding="utf-8") as f:
|
|
227
|
+
source = f.read()
|
|
228
|
+
return {
|
|
229
|
+
"patched": _MARK_BEGIN in source,
|
|
230
|
+
"entrypoint": os.path.relpath(path, workspace),
|
|
231
|
+
"framework": framework,
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
_GO_MODULE = "github.com/tokensafe-dev/tokensafe-backend/go"
|
|
236
|
+
_GO_MODULE_VERSION = "v0.4.3"
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _ensure_go_dependency(workspace: str) -> Optional[str]:
|
|
240
|
+
"""Adds the adapter module to go.mod when missing. Returns an error reason or None."""
|
|
241
|
+
go_mod = os.path.join(workspace, "go.mod")
|
|
242
|
+
if not os.path.isfile(go_mod):
|
|
243
|
+
return None
|
|
244
|
+
try:
|
|
245
|
+
with open(go_mod, "r", encoding="utf-8") as f:
|
|
246
|
+
content = f.read()
|
|
247
|
+
except OSError as exc:
|
|
248
|
+
return f"cannot read go.mod: {exc}"
|
|
249
|
+
|
|
250
|
+
# Skip only when the pinned version is already required; an older requirement
|
|
251
|
+
# would build against an adapter that lacks AutoMount.
|
|
252
|
+
match = re.search(re.escape(_GO_MODULE) + r"\s+v([0-9][\w.+-]*)", content)
|
|
253
|
+
if match and f"v{match.group(1)}" == _GO_MODULE_VERSION:
|
|
254
|
+
return None
|
|
255
|
+
|
|
256
|
+
go_bin = shutil.which("go")
|
|
257
|
+
if not go_bin:
|
|
258
|
+
return "go is not on PATH: cannot add the adapter dependency"
|
|
259
|
+
|
|
260
|
+
try:
|
|
261
|
+
proc = subprocess.run(
|
|
262
|
+
[go_bin, "get", f"{_GO_MODULE}@{_GO_MODULE_VERSION}"],
|
|
263
|
+
cwd=workspace,
|
|
264
|
+
capture_output=True,
|
|
265
|
+
text=True,
|
|
266
|
+
timeout=180,
|
|
267
|
+
)
|
|
268
|
+
except Exception as exc: # pragma: no cover - defensive
|
|
269
|
+
return f"go get failed to run: {exc}"
|
|
270
|
+
if proc.returncode != 0:
|
|
271
|
+
output = (proc.stderr or proc.stdout or "").strip().splitlines()
|
|
272
|
+
return "go get failed: " + (output[0] if output else "unknown error")
|
|
273
|
+
return None
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def _go_tidy(workspace: str) -> Tuple[bool, str]:
|
|
277
|
+
"""Runs `go mod tidy` after the import exists (tidy before would drop it)."""
|
|
278
|
+
go_bin = shutil.which("go")
|
|
279
|
+
if not go_bin:
|
|
280
|
+
return True, "go not found on PATH — tidy skipped"
|
|
281
|
+
try:
|
|
282
|
+
proc = subprocess.run(
|
|
283
|
+
[go_bin, "mod", "tidy"],
|
|
284
|
+
cwd=workspace,
|
|
285
|
+
capture_output=True,
|
|
286
|
+
text=True,
|
|
287
|
+
timeout=180,
|
|
288
|
+
)
|
|
289
|
+
except Exception as exc: # pragma: no cover - defensive
|
|
290
|
+
return True, f"tidy failed to run: {exc}"
|
|
291
|
+
return proc.returncode == 0, (proc.stderr or proc.stdout or "").strip()
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def apply_go_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
|
|
295
|
+
"""Ensures the module dependency, inserts the AutoMount call, validates with `go build`.
|
|
296
|
+
|
|
297
|
+
The original file is backed up first and restored byte-for-byte if any step fails.
|
|
298
|
+
"""
|
|
299
|
+
path, framework = find_go_entrypoint(workspace)
|
|
300
|
+
if not path or not framework:
|
|
301
|
+
return {"status": "skipped", "reason": "no mountable Go entrypoint (main.go with gin/chi/net/http) found"}
|
|
302
|
+
|
|
303
|
+
if not dry_run:
|
|
304
|
+
dep_error = _ensure_go_dependency(workspace)
|
|
305
|
+
if dep_error:
|
|
306
|
+
return {"status": "skipped", "reason": dep_error}
|
|
307
|
+
|
|
308
|
+
with open(path, "r", encoding="utf-8") as f:
|
|
309
|
+
original = f.read()
|
|
310
|
+
|
|
311
|
+
if _MARK_BEGIN in original:
|
|
312
|
+
return {"status": "already-patched", "entrypoint": path, "framework": framework}
|
|
313
|
+
|
|
314
|
+
anchor = _go_anchor(original, framework)
|
|
315
|
+
if anchor is None:
|
|
316
|
+
return {
|
|
317
|
+
"status": "skipped",
|
|
318
|
+
"reason": f"could not find router construction ({framework}) in {os.path.relpath(path, workspace)}",
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
alias, import_path, _, _, call = _GO_ADAPTERS[framework]
|
|
322
|
+
insert = f"\t{_MARK_BEGIN}\n{call}\t{_MARK_END}\n"
|
|
323
|
+
patched = original[:anchor] + insert + original[anchor:]
|
|
324
|
+
|
|
325
|
+
import_line = f'\t{alias} "{import_path}"\n'
|
|
326
|
+
if import_path not in patched:
|
|
327
|
+
import_idx = patched.find("import (")
|
|
328
|
+
if import_idx == -1:
|
|
329
|
+
return {"status": "skipped", "reason": "no parenthesised import block to extend"}
|
|
330
|
+
line_end = patched.find("\n", import_idx)
|
|
331
|
+
patched = patched[: line_end + 1] + import_line + patched[line_end + 1 :]
|
|
332
|
+
|
|
333
|
+
if dry_run:
|
|
334
|
+
return {
|
|
335
|
+
"status": "would-patch",
|
|
336
|
+
"entrypoint": os.path.relpath(path, workspace),
|
|
337
|
+
"framework": framework,
|
|
338
|
+
"preview": insert.strip(),
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
backup_dir = _inject_dir(workspace)
|
|
342
|
+
os.makedirs(backup_dir, exist_ok=True)
|
|
343
|
+
suffix = os.path.relpath(path, workspace).replace(os.sep, "__") + ".bak"
|
|
344
|
+
backup_path = os.path.join(backup_dir, suffix)
|
|
345
|
+
shutil.copy2(path, backup_path)
|
|
346
|
+
module_backups: List[Tuple[str, str]] = []
|
|
347
|
+
for mod_file in ("go.mod", "go.sum"):
|
|
348
|
+
src = os.path.join(workspace, mod_file)
|
|
349
|
+
if os.path.isfile(src):
|
|
350
|
+
dst = os.path.join(backup_dir, mod_file + ".bak")
|
|
351
|
+
shutil.copy2(src, dst)
|
|
352
|
+
module_backups.append((src, dst))
|
|
353
|
+
|
|
354
|
+
with open(path, "w", encoding="utf-8") as f:
|
|
355
|
+
f.write(patched)
|
|
356
|
+
|
|
357
|
+
tidy_ok, tidy_output = _go_tidy(workspace)
|
|
358
|
+
build_ok, build_output = _go_build(workspace) if tidy_ok else (False, tidy_output)
|
|
359
|
+
if not build_ok:
|
|
360
|
+
shutil.copy2(backup_path, path)
|
|
361
|
+
for src, dst in module_backups:
|
|
362
|
+
shutil.copy2(dst, src)
|
|
363
|
+
first_error = next((line for line in build_output.splitlines() if line.strip()), "")
|
|
364
|
+
return {
|
|
365
|
+
"status": "reverted",
|
|
366
|
+
"reason": "go build failed after the patch — original file restored"
|
|
367
|
+
+ (f" ({first_error.strip()})" if first_error else ""),
|
|
368
|
+
"build_output": build_output[-1200:],
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
with open(os.path.join(backup_dir, "manifest.json"), "w", encoding="utf-8") as f:
|
|
372
|
+
json.dump({"entrypoint": path, "backup": backup_path, "framework": framework}, f, indent=2)
|
|
373
|
+
|
|
374
|
+
return {
|
|
375
|
+
"status": "patched",
|
|
376
|
+
"entrypoint": os.path.relpath(path, workspace),
|
|
377
|
+
"framework": framework,
|
|
378
|
+
"backup": backup_path,
|
|
379
|
+
"line": call.strip(),
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def _go_build(workspace: str) -> Tuple[bool, str]:
|
|
384
|
+
go_bin = shutil.which("go")
|
|
385
|
+
if not go_bin:
|
|
386
|
+
return True, "go not found on PATH — build validation skipped"
|
|
387
|
+
try:
|
|
388
|
+
proc = subprocess.run(
|
|
389
|
+
[go_bin, "build", "./..."],
|
|
390
|
+
cwd=workspace,
|
|
391
|
+
capture_output=True,
|
|
392
|
+
text=True,
|
|
393
|
+
timeout=120,
|
|
394
|
+
)
|
|
395
|
+
return proc.returncode == 0, (proc.stderr or proc.stdout or "").strip()
|
|
396
|
+
except Exception as exc: # pragma: no cover - defensive
|
|
397
|
+
return True, f"build validation failed to run: {exc}"
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def revert_go_patch(workspace: str) -> Dict[str, Any]:
|
|
401
|
+
manifest_path = os.path.join(_inject_dir(workspace), "manifest.json")
|
|
402
|
+
if not os.path.isfile(manifest_path):
|
|
403
|
+
return {"status": "nothing-to-revert"}
|
|
404
|
+
with open(manifest_path, "r", encoding="utf-8") as f:
|
|
405
|
+
manifest = json.load(f)
|
|
406
|
+
target = manifest.get("entrypoint")
|
|
407
|
+
backup = manifest.get("backup")
|
|
408
|
+
if not target or not backup or not os.path.isfile(backup):
|
|
409
|
+
return {"status": "error", "reason": "backup missing"}
|
|
410
|
+
shutil.copy2(backup, target)
|
|
411
|
+
os.remove(manifest_path)
|
|
412
|
+
return {"status": "reverted", "entrypoint": os.path.relpath(target, workspace)}
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
# --------------------------------------------------------------------------- #
|
|
416
|
+
# Plan / apply / revert for the CLI and the first-prompt hook
|
|
417
|
+
# --------------------------------------------------------------------------- #
|
|
418
|
+
|
|
419
|
+
def plan(workspace: str) -> Dict[str, Any]:
|
|
420
|
+
"""Describes what apply would do, without touching anything."""
|
|
421
|
+
stack = detect_project_stack(workspace)
|
|
422
|
+
catalog = {entry["id"]: entry for entry in get_adapters_catalog()}
|
|
423
|
+
actions: List[Dict[str, Any]] = []
|
|
424
|
+
|
|
425
|
+
frontend = stack.get("frontend")
|
|
426
|
+
if frontend:
|
|
427
|
+
actions.append({
|
|
428
|
+
"kind": "frontend_zero_footprint",
|
|
429
|
+
"profile": "frontend",
|
|
430
|
+
"framework": f"{frontend.get('provider')}/{frontend.get('framework')}",
|
|
431
|
+
"writes_repo": False,
|
|
432
|
+
"description": "served by `tokensafe dev` (inline Vite config, descriptor in ~/.tokensafe/runtimes)",
|
|
433
|
+
"run": "tokensafe dev",
|
|
434
|
+
"install": catalog.get("frontend/react", {}).get("technology", {}).get("package", {}).get("install"),
|
|
435
|
+
})
|
|
436
|
+
|
|
437
|
+
backend = stack.get("backend")
|
|
438
|
+
if backend:
|
|
439
|
+
provider = backend.get("provider")
|
|
440
|
+
entry_id = "backend/fastapi" if provider == "fastapi" else "backend/go"
|
|
441
|
+
entry = catalog.get(entry_id, {})
|
|
442
|
+
if provider == "fastapi":
|
|
443
|
+
actions.append({
|
|
444
|
+
"kind": "python_autoload",
|
|
445
|
+
"profile": "backend",
|
|
446
|
+
"framework": "fastapi",
|
|
447
|
+
"writes_repo": False,
|
|
448
|
+
"description": "sitecustomize patches uvicorn; mount_tokensafe(app) runs on import",
|
|
449
|
+
"install": entry.get("technology", {}).get("package", {}).get("install", 'pip install "tokensafe-backend-python @ git+https://github.com/tokensafe-dev/tokensafe-backend.git#subdirectory=python"'),
|
|
450
|
+
"run": python_run_hint(workspace),
|
|
451
|
+
})
|
|
452
|
+
elif provider == "go":
|
|
453
|
+
state = go_patch_state(workspace)
|
|
454
|
+
actions.append({
|
|
455
|
+
"kind": "go_one_line_patch",
|
|
456
|
+
"profile": "backend",
|
|
457
|
+
"framework": backend.get("framework", "go"),
|
|
458
|
+
"writes_repo": True,
|
|
459
|
+
"already_patched": state["patched"],
|
|
460
|
+
"entrypoint": state["entrypoint"],
|
|
461
|
+
"description": "one AutoMount() line between tokensafe markers; byte-exact backup + --revert",
|
|
462
|
+
"install": entry.get("technology", {}).get("package", {}).get("install"),
|
|
463
|
+
})
|
|
464
|
+
else:
|
|
465
|
+
actions.append({
|
|
466
|
+
"kind": "unsupported",
|
|
467
|
+
"profile": "backend",
|
|
468
|
+
"framework": backend.get("framework"),
|
|
469
|
+
"writes_repo": False,
|
|
470
|
+
"description": "no OUMV adapter for this stack yet — use tokensafe tools instead",
|
|
471
|
+
})
|
|
472
|
+
|
|
473
|
+
return {
|
|
474
|
+
"workspace": workspace,
|
|
475
|
+
"profiles": [p for p in ("frontend", "backend") if stack.get(p)],
|
|
476
|
+
"actions": actions,
|
|
477
|
+
"python_autoload_present": python_autoload_present(),
|
|
478
|
+
"revertable": os.path.isfile(os.path.join(_inject_dir(workspace), "manifest.json")),
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
|
|
482
|
+
def apply(workspace: str, dry_run: bool = False, include_go: bool = True) -> Dict[str, Any]:
|
|
483
|
+
"""Wires everything that can be wired without leaving a git trace."""
|
|
484
|
+
results: Dict[str, Any] = {"workspace": workspace, "actions": []}
|
|
485
|
+
|
|
486
|
+
config, conf_path, created = generate_config(workspace, dry_run=dry_run)
|
|
487
|
+
results["config"] = {
|
|
488
|
+
"path": conf_path,
|
|
489
|
+
"created": created,
|
|
490
|
+
"mutate": config.get("permissions", {}).get("mutate", True),
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
stack = detect_project_stack(workspace)
|
|
494
|
+
if stack.get("frontend"):
|
|
495
|
+
results["actions"].append({
|
|
496
|
+
"kind": "frontend_zero_footprint",
|
|
497
|
+
"status": "ready",
|
|
498
|
+
"run": "tokensafe dev",
|
|
499
|
+
"note": "no repository files are written; the bridge lives in the dev-server wrapper",
|
|
500
|
+
})
|
|
501
|
+
|
|
502
|
+
backend = stack.get("backend") or {}
|
|
503
|
+
if backend.get("provider") == "fastapi":
|
|
504
|
+
if dry_run:
|
|
505
|
+
results["actions"].append({"kind": "python_autoload", "status": "would-write", "path": os.path.join(pyhooks_dir(), "sitecustomize.py")})
|
|
506
|
+
else:
|
|
507
|
+
written = ensure_python_autoload()
|
|
508
|
+
results["actions"].append({"kind": "python_autoload", **written, "run": python_run_hint(workspace)})
|
|
509
|
+
|
|
510
|
+
if backend.get("provider") == "go" and include_go:
|
|
511
|
+
results["actions"].append({"kind": "go_one_line_patch", **apply_go_patch(workspace, dry_run=dry_run)})
|
|
512
|
+
|
|
513
|
+
return results
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
def revert(workspace: str) -> Dict[str, Any]:
|
|
517
|
+
return {"workspace": workspace, "go": revert_go_patch(workspace)}
|
package/src/batch_editor.py
CHANGED
|
@@ -452,6 +452,7 @@ def execute_batch_edits(
|
|
|
452
452
|
"allow_overwrite": overwrite,
|
|
453
453
|
"hunk_count": 0,
|
|
454
454
|
"noop_hunks": 0,
|
|
455
|
+
"clamped_hunks": 0,
|
|
455
456
|
}
|
|
456
457
|
continue
|
|
457
458
|
|
|
@@ -465,6 +466,7 @@ def execute_batch_edits(
|
|
|
465
466
|
current_text = prior_prepared["new_content"]
|
|
466
467
|
prev_hunk_count = prior_prepared["hunk_count"]
|
|
467
468
|
prev_noop_count = prior_prepared.get("noop_hunks", 0)
|
|
469
|
+
prev_clamped_count = prior_prepared.get("clamped_hunks", 0)
|
|
468
470
|
is_create = prior_prepared["is_create"]
|
|
469
471
|
else:
|
|
470
472
|
if not os.path.exists(abs_path):
|
|
@@ -486,11 +488,14 @@ def execute_batch_edits(
|
|
|
486
488
|
continue
|
|
487
489
|
prev_hunk_count = 0
|
|
488
490
|
prev_noop_count = 0
|
|
491
|
+
prev_clamped_count = 0
|
|
489
492
|
is_create = False
|
|
490
493
|
|
|
491
494
|
file_failed = False
|
|
492
495
|
applied_hunk_count = 0
|
|
493
496
|
noop_hunk_count = prev_noop_count
|
|
497
|
+
clamped_hunk_count = 0
|
|
498
|
+
hunk_clamped = False
|
|
494
499
|
|
|
495
500
|
for hunk_idx, hunk in enumerate(hunks):
|
|
496
501
|
if not isinstance(hunk, dict):
|
|
@@ -524,6 +529,15 @@ def execute_batch_edits(
|
|
|
524
529
|
file_failed = True
|
|
525
530
|
break
|
|
526
531
|
|
|
532
|
+
# Clamp end_line beyond EOF: clients routinely read N lines and pass
|
|
533
|
+
# start+limit, and a hard error costs a whole extra turn. The result
|
|
534
|
+
# reports clamped_hunks so a shrunken region is never silent.
|
|
535
|
+
if e_val is not None and e_val > 0:
|
|
536
|
+
line_count = len(current_text.splitlines(keepends=True))
|
|
537
|
+
if e_val > line_count:
|
|
538
|
+
e_val = line_count
|
|
539
|
+
hunk_clamped = True
|
|
540
|
+
|
|
527
541
|
new_text, err = _apply_hunk_to_text(
|
|
528
542
|
current_text,
|
|
529
543
|
target=str(target),
|
|
@@ -544,6 +558,9 @@ def execute_batch_edits(
|
|
|
544
558
|
|
|
545
559
|
current_text = new_text
|
|
546
560
|
applied_hunk_count += 1
|
|
561
|
+
if hunk_clamped:
|
|
562
|
+
clamped_hunk_count += 1
|
|
563
|
+
hunk_clamped = False
|
|
547
564
|
|
|
548
565
|
if not file_failed:
|
|
549
566
|
prepared_files[abs_path] = {
|
|
@@ -552,6 +569,7 @@ def execute_batch_edits(
|
|
|
552
569
|
"is_create": is_create,
|
|
553
570
|
"hunk_count": prev_hunk_count + applied_hunk_count,
|
|
554
571
|
"noop_hunks": noop_hunk_count,
|
|
572
|
+
"clamped_hunks": prev_clamped_count + clamped_hunk_count,
|
|
555
573
|
}
|
|
556
574
|
|
|
557
575
|
# Atomic enforcement: if any file failed and not best_effort, reject all
|
|
@@ -589,6 +607,18 @@ def execute_batch_edits(
|
|
|
589
607
|
write_aborted = False
|
|
590
608
|
for abs_p, p_info in prepared_files.items():
|
|
591
609
|
try:
|
|
610
|
+
if p_info["hunk_count"] == 0 and not p_info["is_create"]:
|
|
611
|
+
# Pure no-op batch entry: report it, but never rewrite identical
|
|
612
|
+
# bytes (that would bump mtime/inode and invalidate readers).
|
|
613
|
+
applied_files_info.append({
|
|
614
|
+
"path": p_info["rel_path"],
|
|
615
|
+
"hunks": 0,
|
|
616
|
+
"noop_hunks": p_info.get("noop_hunks", 0),
|
|
617
|
+
"clamped_hunks": p_info.get("clamped_hunks", 0),
|
|
618
|
+
"is_create": False,
|
|
619
|
+
"unchanged": True,
|
|
620
|
+
})
|
|
621
|
+
continue
|
|
592
622
|
existed = os.path.exists(abs_p)
|
|
593
623
|
orig_bytes: Optional[bytes] = None
|
|
594
624
|
orig_mode: Optional[int] = None
|
|
@@ -610,6 +640,7 @@ def execute_batch_edits(
|
|
|
610
640
|
"path": p_info["rel_path"],
|
|
611
641
|
"hunks": p_info["hunk_count"],
|
|
612
642
|
"noop_hunks": p_info.get("noop_hunks", 0),
|
|
643
|
+
"clamped_hunks": p_info.get("clamped_hunks", 0),
|
|
613
644
|
"is_create": not existed,
|
|
614
645
|
})
|
|
615
646
|
except Exception as e:
|
|
@@ -627,14 +658,17 @@ def execute_batch_edits(
|
|
|
627
658
|
"path": p_info["rel_path"],
|
|
628
659
|
"hunks": p_info["hunk_count"],
|
|
629
660
|
"noop_hunks": p_info.get("noop_hunks", 0),
|
|
661
|
+
"clamped_hunks": p_info.get("clamped_hunks", 0),
|
|
630
662
|
"is_create": p_info["is_create"],
|
|
631
663
|
"dry_run": True
|
|
632
664
|
})
|
|
633
665
|
|
|
666
|
+
total_changed_hunks = sum(int(p.get("hunk_count") or 0) for p in prepared_files.values())
|
|
634
667
|
result: Dict[str, Any] = {
|
|
635
668
|
"success": len(applied_files_info) > 0 and len(failed_files) == 0,
|
|
636
669
|
"applied_count": len(applied_files_info),
|
|
637
670
|
"applied_files": applied_files_info,
|
|
671
|
+
"changed_hunks": total_changed_hunks,
|
|
638
672
|
"failed_count": len(failed_files),
|
|
639
673
|
"failed_files": failed_files,
|
|
640
674
|
"dry_run": dry_run,
|
|
@@ -655,8 +689,8 @@ def execute_batch_edits(
|
|
|
655
689
|
if isinstance(result.get("verify"), dict):
|
|
656
690
|
result["verify"]["rolled_back"] = True
|
|
657
691
|
|
|
658
|
-
# Execute inline verify command if requested and
|
|
659
|
-
if verified_argv and applied_files_info and not dry_run:
|
|
692
|
+
# Execute inline verify command if requested and at least one byte actually changed
|
|
693
|
+
if verified_argv and applied_files_info and not dry_run and total_changed_hunks > 0:
|
|
660
694
|
cmd_str = str(verify).strip()
|
|
661
695
|
t0 = time.time()
|
|
662
696
|
try:
|