tokensafe 4.12.4 → 4.13.2
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 +8 -6
- package/hooks/pre_invocation.py +8 -4
- package/kimi.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/rules/AGENTS.md +4 -3
- package/server.json +3 -3
- package/src/auto_inject.py +1070 -283
- package/src/backend_release.py +10 -0
- package/src/batch_editor.py +18 -8
- package/src/batch_search.py +39 -16
- package/src/bundle_probe.py +205 -0
- package/src/cli.py +76 -7
- package/src/fts_index.py +9 -0
- package/src/globmatch.py +124 -0
- package/src/governor.py +120 -44
- package/src/graph_engine.py +292 -14
- package/src/installer.py +3 -3
- package/src/mcp_server.py +153 -35
- package/src/metrics.py +7 -0
- package/src/oumv_brief.py +346 -0
- package/src/oumv_gateway.py +132 -43
- package/src/quality_score.py +46 -24
- package/src/retrofit.py +35 -11
- package/src/savings.py +1 -0
- package/src/scoped_search.py +238 -9
- package/src/session_brief.py +6 -1
- package/src/telemetry_sync.py +1 -1
- package/src/treesitter_backend.py +26 -1
- package/src/version_checker.py +1 -1
- package/src/web_reader.py +42 -0
- package/src/workspace_roots.py +246 -0
package/src/auto_inject.py
CHANGED
|
@@ -9,11 +9,17 @@ Two very different injection strategies live here, because the runtimes differ:
|
|
|
9
9
|
patches ``uvicorn.importer.import_from_string`` so ``mount_tokensafe(app)`` runs
|
|
10
10
|
as soon as the app object is imported. Zero repository changes; activated only
|
|
11
11
|
by ``TOKENSAFE_OUMV_AUTOMOUNT=1``, which our command wrapper sets.
|
|
12
|
-
* **Go (Gin/Chi
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
12
|
+
* **Go (Gin/Chi)** — there is no in-process hook, so one line plus one import is
|
|
13
|
+
inserted between ``// tokensafe:oumv:begin/end`` markers. The original file is
|
|
14
|
+
backed up under ``~/.tokensafe/inject/<hash>/`` and ``revert`` restores it
|
|
15
|
+
byte-for-byte, including ``go.mod``/``go.sum`` when they were not edited after
|
|
16
|
+
inject. The edited file is validated with ``go build`` before we keep it; a
|
|
17
|
+
failed build reverts automatically. ``net/http`` has no anchor line to patch
|
|
18
|
+
(the adapter constructs the mux), so its plan is an explicit manual recipe;
|
|
19
|
+
Echo has no adapter yet and is reported as planned.
|
|
20
|
+
|
|
21
|
+
Every detected app gets its own manifest (``manifests/<kind>--<app>.json``), so a
|
|
22
|
+
monorepo is wired app by app and one ``--revert`` undoes all of them.
|
|
17
23
|
"""
|
|
18
24
|
|
|
19
25
|
from __future__ import annotations
|
|
@@ -28,7 +34,7 @@ import subprocess
|
|
|
28
34
|
from typing import Any, Dict, List, Optional, Tuple
|
|
29
35
|
|
|
30
36
|
from src import oumv_policy
|
|
31
|
-
from src.backend_release import BACKEND_RELEASE_TAG
|
|
37
|
+
from src.backend_release import BACKEND_DOTNET_VERSION, BACKEND_NPM_VERSION, BACKEND_RELEASE_TAG
|
|
32
38
|
from src.retrofit import detect_project_stack, generate_config, get_adapters_catalog
|
|
33
39
|
|
|
34
40
|
_PYHOOKS_DIRNAME = "pyhooks"
|
|
@@ -36,6 +42,15 @@ _INJECT_DIRNAME = "inject"
|
|
|
36
42
|
_MARK_BEGIN = "// tokensafe:oumv:begin"
|
|
37
43
|
_MARK_END = "// tokensafe:oumv:end"
|
|
38
44
|
|
|
45
|
+
# net/http has no Anchor line to patch: the adapter constructs the mux itself.
|
|
46
|
+
# The plan shows this recipe and apply() never rewrites the user's main.go.
|
|
47
|
+
_GO_MANUAL_SNIPPET = '''rt := oumv.NewRuntime(oumv.Config{Name: "app"})
|
|
48
|
+
mux := oumvstdhttp.NewServeMux(rt)
|
|
49
|
+
mux.Mount("/__oumv/rpc")
|
|
50
|
+
// imports:
|
|
51
|
+
// oumv "github.com/tokensafe-dev/tokensafe-backend/go/pkg/oumv"
|
|
52
|
+
// oumvstdhttp "github.com/tokensafe-dev/tokensafe-backend/go/pkg/adapters/stdhttp"'''
|
|
53
|
+
|
|
39
54
|
_GO_ADAPTERS = {
|
|
40
55
|
"gin": (
|
|
41
56
|
"oumvgin",
|
|
@@ -66,24 +81,27 @@ def _inject_dir(workspace: str) -> str:
|
|
|
66
81
|
return os.path.join(_tokensafe_home(), _INJECT_DIRNAME, _workspace_id(workspace))
|
|
67
82
|
|
|
68
83
|
|
|
69
|
-
def _manifest_path(workspace: str, kind: str) -> str:
|
|
70
|
-
"""One manifest per adapter kind
|
|
71
|
-
|
|
72
|
-
|
|
84
|
+
def _manifest_path(workspace: str, kind: str, app: str = ".") -> str:
|
|
85
|
+
"""One manifest per adapter kind *and app*: a monorepo can carry several Go
|
|
86
|
+
services at once, and a single shared file would lose the first one's backup."""
|
|
87
|
+
suffix = ""
|
|
88
|
+
if app and app not in (".", ""):
|
|
89
|
+
suffix = "--" + hashlib.sha256(app.encode("utf-8")).hexdigest()[:12]
|
|
90
|
+
return os.path.join(_inject_dir(workspace), "manifests", f"{kind}{suffix}.json")
|
|
73
91
|
|
|
74
92
|
|
|
75
93
|
def _write_manifest(workspace: str, kind: str, payload: Dict[str, Any]) -> str:
|
|
76
|
-
path = _manifest_path(workspace, kind)
|
|
94
|
+
path = _manifest_path(workspace, kind, payload.get("app") or ".")
|
|
77
95
|
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
78
96
|
with open(path, "w", encoding="utf-8") as f:
|
|
79
97
|
json.dump(payload, f, indent=2)
|
|
80
98
|
return path
|
|
81
99
|
|
|
82
100
|
|
|
83
|
-
def _read_manifest(workspace: str, kind: str, legacy_modes: tuple) -> Optional[Dict[str, Any]]:
|
|
101
|
+
def _read_manifest(workspace: str, kind: str, legacy_modes: tuple, app: str = ".") -> Optional[Dict[str, Any]]:
|
|
84
102
|
"""Own manifest first; a legacy single manifest.json only when its mode belongs
|
|
85
103
|
to this adapter (the old file was shared by every kind)."""
|
|
86
|
-
own = _manifest_path(workspace, kind)
|
|
104
|
+
own = _manifest_path(workspace, kind, app)
|
|
87
105
|
if os.path.isfile(own):
|
|
88
106
|
try:
|
|
89
107
|
with open(own, "r", encoding="utf-8") as f:
|
|
@@ -92,6 +110,10 @@ def _read_manifest(workspace: str, kind: str, legacy_modes: tuple) -> Optional[D
|
|
|
92
110
|
return data
|
|
93
111
|
except Exception:
|
|
94
112
|
return None
|
|
113
|
+
# The shared legacy file belongs to the workspace root only; a nested app
|
|
114
|
+
# must never consume the root app's backup.
|
|
115
|
+
if app not in (".", ""):
|
|
116
|
+
return None
|
|
95
117
|
legacy = os.path.join(_inject_dir(workspace), "manifest.json")
|
|
96
118
|
if os.path.isfile(legacy):
|
|
97
119
|
try:
|
|
@@ -111,6 +133,21 @@ def _delete_manifest(manifest: Dict[str, Any]) -> None:
|
|
|
111
133
|
os.unlink(path)
|
|
112
134
|
|
|
113
135
|
|
|
136
|
+
def _backup_path(workspace: str, path: str) -> str:
|
|
137
|
+
"""Byte-exact backup location for one patched source file."""
|
|
138
|
+
return os.path.join(
|
|
139
|
+
_inject_dir(workspace),
|
|
140
|
+
os.path.relpath(path, workspace).replace(os.sep, "__") + ".bak",
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _app_root(workspace: str, root: Optional[str]) -> str:
|
|
145
|
+
"""Absolute directory of one detected app; `.` is the workspace itself."""
|
|
146
|
+
if not root or root in (".", ""):
|
|
147
|
+
return os.path.abspath(workspace)
|
|
148
|
+
return os.path.abspath(os.path.join(workspace, root))
|
|
149
|
+
|
|
150
|
+
|
|
114
151
|
def pyhooks_dir() -> str:
|
|
115
152
|
return os.path.join(_tokensafe_home(), _PYHOOKS_DIRNAME)
|
|
116
153
|
|
|
@@ -195,6 +232,83 @@ def python_autoload_present() -> bool:
|
|
|
195
232
|
return False
|
|
196
233
|
|
|
197
234
|
|
|
235
|
+
def revert_python_autoload(
|
|
236
|
+
workspace: str, manifest: Optional[Dict[str, Any]] = None
|
|
237
|
+
) -> Dict[str, Any]:
|
|
238
|
+
"""Removes the global hook only when no other workspace still uses it."""
|
|
239
|
+
if manifest is None:
|
|
240
|
+
manifest = _read_manifest(workspace, "python", ("python_autoload",))
|
|
241
|
+
if manifest is None:
|
|
242
|
+
return {"status": "clean", "reason": "no Python autoload manifest"}
|
|
243
|
+
_delete_manifest(manifest)
|
|
244
|
+
others = glob.glob(
|
|
245
|
+
os.path.join(_tokensafe_home(), _INJECT_DIRNAME, "*", "manifests", "python*.json")
|
|
246
|
+
)
|
|
247
|
+
if others:
|
|
248
|
+
return {"status": "kept", "reason": f"{len(others)} other workspace manifest(s) still use it"}
|
|
249
|
+
target = os.path.join(pyhooks_dir(), "sitecustomize.py")
|
|
250
|
+
if not os.path.isfile(target):
|
|
251
|
+
return {"status": "absent"}
|
|
252
|
+
try:
|
|
253
|
+
with open(target, "r", encoding="utf-8") as f:
|
|
254
|
+
current = f.read()
|
|
255
|
+
except OSError:
|
|
256
|
+
return {"status": "error", "reason": "cannot read sitecustomize.py"}
|
|
257
|
+
if current != _SITECUSTOMIZE:
|
|
258
|
+
return {"status": "modified", "path": target}
|
|
259
|
+
os.remove(target)
|
|
260
|
+
return {"status": "removed", "path": target}
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def _config_state_path(workspace: str) -> str:
|
|
264
|
+
return os.path.join(_inject_dir(workspace), "config.json")
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _write_config_state(workspace: str, path: str, created: bool) -> None:
|
|
268
|
+
state_path = _config_state_path(workspace)
|
|
269
|
+
os.makedirs(os.path.dirname(state_path), exist_ok=True)
|
|
270
|
+
previous: Dict[str, Any] = {}
|
|
271
|
+
if os.path.isfile(state_path):
|
|
272
|
+
try:
|
|
273
|
+
with open(state_path, "r", encoding="utf-8") as handle:
|
|
274
|
+
previous = json.load(handle)
|
|
275
|
+
except Exception:
|
|
276
|
+
previous = {}
|
|
277
|
+
owned = bool(created)
|
|
278
|
+
sha = _sha256_file(path) if created and path and os.path.isfile(path) else None
|
|
279
|
+
# A second `inject` sees the file it created and would otherwise record
|
|
280
|
+
# `created: false`, leaving the config behind after --revert.
|
|
281
|
+
if not owned and previous.get("created") and previous.get("path") == path:
|
|
282
|
+
owned = True
|
|
283
|
+
sha = previous.get("sha") or (_sha256_file(path) if path and os.path.isfile(path) else None)
|
|
284
|
+
payload = {"path": path, "created": owned, "sha": sha}
|
|
285
|
+
with open(state_path, "w", encoding="utf-8") as handle:
|
|
286
|
+
json.dump(payload, handle, indent=2)
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def revert_config(workspace: str) -> Dict[str, Any]:
|
|
290
|
+
"""Removes .tokensafe/oumv.json only when inject created it and it is unchanged."""
|
|
291
|
+
state_path = _config_state_path(workspace)
|
|
292
|
+
if not os.path.isfile(state_path):
|
|
293
|
+
return {"status": "nothing-to-revert"}
|
|
294
|
+
try:
|
|
295
|
+
with open(state_path, "r", encoding="utf-8") as handle:
|
|
296
|
+
state = json.load(handle)
|
|
297
|
+
except Exception:
|
|
298
|
+
return {"status": "error", "reason": "unreadable config state"}
|
|
299
|
+
os.unlink(state_path)
|
|
300
|
+
path = state.get("path")
|
|
301
|
+
if not state.get("created"):
|
|
302
|
+
return {"status": "preserved", "reason": "config existed before inject"}
|
|
303
|
+
if not path or not os.path.isfile(path):
|
|
304
|
+
return {"status": "absent"}
|
|
305
|
+
sha = state.get("sha")
|
|
306
|
+
if sha and _sha256_file(path) != sha:
|
|
307
|
+
return {"status": "config_modified", "path": path}
|
|
308
|
+
os.remove(path)
|
|
309
|
+
return {"status": "removed", "path": path}
|
|
310
|
+
|
|
311
|
+
|
|
198
312
|
def backend_env(env: Optional[Dict[str, str]] = None) -> Dict[str, str]:
|
|
199
313
|
"""Environment that activates the Python autoload hook without touching the repo."""
|
|
200
314
|
base = dict(env if env is not None else os.environ)
|
|
@@ -232,7 +346,11 @@ def _go_candidates(workspace: str) -> List[str]:
|
|
|
232
346
|
|
|
233
347
|
|
|
234
348
|
def find_go_entrypoint(workspace: str, framework: Optional[str] = None) -> Tuple[Optional[str], Optional[str]]:
|
|
235
|
-
"""Returns (path, framework) for the first main.go that looks mountable.
|
|
349
|
+
"""Returns (path, framework) for the first main.go that looks mountable.
|
|
350
|
+
|
|
351
|
+
`nethttp`/`stdhttp` are returned too: they cannot be auto-patched, but a
|
|
352
|
+
silent miss reads as "no Go app" when the honest answer is a manual recipe.
|
|
353
|
+
"""
|
|
236
354
|
for path in _go_candidates(workspace):
|
|
237
355
|
try:
|
|
238
356
|
with open(path, "r", encoding="utf-8", errors="replace") as f:
|
|
@@ -247,9 +365,11 @@ def find_go_entrypoint(workspace: str, framework: Optional[str] = None) -> Tuple
|
|
|
247
365
|
detected = "chi"
|
|
248
366
|
elif "tokensafe-dev/tokensafe-backend/go/pkg/adapters/stdhttp" in source:
|
|
249
367
|
detected = "stdhttp"
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
if detected
|
|
368
|
+
elif "http.NewServeMux(" in source:
|
|
369
|
+
detected = "nethttp"
|
|
370
|
+
if detected in _GO_ADAPTERS and "func main(" in source:
|
|
371
|
+
return path, detected
|
|
372
|
+
if detected in ("stdhttp", "nethttp") and "func main(" in source:
|
|
253
373
|
return path, detected
|
|
254
374
|
return None, None
|
|
255
375
|
|
|
@@ -278,8 +398,8 @@ def _go_anchor(source: str, framework: str) -> Optional[int]:
|
|
|
278
398
|
return None
|
|
279
399
|
|
|
280
400
|
|
|
281
|
-
def go_patch_state(workspace: str) -> Dict[str, Any]:
|
|
282
|
-
path, framework = find_go_entrypoint(workspace)
|
|
401
|
+
def go_patch_state(workspace: str, root: str = ".") -> Dict[str, Any]:
|
|
402
|
+
path, framework = find_go_entrypoint(_app_root(workspace, root))
|
|
283
403
|
if not path:
|
|
284
404
|
return {"patched": False, "entrypoint": None, "framework": None}
|
|
285
405
|
with open(path, "r", encoding="utf-8") as f:
|
|
@@ -417,6 +537,51 @@ def _wrap_go_serve(source: str, framework: str) -> Optional[Tuple[str, str]]:
|
|
|
417
537
|
return None
|
|
418
538
|
|
|
419
539
|
|
|
540
|
+
def _go_origin_from_addr(addr: str, scheme: str = "http") -> Optional[str]:
|
|
541
|
+
"""`":8080"` / `"0.0.0.0:8080"` -> `http://127.0.0.1:8080`; dynamic addrs -> None."""
|
|
542
|
+
addr = str(addr or "").strip().strip('"').strip()
|
|
543
|
+
if not addr or "(" in addr or "$" in addr:
|
|
544
|
+
return None
|
|
545
|
+
host, sep, port = addr.rpartition(":")
|
|
546
|
+
if not sep or not port.isdigit() or int(port) == 0:
|
|
547
|
+
return None
|
|
548
|
+
host = host.strip("[]")
|
|
549
|
+
if host in ("", "0.0.0.0", "::", "+", "*"):
|
|
550
|
+
host = "127.0.0.1"
|
|
551
|
+
return f"{scheme}://{host}:{port}"
|
|
552
|
+
|
|
553
|
+
|
|
554
|
+
def _go_literal_listen_addr(source: str, framework: str) -> Optional[str]:
|
|
555
|
+
"""The origin a mounted runtime can honestly advertise, when the source names it.
|
|
556
|
+
|
|
557
|
+
The port must be a literal: `r.Run(port())` or an env lookup is not a fact the
|
|
558
|
+
injector may bake into the discovery registry.
|
|
559
|
+
"""
|
|
560
|
+
if framework == "gin":
|
|
561
|
+
for match in re.finditer(r'\.Run\(\s*"([^"]+)"\s*\)', source):
|
|
562
|
+
origin = _go_origin_from_addr(match.group(1))
|
|
563
|
+
if origin:
|
|
564
|
+
return origin
|
|
565
|
+
return None
|
|
566
|
+
if framework == "chi":
|
|
567
|
+
match = re.search(r'http\.ListenAndServeTLS\(\s*"([^"]+)"', source)
|
|
568
|
+
if match:
|
|
569
|
+
origin = _go_origin_from_addr(match.group(1), "https")
|
|
570
|
+
if origin:
|
|
571
|
+
return origin
|
|
572
|
+
match = re.search(r'http\.ListenAndServe\(\s*"([^"]+)"', source)
|
|
573
|
+
if match:
|
|
574
|
+
origin = _go_origin_from_addr(match.group(1))
|
|
575
|
+
if origin:
|
|
576
|
+
return origin
|
|
577
|
+
# `srv := &http.Server{Addr: ":9090", ...}; srv.ListenAndServe()`
|
|
578
|
+
match = re.search(r'Addr:\s*"([^"]+)"', source)
|
|
579
|
+
if match:
|
|
580
|
+
scheme = "https" if "ListenAndServeTLS(" in source else "http"
|
|
581
|
+
return _go_origin_from_addr(match.group(1), scheme)
|
|
582
|
+
return None
|
|
583
|
+
|
|
584
|
+
|
|
420
585
|
def _ensure_std_import(source: str, package: str) -> str:
|
|
421
586
|
if re.search(r'^\s*(?:\w+\s+)?"%s"\s*$' % re.escape(package), source, re.M):
|
|
422
587
|
return source
|
|
@@ -429,19 +594,26 @@ def _ensure_std_import(source: str, package: str) -> str:
|
|
|
429
594
|
return source[: line_end + 1] + f'\t"{package}"\n' + source[line_end + 1 :]
|
|
430
595
|
|
|
431
596
|
|
|
432
|
-
def apply_go_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
|
|
597
|
+
def apply_go_patch(workspace: str, dry_run: bool = False, root: str = ".") -> Dict[str, Any]:
|
|
433
598
|
"""Ensures the module dependency, inserts the AutoMount call, validates with `go build`.
|
|
434
599
|
|
|
435
600
|
The original file is backed up first and restored byte-for-byte if any step fails.
|
|
436
601
|
"""
|
|
437
|
-
|
|
602
|
+
root_dir = _app_root(workspace, root)
|
|
603
|
+
path, framework = find_go_entrypoint(root_dir)
|
|
438
604
|
if not path or not framework:
|
|
439
605
|
return {"status": "skipped", "reason": "no mountable Go entrypoint (main.go with gin/chi/net/http) found"}
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
606
|
+
if framework in ("nethttp", "stdhttp"):
|
|
607
|
+
return {
|
|
608
|
+
"status": "manual",
|
|
609
|
+
"entrypoint": os.path.relpath(path, workspace),
|
|
610
|
+
"framework": "net/http",
|
|
611
|
+
"reason": (
|
|
612
|
+
"net/http needs the stdhttp adapter's mux; replace http.NewServeMux() "
|
|
613
|
+
"with oumvstdhttp.NewServeMux(rt) and mount the RPC path"
|
|
614
|
+
),
|
|
615
|
+
"snippet": _GO_MANUAL_SNIPPET,
|
|
616
|
+
}
|
|
445
617
|
|
|
446
618
|
with open(path, "r", encoding="utf-8") as f:
|
|
447
619
|
original = f.read()
|
|
@@ -462,7 +634,15 @@ def apply_go_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
|
|
|
462
634
|
patched, preview = wrapped
|
|
463
635
|
patched = _ensure_std_import(patched, "log")
|
|
464
636
|
else:
|
|
465
|
-
|
|
637
|
+
mount_call = call.rstrip("\n")
|
|
638
|
+
public_url = _go_literal_listen_addr(original, framework)
|
|
639
|
+
if public_url:
|
|
640
|
+
# §9.2: a mounted runtime cannot recover the listen address itself, so the
|
|
641
|
+
# literal one from the serve call is handed over explicitly.
|
|
642
|
+
mount_call = mount_call.replace(
|
|
643
|
+
"AutoMount(r)", f'AutoMount(r, {alias}.Options{{PublicURL: "{public_url}"}})'
|
|
644
|
+
)
|
|
645
|
+
insert = f"\t{_MARK_BEGIN}\n{mount_call}\n\t{_MARK_END}\n"
|
|
466
646
|
patched = original[:anchor] + insert + original[anchor:]
|
|
467
647
|
preview = insert.strip()
|
|
468
648
|
|
|
@@ -483,28 +663,52 @@ def apply_go_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
|
|
|
483
663
|
"preview": preview,
|
|
484
664
|
}
|
|
485
665
|
|
|
486
|
-
|
|
487
|
-
os.makedirs(
|
|
488
|
-
suffix = os.path.relpath(path, workspace).replace(os.sep, "__") + ".bak"
|
|
489
|
-
backup_path = os.path.join(backup_dir, suffix)
|
|
666
|
+
backup_path = _backup_path(workspace, path)
|
|
667
|
+
os.makedirs(os.path.dirname(backup_path), exist_ok=True)
|
|
490
668
|
shutil.copy2(path, backup_path)
|
|
491
|
-
module_backups: List[
|
|
669
|
+
module_backups: List[Dict[str, Any]] = []
|
|
492
670
|
for mod_file in ("go.mod", "go.sum"):
|
|
493
|
-
src = os.path.join(
|
|
671
|
+
src = os.path.join(root_dir, mod_file)
|
|
494
672
|
if os.path.isfile(src):
|
|
495
|
-
dst =
|
|
673
|
+
dst = _backup_path(workspace, src)
|
|
674
|
+
os.makedirs(os.path.dirname(dst), exist_ok=True)
|
|
496
675
|
shutil.copy2(src, dst)
|
|
497
|
-
module_backups.append(
|
|
676
|
+
module_backups.append({
|
|
677
|
+
"path": src,
|
|
678
|
+
"backup": dst,
|
|
679
|
+
"before_sha": _sha256_file(src),
|
|
680
|
+
"created": False,
|
|
681
|
+
})
|
|
682
|
+
else:
|
|
683
|
+
# `go get` may create go.sum; revert must remove it, not leave it.
|
|
684
|
+
module_backups.append({"path": src, "backup": None, "before_sha": None, "created": True})
|
|
685
|
+
|
|
686
|
+
# The dependency must be added *after* the backups: `go get` rewrites
|
|
687
|
+
# go.mod/go.sum, and a backup taken afterwards would restore the dependency
|
|
688
|
+
# instead of the pre-inject bytes.
|
|
689
|
+
dep_error = _ensure_go_dependency(root_dir)
|
|
690
|
+
if dep_error:
|
|
691
|
+
if os.path.isfile(backup_path):
|
|
692
|
+
os.unlink(backup_path)
|
|
693
|
+
for module in module_backups:
|
|
694
|
+
backup = module.get("backup")
|
|
695
|
+
if backup and os.path.isfile(backup):
|
|
696
|
+
os.unlink(backup)
|
|
697
|
+
return {"status": "skipped", "reason": dep_error}
|
|
498
698
|
|
|
499
699
|
with open(path, "w", encoding="utf-8") as f:
|
|
500
700
|
f.write(patched)
|
|
501
701
|
|
|
502
|
-
tidy_ok, tidy_output = _go_tidy(
|
|
503
|
-
build_ok, build_output = _go_build(
|
|
702
|
+
tidy_ok, tidy_output = _go_tidy(root_dir)
|
|
703
|
+
build_ok, build_output = _go_build(root_dir) if tidy_ok else (False, tidy_output)
|
|
504
704
|
if not build_ok:
|
|
505
705
|
shutil.copy2(backup_path, path)
|
|
506
|
-
for
|
|
507
|
-
|
|
706
|
+
for module in module_backups:
|
|
707
|
+
if module.get("created"):
|
|
708
|
+
if os.path.isfile(module["path"]):
|
|
709
|
+
os.remove(module["path"])
|
|
710
|
+
elif module.get("backup"):
|
|
711
|
+
shutil.copy2(module["backup"], module["path"])
|
|
508
712
|
first_error = next((line for line in build_output.splitlines() if line.strip()), "")
|
|
509
713
|
return {
|
|
510
714
|
"status": "reverted",
|
|
@@ -513,11 +717,17 @@ def apply_go_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
|
|
|
513
717
|
"build_output": build_output[-1200:],
|
|
514
718
|
}
|
|
515
719
|
|
|
720
|
+
for module in module_backups:
|
|
721
|
+
if os.path.isfile(module["path"]):
|
|
722
|
+
module["after_sha"] = _sha256_file(module["path"])
|
|
516
723
|
_write_manifest(workspace, "go", {
|
|
724
|
+
"kind": "go",
|
|
725
|
+
"app": root,
|
|
517
726
|
"entrypoint": path,
|
|
518
727
|
"backup": backup_path,
|
|
519
728
|
"framework": framework,
|
|
520
729
|
"mode": "serve" if wrapped is not None else "mount",
|
|
730
|
+
"modules": module_backups,
|
|
521
731
|
})
|
|
522
732
|
|
|
523
733
|
return {
|
|
@@ -547,8 +757,11 @@ def _go_build(workspace: str) -> Tuple[bool, str]:
|
|
|
547
757
|
return True, f"build validation failed to run: {exc}"
|
|
548
758
|
|
|
549
759
|
|
|
550
|
-
def revert_go_patch(
|
|
551
|
-
|
|
760
|
+
def revert_go_patch(
|
|
761
|
+
workspace: str, root: str = ".", manifest: Optional[Dict[str, Any]] = None
|
|
762
|
+
) -> Dict[str, Any]:
|
|
763
|
+
if manifest is None:
|
|
764
|
+
manifest = _read_manifest(workspace, "go", ("serve", "mount", "go_patch"), app=root)
|
|
552
765
|
if manifest is None:
|
|
553
766
|
return {"status": "nothing-to-revert"}
|
|
554
767
|
target = manifest.get("entrypoint")
|
|
@@ -556,8 +769,34 @@ def revert_go_patch(workspace: str) -> Dict[str, Any]:
|
|
|
556
769
|
if not target or not backup or not os.path.isfile(backup):
|
|
557
770
|
return {"status": "error", "reason": "backup missing"}
|
|
558
771
|
shutil.copy2(backup, target)
|
|
772
|
+
modules: List[Dict[str, str]] = []
|
|
773
|
+
for module in manifest.get("modules") or []:
|
|
774
|
+
path, module_backup = module.get("path"), module.get("backup")
|
|
775
|
+
after = module.get("after_sha")
|
|
776
|
+
if module.get("created"):
|
|
777
|
+
if not path or not os.path.isfile(path):
|
|
778
|
+
modules.append({"path": path or "?", "status": "absent"})
|
|
779
|
+
continue
|
|
780
|
+
if after and _sha256_file(path) != after:
|
|
781
|
+
modules.append({"path": os.path.relpath(path, workspace), "status": "modules_modified"})
|
|
782
|
+
continue
|
|
783
|
+
os.remove(path)
|
|
784
|
+
modules.append({"path": os.path.relpath(path, workspace), "status": "removed"})
|
|
785
|
+
continue
|
|
786
|
+
if not (path and module_backup and os.path.isfile(module_backup)):
|
|
787
|
+
modules.append({"path": path or "?", "status": "backup-missing"})
|
|
788
|
+
continue
|
|
789
|
+
if after and os.path.isfile(path) and _sha256_file(path) != after:
|
|
790
|
+
modules.append({"path": os.path.relpath(path, workspace), "status": "modules_modified"})
|
|
791
|
+
continue
|
|
792
|
+
shutil.copy2(module_backup, path)
|
|
793
|
+
modules.append({"path": os.path.relpath(path, workspace), "status": "restored"})
|
|
559
794
|
_delete_manifest(manifest)
|
|
560
|
-
return {
|
|
795
|
+
return {
|
|
796
|
+
"status": "reverted",
|
|
797
|
+
"entrypoint": os.path.relpath(target, workspace),
|
|
798
|
+
"modules": modules,
|
|
799
|
+
}
|
|
561
800
|
|
|
562
801
|
|
|
563
802
|
# --------------------------------------------------------------------------- #
|
|
@@ -605,27 +844,112 @@ def _node_framework_of(workspace: str) -> Optional[str]:
|
|
|
605
844
|
return None
|
|
606
845
|
|
|
607
846
|
|
|
608
|
-
def node_patch_state(workspace: str) -> Dict[str, Any]:
|
|
847
|
+
def node_patch_state(workspace: str, root: str = ".") -> Dict[str, Any]:
|
|
609
848
|
"""Reports whether the one-line OUMV mount is already in the Node entrypoint."""
|
|
610
|
-
|
|
849
|
+
root_dir = _app_root(workspace, root)
|
|
850
|
+
path = _find_node_entrypoint(root_dir)
|
|
851
|
+
framework = _node_framework_of(root_dir)
|
|
611
852
|
if not path:
|
|
612
|
-
return {"entrypoint": None, "patched": False, "framework":
|
|
853
|
+
return {"entrypoint": None, "patched": False, "framework": framework}
|
|
613
854
|
try:
|
|
614
855
|
with open(path, "r", encoding="utf-8") as f:
|
|
615
856
|
source = f.read()
|
|
616
857
|
except OSError:
|
|
617
|
-
return {"entrypoint": path, "patched": False, "framework":
|
|
858
|
+
return {"entrypoint": path, "patched": False, "framework": framework}
|
|
618
859
|
return {
|
|
619
860
|
"entrypoint": os.path.relpath(path, workspace),
|
|
620
861
|
"patched": _MARK_BEGIN in source and _MARK_END in source,
|
|
621
|
-
"framework":
|
|
862
|
+
"framework": framework,
|
|
622
863
|
}
|
|
623
864
|
|
|
624
865
|
|
|
625
|
-
|
|
866
|
+
_NODE_PACKAGE = "tokensafe-backend-node"
|
|
867
|
+
|
|
868
|
+
|
|
869
|
+
def _node_package_dir(workspace: str, entrypoint: str) -> str:
|
|
870
|
+
"""Nearest directory holding a package.json, confined to the workspace."""
|
|
871
|
+
root = os.path.abspath(workspace)
|
|
872
|
+
current = os.path.dirname(os.path.abspath(entrypoint))
|
|
873
|
+
while True:
|
|
874
|
+
if os.path.isfile(os.path.join(current, "package.json")):
|
|
875
|
+
return current
|
|
876
|
+
parent = os.path.dirname(current)
|
|
877
|
+
if parent == current or os.path.abspath(current) == root:
|
|
878
|
+
return current if os.path.isdir(current) else root
|
|
879
|
+
current = parent
|
|
880
|
+
|
|
881
|
+
|
|
882
|
+
def _node_install_command(package_dir: str) -> Tuple[List[str], str]:
|
|
883
|
+
"""(argv, manager) for an exact install of the Node adapter package."""
|
|
884
|
+
package = f"{_NODE_PACKAGE}@{BACKEND_NPM_VERSION}"
|
|
885
|
+
markers = (
|
|
886
|
+
("bun.lock", ["bun", "add"], "bun"),
|
|
887
|
+
("bun.lockb", ["bun", "add"], "bun"),
|
|
888
|
+
("pnpm-lock.yaml", ["pnpm", "add", "--save-exact"], "pnpm"),
|
|
889
|
+
("yarn.lock", ["yarn", "add", "--exact"], "yarn"),
|
|
890
|
+
("package-lock.json", ["npm", "install", "--save-exact"], "npm"),
|
|
891
|
+
)
|
|
892
|
+
for marker, prefix, manager in markers:
|
|
893
|
+
if os.path.isfile(os.path.join(package_dir, marker)):
|
|
894
|
+
return [*prefix, package], manager
|
|
895
|
+
return ["npm", "install", "--save-exact", package], "npm"
|
|
896
|
+
|
|
897
|
+
|
|
898
|
+
def _node_package_installed(package_dir: str) -> bool:
|
|
899
|
+
return os.path.isdir(os.path.join(package_dir, "node_modules", _NODE_PACKAGE))
|
|
900
|
+
|
|
901
|
+
|
|
902
|
+
def _install_node_package(workspace: str, entrypoint: str) -> Dict[str, Any]:
|
|
903
|
+
"""Installs the adapter through the app's own package manager.
|
|
904
|
+
|
|
905
|
+
A missing or failed install must never leave an unresolvable `require`
|
|
906
|
+
behind, so the caller skips the patch instead of writing a broken line.
|
|
907
|
+
``TOKENSAFE_INJECT_NO_INSTALL=1`` is the explicit opt-out (the plan already
|
|
908
|
+
names the exact command).
|
|
909
|
+
"""
|
|
910
|
+
package_dir = _node_package_dir(workspace, entrypoint)
|
|
911
|
+
argv, manager = _node_install_command(package_dir)
|
|
912
|
+
command = " ".join(argv)
|
|
913
|
+
if _node_package_installed(package_dir):
|
|
914
|
+
return {"status": "already_installed", "manager": manager, "command": command}
|
|
915
|
+
if os.environ.get("TOKENSAFE_INJECT_NO_INSTALL") == "1":
|
|
916
|
+
return {"status": "opted_out", "manager": manager, "command": command}
|
|
917
|
+
try:
|
|
918
|
+
proc = subprocess.run(
|
|
919
|
+
argv, cwd=package_dir, capture_output=True, text=True, timeout=180
|
|
920
|
+
)
|
|
921
|
+
except FileNotFoundError:
|
|
922
|
+
return {
|
|
923
|
+
"status": "unavailable",
|
|
924
|
+
"manager": manager,
|
|
925
|
+
"command": command,
|
|
926
|
+
"reason": f"{argv[0]} is not on PATH",
|
|
927
|
+
}
|
|
928
|
+
except subprocess.TimeoutExpired:
|
|
929
|
+
return {
|
|
930
|
+
"status": "unavailable",
|
|
931
|
+
"manager": manager,
|
|
932
|
+
"command": command,
|
|
933
|
+
"reason": "install timed out after 180s",
|
|
934
|
+
}
|
|
935
|
+
except OSError as exc:
|
|
936
|
+
return {"status": "unavailable", "manager": manager, "command": command, "reason": str(exc)}
|
|
937
|
+
if proc.returncode != 0:
|
|
938
|
+
tail = (proc.stderr or proc.stdout or "").strip().splitlines()
|
|
939
|
+
return {
|
|
940
|
+
"status": "failed",
|
|
941
|
+
"manager": manager,
|
|
942
|
+
"command": command,
|
|
943
|
+
"reason": f"exit {proc.returncode}: {tail[-1] if tail else 'no output'}",
|
|
944
|
+
}
|
|
945
|
+
return {"status": "installed", "manager": manager, "command": command}
|
|
946
|
+
|
|
947
|
+
|
|
948
|
+
def apply_node_patch(workspace: str, dry_run: bool = False, root: str = ".") -> Dict[str, Any]:
|
|
626
949
|
"""Inserts one mount line between tokensafe markers, with a byte-exact backup."""
|
|
627
|
-
|
|
628
|
-
|
|
950
|
+
root_dir = _app_root(workspace, root)
|
|
951
|
+
framework = _node_framework_of(root_dir)
|
|
952
|
+
path = _find_node_entrypoint(root_dir)
|
|
629
953
|
if framework not in ("express", "fastify"):
|
|
630
954
|
return {"status": "skipped", "reason": "no supported Node framework (express/fastify) found"}
|
|
631
955
|
if not path:
|
|
@@ -662,16 +986,42 @@ def apply_node_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
|
|
|
662
986
|
insert_at = len(source) if line_end < 0 else line_end + 1
|
|
663
987
|
patched = source[:insert_at] + mount + source[insert_at:]
|
|
664
988
|
|
|
989
|
+
argv, manager = _node_install_command(_node_package_dir(root_dir, path))
|
|
990
|
+
planned_install = {"status": "planned", "manager": manager, "command": " ".join(argv)}
|
|
665
991
|
if dry_run:
|
|
666
|
-
return {
|
|
992
|
+
return {
|
|
993
|
+
"status": "dry_run",
|
|
994
|
+
"entrypoint": os.path.relpath(path, workspace),
|
|
995
|
+
"preview": mount.strip(),
|
|
996
|
+
"install": planned_install,
|
|
997
|
+
}
|
|
998
|
+
|
|
999
|
+
install = _install_node_package(root_dir, path)
|
|
1000
|
+
if install["status"] in ("failed", "unavailable"):
|
|
1001
|
+
return {
|
|
1002
|
+
"status": "skipped",
|
|
1003
|
+
"entrypoint": os.path.relpath(path, workspace),
|
|
1004
|
+
"framework": framework,
|
|
1005
|
+
"install": install,
|
|
1006
|
+
"reason": (
|
|
1007
|
+
f"could not install {_NODE_PACKAGE} ({install.get('reason')}); "
|
|
1008
|
+
f"run `{install['command']}` and retry"
|
|
1009
|
+
),
|
|
1010
|
+
}
|
|
667
1011
|
|
|
668
|
-
|
|
669
|
-
os.makedirs(
|
|
670
|
-
backup_path = os.path.join(backup_dir, os.path.relpath(path, workspace).replace(os.sep, "__") + ".bak")
|
|
1012
|
+
backup_path = _backup_path(workspace, path)
|
|
1013
|
+
os.makedirs(os.path.dirname(backup_path), exist_ok=True)
|
|
671
1014
|
shutil.copy2(path, backup_path)
|
|
672
1015
|
with open(path, "w", encoding="utf-8") as f:
|
|
673
1016
|
f.write(patched)
|
|
674
|
-
_write_manifest(workspace, "node", {
|
|
1017
|
+
_write_manifest(workspace, "node", {
|
|
1018
|
+
"kind": "node",
|
|
1019
|
+
"app": root,
|
|
1020
|
+
"entrypoint": path,
|
|
1021
|
+
"backup": backup_path,
|
|
1022
|
+
"framework": framework,
|
|
1023
|
+
"install": install,
|
|
1024
|
+
})
|
|
675
1025
|
return {
|
|
676
1026
|
"status": "patched",
|
|
677
1027
|
"entrypoint": os.path.relpath(path, workspace),
|
|
@@ -679,11 +1029,15 @@ def apply_node_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
|
|
|
679
1029
|
"mode": "node_mount",
|
|
680
1030
|
"backup": backup_path,
|
|
681
1031
|
"line": mount.splitlines()[1],
|
|
1032
|
+
"install": install,
|
|
682
1033
|
}
|
|
683
1034
|
|
|
684
1035
|
|
|
685
|
-
def revert_node_patch(
|
|
686
|
-
|
|
1036
|
+
def revert_node_patch(
|
|
1037
|
+
workspace: str, root: str = ".", manifest: Optional[Dict[str, Any]] = None
|
|
1038
|
+
) -> Dict[str, Any]:
|
|
1039
|
+
if manifest is None:
|
|
1040
|
+
manifest = _read_manifest(workspace, "node", ("node_mount",), app=root)
|
|
687
1041
|
if manifest is None:
|
|
688
1042
|
return {"status": "clean", "reason": "no Node patch manifest"}
|
|
689
1043
|
entrypoint = manifest.get("entrypoint")
|
|
@@ -718,10 +1072,12 @@ def _elysia_app_reference(source: str) -> Optional[Tuple[str, str, int]]:
|
|
|
718
1072
|
return created.group("var"), created.group("indent"), insert_at
|
|
719
1073
|
|
|
720
1074
|
|
|
721
|
-
def elysia_patch_state(workspace: str) -> Dict[str, Any]:
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
1075
|
+
def elysia_patch_state(workspace: str, root: str = ".") -> Dict[str, Any]:
|
|
1076
|
+
root_dir = _app_root(workspace, root)
|
|
1077
|
+
path = _find_node_entrypoint(root_dir)
|
|
1078
|
+
framework = _node_framework_of(root_dir)
|
|
1079
|
+
if not path or framework != "elysia":
|
|
1080
|
+
return {"entrypoint": None, "patched": False, "framework": framework}
|
|
725
1081
|
try:
|
|
726
1082
|
with open(path, "r", encoding="utf-8") as f:
|
|
727
1083
|
source = f.read()
|
|
@@ -734,11 +1090,12 @@ def elysia_patch_state(workspace: str) -> Dict[str, Any]:
|
|
|
734
1090
|
}
|
|
735
1091
|
|
|
736
1092
|
|
|
737
|
-
def apply_elysia_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
|
|
1093
|
+
def apply_elysia_patch(workspace: str, dry_run: bool = False, root: str = ".") -> Dict[str, Any]:
|
|
738
1094
|
"""Adds `app.use(oumv())` to an Elysia app, with a byte-exact backup."""
|
|
739
|
-
|
|
1095
|
+
root_dir = _app_root(workspace, root)
|
|
1096
|
+
if _node_framework_of(root_dir) != "elysia":
|
|
740
1097
|
return {"status": "skipped", "reason": "no Elysia dependency in package.json"}
|
|
741
|
-
path = _find_node_entrypoint(
|
|
1098
|
+
path = _find_node_entrypoint(root_dir)
|
|
742
1099
|
if not path:
|
|
743
1100
|
return {"status": "skipped", "reason": "no Bun entrypoint found"}
|
|
744
1101
|
|
|
@@ -762,21 +1119,43 @@ def apply_elysia_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
|
|
|
762
1119
|
)
|
|
763
1120
|
patched = source[:insert_at] + mount + source[insert_at:]
|
|
764
1121
|
|
|
1122
|
+
argv, manager = _node_install_command(_node_package_dir(root_dir, path))
|
|
1123
|
+
planned_install = {"status": "planned", "manager": manager, "command": " ".join(argv)}
|
|
765
1124
|
if dry_run:
|
|
766
1125
|
return {
|
|
767
1126
|
"status": "dry_run",
|
|
768
1127
|
"entrypoint": os.path.relpath(path, workspace),
|
|
769
1128
|
"framework": "elysia",
|
|
770
1129
|
"preview": f"{var}.use(_oumv());",
|
|
1130
|
+
"install": planned_install,
|
|
771
1131
|
}
|
|
772
1132
|
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
1133
|
+
install = _install_node_package(root_dir, path)
|
|
1134
|
+
if install["status"] in ("failed", "unavailable"):
|
|
1135
|
+
return {
|
|
1136
|
+
"status": "skipped",
|
|
1137
|
+
"entrypoint": os.path.relpath(path, workspace),
|
|
1138
|
+
"framework": "elysia",
|
|
1139
|
+
"install": install,
|
|
1140
|
+
"reason": (
|
|
1141
|
+
f"could not install {_NODE_PACKAGE} ({install.get('reason')}); "
|
|
1142
|
+
f"run `{install['command']}` and retry"
|
|
1143
|
+
),
|
|
1144
|
+
}
|
|
1145
|
+
|
|
1146
|
+
backup_path = _backup_path(workspace, path)
|
|
1147
|
+
os.makedirs(os.path.dirname(backup_path), exist_ok=True)
|
|
776
1148
|
shutil.copy2(path, backup_path)
|
|
777
1149
|
with open(path, "w", encoding="utf-8") as f:
|
|
778
1150
|
f.write(patched)
|
|
779
|
-
_write_manifest(workspace, "elysia", {
|
|
1151
|
+
_write_manifest(workspace, "elysia", {
|
|
1152
|
+
"kind": "elysia",
|
|
1153
|
+
"app": root,
|
|
1154
|
+
"entrypoint": path,
|
|
1155
|
+
"backup": backup_path,
|
|
1156
|
+
"framework": "elysia",
|
|
1157
|
+
"install": install,
|
|
1158
|
+
})
|
|
780
1159
|
return {
|
|
781
1160
|
"status": "patched",
|
|
782
1161
|
"entrypoint": os.path.relpath(path, workspace),
|
|
@@ -784,11 +1163,15 @@ def apply_elysia_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
|
|
|
784
1163
|
"mode": "elysia_plugin",
|
|
785
1164
|
"backup": backup_path,
|
|
786
1165
|
"line": f"{var}.use(_oumv());",
|
|
1166
|
+
"install": install,
|
|
787
1167
|
}
|
|
788
1168
|
|
|
789
1169
|
|
|
790
|
-
def revert_elysia_patch(
|
|
791
|
-
|
|
1170
|
+
def revert_elysia_patch(
|
|
1171
|
+
workspace: str, root: str = ".", manifest: Optional[Dict[str, Any]] = None
|
|
1172
|
+
) -> Dict[str, Any]:
|
|
1173
|
+
if manifest is None:
|
|
1174
|
+
manifest = _read_manifest(workspace, "elysia", ("elysia_plugin",), app=root)
|
|
792
1175
|
if manifest is None:
|
|
793
1176
|
return {"status": "clean", "reason": "no Elysia patch manifest"}
|
|
794
1177
|
entrypoint = manifest.get("entrypoint")
|
|
@@ -956,12 +1339,13 @@ def next_bridge_mode(workspace: str) -> str:
|
|
|
956
1339
|
return "instrumentation" if version >= _NEXT_INSTRUMENTATION_MIN else "manual"
|
|
957
1340
|
|
|
958
1341
|
|
|
959
|
-
def next_patch_state(workspace: str) -> Dict[str, Any]:
|
|
960
|
-
|
|
1342
|
+
def next_patch_state(workspace: str, root: str = ".") -> Dict[str, Any]:
|
|
1343
|
+
root_dir = _app_root(workspace, root)
|
|
1344
|
+
files = _next_files(root_dir)
|
|
961
1345
|
existing = [path for path, _ in files if os.path.isfile(path)]
|
|
962
|
-
loader = _next_existing_instrumentation(
|
|
963
|
-
installed = _next_instrumentation_installed(
|
|
964
|
-
mode = next_bridge_mode(
|
|
1346
|
+
loader = _next_existing_instrumentation(root_dir)
|
|
1347
|
+
installed = _next_instrumentation_installed(root_dir)
|
|
1348
|
+
mode = next_bridge_mode(root_dir)
|
|
965
1349
|
return {
|
|
966
1350
|
"entrypoint": existing[0] if existing else None,
|
|
967
1351
|
"patched": len(existing) == len(files) and (mode != "instrumentation" or installed),
|
|
@@ -981,19 +1365,39 @@ def _next_route_has_bridge(path: str) -> bool:
|
|
|
981
1365
|
return False
|
|
982
1366
|
|
|
983
1367
|
|
|
984
|
-
def
|
|
985
|
-
|
|
986
|
-
mode
|
|
1368
|
+
def _next_manual_note(workspace: str, root_dir: str, files: List[Tuple[str, str]], mode: str) -> Optional[Dict[str, str]]:
|
|
1369
|
+
snippet = "import { installNextBridge } from 'tokensafe-backend-node/next-bridge';\ninstallNextBridge();"
|
|
1370
|
+
if mode == "manual":
|
|
1371
|
+
return {
|
|
1372
|
+
"reason": "instrumentation-client requires Next >= 15.3; load the bridge by hand in this app",
|
|
1373
|
+
"snippet": snippet,
|
|
1374
|
+
}
|
|
1375
|
+
loader = _next_existing_instrumentation(root_dir)
|
|
1376
|
+
own_paths = {path for path, _ in files}
|
|
1377
|
+
if loader and loader not in own_paths and not _next_instrumentation_installed(root_dir):
|
|
1378
|
+
return {
|
|
1379
|
+
"reason": f"{os.path.relpath(loader, workspace)} already exists — add the installer call to it instead of letting the engine shadow it",
|
|
1380
|
+
"snippet": snippet,
|
|
1381
|
+
}
|
|
1382
|
+
return None
|
|
1383
|
+
|
|
1384
|
+
|
|
1385
|
+
def apply_next_patch(workspace: str, dry_run: bool = False, root: str = ".") -> Dict[str, Any]:
|
|
1386
|
+
root_dir = _app_root(workspace, root)
|
|
1387
|
+
files = _next_files(root_dir)
|
|
1388
|
+
mode = next_bridge_mode(root_dir)
|
|
987
1389
|
entrypoint = os.path.relpath(files[0][0], workspace)
|
|
988
1390
|
actions: List[Dict[str, str]] = []
|
|
989
|
-
|
|
1391
|
+
created: List[str] = []
|
|
1392
|
+
restore: Dict[str, str] = {}
|
|
990
1393
|
|
|
991
1394
|
for path, source in files:
|
|
992
1395
|
rel = os.path.relpath(path, workspace)
|
|
993
1396
|
if os.path.isfile(path):
|
|
994
1397
|
if path == files[0][0] and not _next_route_has_bridge(path):
|
|
995
1398
|
try:
|
|
996
|
-
|
|
1399
|
+
with open(path, "r", encoding="utf-8") as handle:
|
|
1400
|
+
current = handle.read()
|
|
997
1401
|
except Exception:
|
|
998
1402
|
current = ""
|
|
999
1403
|
if current != _NEXT_LEGACY_ROUTE_SOURCE:
|
|
@@ -1003,12 +1407,12 @@ def apply_next_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
|
|
|
1003
1407
|
"entrypoint": rel,
|
|
1004
1408
|
}
|
|
1005
1409
|
actions.append({"path": rel, "action": "upgrade"})
|
|
1006
|
-
|
|
1410
|
+
restore[path] = _backup_path(workspace, path)
|
|
1007
1411
|
else:
|
|
1008
1412
|
actions.append({"path": rel, "action": "keep"})
|
|
1009
1413
|
continue
|
|
1010
1414
|
actions.append({"path": rel, "action": "create"})
|
|
1011
|
-
|
|
1415
|
+
created.append(path)
|
|
1012
1416
|
|
|
1013
1417
|
if dry_run:
|
|
1014
1418
|
return {
|
|
@@ -1016,65 +1420,65 @@ def apply_next_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
|
|
|
1016
1420
|
"entrypoint": entrypoint,
|
|
1017
1421
|
"bridge": mode,
|
|
1018
1422
|
"files": actions,
|
|
1019
|
-
"would_create": [os.path.relpath(path, workspace) for path in
|
|
1423
|
+
"would_create": [os.path.relpath(path, workspace) for path in created],
|
|
1424
|
+
"would_upgrade": [os.path.relpath(path, workspace) for path in restore],
|
|
1020
1425
|
}
|
|
1021
1426
|
|
|
1022
|
-
|
|
1427
|
+
# Nothing was written: a manifest here would let revert delete user files.
|
|
1428
|
+
if not created and not restore:
|
|
1429
|
+
result: Dict[str, Any] = {
|
|
1430
|
+
"status": "already_patched",
|
|
1431
|
+
"entrypoint": entrypoint,
|
|
1432
|
+
"bridge": mode,
|
|
1433
|
+
"files": actions,
|
|
1434
|
+
"created": [],
|
|
1435
|
+
}
|
|
1436
|
+
note = _next_manual_note(workspace, root_dir, files, mode)
|
|
1437
|
+
if note:
|
|
1438
|
+
result["bridge_manual"] = note
|
|
1439
|
+
return result
|
|
1440
|
+
|
|
1441
|
+
# An upgraded v1 route is the user's file; keep its bytes for revert.
|
|
1442
|
+
for path, backup in restore.items():
|
|
1443
|
+
os.makedirs(os.path.dirname(backup), exist_ok=True)
|
|
1444
|
+
shutil.copy2(path, backup)
|
|
1445
|
+
|
|
1023
1446
|
for path, source in files:
|
|
1024
|
-
if
|
|
1447
|
+
if path not in created and path not in restore:
|
|
1025
1448
|
continue
|
|
1026
1449
|
parent = os.path.dirname(path)
|
|
1027
1450
|
if parent:
|
|
1028
1451
|
os.makedirs(parent, exist_ok=True)
|
|
1029
1452
|
with open(path, "w", encoding="utf-8") as handle:
|
|
1030
1453
|
handle.write(source)
|
|
1031
|
-
if path not in created:
|
|
1032
|
-
created.append(path)
|
|
1033
1454
|
|
|
1034
1455
|
_write_manifest(workspace, "next", {
|
|
1456
|
+
"kind": "next",
|
|
1457
|
+
"app": root,
|
|
1458
|
+
"ownership": 2,
|
|
1035
1459
|
"entrypoint": files[0][0],
|
|
1036
1460
|
"framework": "nextjs",
|
|
1037
1461
|
"mode": "next_route_v2",
|
|
1038
1462
|
"bridge": mode,
|
|
1039
1463
|
"files": [path for path, _ in files],
|
|
1040
|
-
"owned": owned or [path for path, _ in files],
|
|
1041
1464
|
"created": created,
|
|
1465
|
+
"restore": restore,
|
|
1042
1466
|
})
|
|
1043
|
-
result
|
|
1044
|
-
"status": "patched"
|
|
1467
|
+
result = {
|
|
1468
|
+
"status": "patched",
|
|
1045
1469
|
"entrypoint": entrypoint,
|
|
1046
1470
|
"bridge": mode,
|
|
1047
1471
|
"files": actions,
|
|
1048
1472
|
"created": [os.path.relpath(path, workspace) for path in created],
|
|
1473
|
+
"upgraded": [os.path.relpath(path, workspace) for path in restore],
|
|
1049
1474
|
}
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
"snippet": "import { installNextBridge } from 'tokensafe-backend-node/next-bridge';\ninstallNextBridge();",
|
|
1054
|
-
}
|
|
1055
|
-
else:
|
|
1056
|
-
loader = _next_existing_instrumentation(workspace)
|
|
1057
|
-
own_paths = {path for path, _ in files}
|
|
1058
|
-
if loader and loader not in own_paths and not _next_instrumentation_installed(workspace):
|
|
1059
|
-
result["bridge_manual"] = {
|
|
1060
|
-
"reason": f"{os.path.relpath(loader, workspace)} already exists — add the installer call to it instead of letting the engine shadow it",
|
|
1061
|
-
"snippet": "import { installNextBridge } from 'tokensafe-backend-node/next-bridge';\ninstallNextBridge();",
|
|
1062
|
-
}
|
|
1475
|
+
note = _next_manual_note(workspace, root_dir, files, mode)
|
|
1476
|
+
if note:
|
|
1477
|
+
result["bridge_manual"] = note
|
|
1063
1478
|
return result
|
|
1064
1479
|
|
|
1065
1480
|
|
|
1066
|
-
def
|
|
1067
|
-
manifest = _read_manifest(workspace, "next", ("next_route", "next_route_v2"))
|
|
1068
|
-
if not manifest:
|
|
1069
|
-
return {"status": "nothing-to-revert"}
|
|
1070
|
-
candidates = manifest.get("owned") or manifest.get("created") or []
|
|
1071
|
-
if not candidates and manifest.get("entrypoint"):
|
|
1072
|
-
candidates = [manifest["entrypoint"]]
|
|
1073
|
-
removed: List[str] = []
|
|
1074
|
-
for path in candidates:
|
|
1075
|
-
if path and os.path.isfile(path):
|
|
1076
|
-
os.remove(path)
|
|
1077
|
-
removed.append(path)
|
|
1481
|
+
def _remove_empty_dirs(workspace: str, removed: List[str]) -> None:
|
|
1078
1482
|
# Remove only directories this adapter emptied, never a non-empty parent.
|
|
1079
1483
|
for directory in sorted({os.path.dirname(path) for path in removed}, key=len, reverse=True):
|
|
1080
1484
|
while os.path.abspath(directory) != os.path.abspath(workspace) and os.path.isdir(directory):
|
|
@@ -1083,11 +1487,77 @@ def revert_next_patch(workspace: str) -> Dict[str, Any]:
|
|
|
1083
1487
|
except OSError:
|
|
1084
1488
|
break
|
|
1085
1489
|
directory = os.path.dirname(directory)
|
|
1490
|
+
|
|
1491
|
+
|
|
1492
|
+
def _revert_legacy_next_patch(workspace: str, manifest: Dict[str, Any]) -> Dict[str, Any]:
|
|
1493
|
+
"""Manifests before `ownership: 2` cannot tell created files from pre-existing
|
|
1494
|
+
ones. Delete only bytes this adapter wrote; keep everything else."""
|
|
1495
|
+
candidates = manifest.get("owned") or manifest.get("created") or []
|
|
1496
|
+
if not candidates and manifest.get("entrypoint"):
|
|
1497
|
+
candidates = [manifest["entrypoint"]]
|
|
1498
|
+
removed: List[str] = []
|
|
1499
|
+
kept: List[Dict[str, str]] = []
|
|
1500
|
+
for path in candidates:
|
|
1501
|
+
if not path or not os.path.isfile(path):
|
|
1502
|
+
continue
|
|
1503
|
+
try:
|
|
1504
|
+
with open(path, "r", encoding="utf-8") as handle:
|
|
1505
|
+
content = handle.read()
|
|
1506
|
+
except OSError:
|
|
1507
|
+
kept.append({"path": os.path.relpath(path, workspace), "reason": "unreadable; left in place"})
|
|
1508
|
+
continue
|
|
1509
|
+
if content in (_NEXT_RPC_SOURCE, _NEXT_BRIDGE_SOURCE, _NEXT_INSTRUMENTATION_SOURCE):
|
|
1510
|
+
os.remove(path)
|
|
1511
|
+
removed.append(path)
|
|
1512
|
+
elif content == _NEXT_LEGACY_ROUTE_SOURCE:
|
|
1513
|
+
kept.append({"path": os.path.relpath(path, workspace), "reason": "pre-existing legacy route; left in place"})
|
|
1514
|
+
else:
|
|
1515
|
+
kept.append({"path": os.path.relpath(path, workspace), "reason": "content was not generated by this adapter"})
|
|
1516
|
+
_remove_empty_dirs(workspace, removed)
|
|
1086
1517
|
_delete_manifest(manifest)
|
|
1087
1518
|
return {
|
|
1088
|
-
"status": "reverted",
|
|
1519
|
+
"status": "reverted" if removed else "kept",
|
|
1520
|
+
"entrypoint": manifest.get("entrypoint"),
|
|
1521
|
+
"removed": [os.path.relpath(path, workspace) for path in removed],
|
|
1522
|
+
"kept": kept,
|
|
1523
|
+
}
|
|
1524
|
+
|
|
1525
|
+
|
|
1526
|
+
def revert_next_patch(
|
|
1527
|
+
workspace: str, root: str = ".", manifest: Optional[Dict[str, Any]] = None
|
|
1528
|
+
) -> Dict[str, Any]:
|
|
1529
|
+
if manifest is None:
|
|
1530
|
+
manifest = _read_manifest(workspace, "next", ("next_route", "next_route_v2"), app=root)
|
|
1531
|
+
if not manifest:
|
|
1532
|
+
return {"status": "nothing-to-revert"}
|
|
1533
|
+
if manifest.get("ownership") != 2:
|
|
1534
|
+
return _revert_legacy_next_patch(workspace, manifest)
|
|
1535
|
+
created = manifest.get("created") or []
|
|
1536
|
+
restore = manifest.get("restore") or {}
|
|
1537
|
+
removed: List[str] = []
|
|
1538
|
+
restored: List[str] = []
|
|
1539
|
+
kept: List[Dict[str, str]] = []
|
|
1540
|
+
for path in created:
|
|
1541
|
+
if path and os.path.isfile(path):
|
|
1542
|
+
os.remove(path)
|
|
1543
|
+
removed.append(path)
|
|
1544
|
+
for path, backup in restore.items():
|
|
1545
|
+
if path and backup and os.path.isfile(backup):
|
|
1546
|
+
parent = os.path.dirname(path)
|
|
1547
|
+
if parent:
|
|
1548
|
+
os.makedirs(parent, exist_ok=True)
|
|
1549
|
+
shutil.copy2(backup, path)
|
|
1550
|
+
restored.append(path)
|
|
1551
|
+
else:
|
|
1552
|
+
kept.append({"path": os.path.relpath(path, workspace) if path else "?", "reason": "backup missing; left in place"})
|
|
1553
|
+
_remove_empty_dirs(workspace, removed)
|
|
1554
|
+
_delete_manifest(manifest)
|
|
1555
|
+
return {
|
|
1556
|
+
"status": "reverted" if (removed or restored) else "clean",
|
|
1089
1557
|
"entrypoint": manifest.get("entrypoint"),
|
|
1090
1558
|
"removed": [os.path.relpath(path, workspace) for path in removed],
|
|
1559
|
+
"restored": [os.path.relpath(path, workspace) for path in restored],
|
|
1560
|
+
"kept": kept,
|
|
1091
1561
|
}
|
|
1092
1562
|
|
|
1093
1563
|
|
|
@@ -1155,7 +1625,7 @@ def _sidecar_cache_dir() -> str:
|
|
|
1155
1625
|
_DOTNET_MARK_BEGIN = "// tokensafe:oumv:begin"
|
|
1156
1626
|
_DOTNET_MARK_END = "// tokensafe:oumv:end"
|
|
1157
1627
|
_DOTNET_PACKAGE = "TokenSafe.Oumv.AspNetCore"
|
|
1158
|
-
_DOTNET_PACKAGE_VERSION =
|
|
1628
|
+
_DOTNET_PACKAGE_VERSION = BACKEND_DOTNET_VERSION
|
|
1159
1629
|
|
|
1160
1630
|
|
|
1161
1631
|
|
|
@@ -1204,10 +1674,11 @@ def _find_dotnet_entrypoint(workspace: str, project: Optional[str] = None) -> Op
|
|
|
1204
1674
|
return candidate if os.path.isfile(candidate) else None
|
|
1205
1675
|
|
|
1206
1676
|
|
|
1207
|
-
def dotnet_patch_state(workspace: str) -> Dict[str, Any]:
|
|
1677
|
+
def dotnet_patch_state(workspace: str, root: str = ".") -> Dict[str, Any]:
|
|
1208
1678
|
"""Reports whether the OUMV mount is already present in Program.cs."""
|
|
1209
|
-
|
|
1210
|
-
|
|
1679
|
+
root_dir = _app_root(workspace, root)
|
|
1680
|
+
project = _dotnet_web_project(root_dir)
|
|
1681
|
+
entrypoint = _find_dotnet_entrypoint(root_dir, project)
|
|
1211
1682
|
if not entrypoint:
|
|
1212
1683
|
return {"entrypoint": None, "patched": False, "project": project}
|
|
1213
1684
|
try:
|
|
@@ -1237,15 +1708,15 @@ def _dotnet_build(project: str) -> Tuple[bool, str]:
|
|
|
1237
1708
|
return False, "dotnet build timed out"
|
|
1238
1709
|
|
|
1239
1710
|
|
|
1240
|
-
def _ensure_dotnet_dependency(project: str) -> Optional[str]:
|
|
1241
|
-
"""Adds the NuGet package once; returns
|
|
1711
|
+
def _ensure_dotnet_dependency(project: str) -> Tuple[Optional[str], bool]:
|
|
1712
|
+
"""Adds the NuGet package once; returns (note, mutated)."""
|
|
1242
1713
|
try:
|
|
1243
1714
|
with open(project, "r", encoding="utf-8") as handle:
|
|
1244
1715
|
content = handle.read()
|
|
1245
1716
|
except OSError:
|
|
1246
|
-
return f"could not read {project}"
|
|
1717
|
+
return f"could not read {project}", False
|
|
1247
1718
|
if _DOTNET_PACKAGE in content:
|
|
1248
|
-
return None
|
|
1719
|
+
return None, False
|
|
1249
1720
|
try:
|
|
1250
1721
|
result = subprocess.run(
|
|
1251
1722
|
[_dotnet_cli(), "add", project, "package", _DOTNET_PACKAGE, "--version", _DOTNET_PACKAGE_VERSION],
|
|
@@ -1254,20 +1725,29 @@ def _ensure_dotnet_dependency(project: str) -> Optional[str]:
|
|
|
1254
1725
|
timeout=300,
|
|
1255
1726
|
)
|
|
1256
1727
|
except FileNotFoundError:
|
|
1257
|
-
return
|
|
1728
|
+
return (
|
|
1729
|
+
f"dotnet SDK not found; add <PackageReference Include=\"{_DOTNET_PACKAGE}\" "
|
|
1730
|
+
f"Version=\"{_DOTNET_PACKAGE_VERSION}\" /> manually",
|
|
1731
|
+
False,
|
|
1732
|
+
)
|
|
1258
1733
|
except subprocess.TimeoutExpired:
|
|
1259
|
-
return "dotnet add package timed out"
|
|
1734
|
+
return "dotnet add package timed out", False
|
|
1260
1735
|
if result.returncode != 0:
|
|
1261
|
-
return
|
|
1262
|
-
|
|
1736
|
+
return (
|
|
1737
|
+
f"dotnet add package failed; add the PackageReference manually: "
|
|
1738
|
+
f"{(result.stdout + result.stderr)[-300:]}",
|
|
1739
|
+
False,
|
|
1740
|
+
)
|
|
1741
|
+
return None, True
|
|
1263
1742
|
|
|
1264
1743
|
|
|
1265
|
-
def apply_dotnet_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
|
|
1744
|
+
def apply_dotnet_patch(workspace: str, dry_run: bool = False, root: str = ".") -> Dict[str, Any]:
|
|
1266
1745
|
"""Inserts `using`, `AddTokensafe()` and `UseTokensafe()` between tokensafe markers."""
|
|
1267
|
-
|
|
1746
|
+
root_dir = _app_root(workspace, root)
|
|
1747
|
+
project = _dotnet_web_project(root_dir)
|
|
1268
1748
|
if not project:
|
|
1269
1749
|
return {"status": "skipped", "reason": "no ASP.NET Core (Microsoft.NET.Sdk.Web) project found"}
|
|
1270
|
-
entrypoint = _find_dotnet_entrypoint(
|
|
1750
|
+
entrypoint = _find_dotnet_entrypoint(root_dir, project)
|
|
1271
1751
|
if not entrypoint:
|
|
1272
1752
|
return {"status": "skipped", "reason": "no Program.cs next to the web project"}
|
|
1273
1753
|
|
|
@@ -1329,18 +1809,36 @@ def apply_dotnet_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
|
|
|
1329
1809
|
"preview": f"{builder.group('builder')}.Services.AddTokensafe();\n{app.group('app')}.UseTokensafe();",
|
|
1330
1810
|
}
|
|
1331
1811
|
|
|
1332
|
-
|
|
1333
|
-
os.makedirs(
|
|
1334
|
-
backup_path = os.path.join(backup_dir, os.path.relpath(entrypoint, workspace).replace(os.sep, "__") + ".bak")
|
|
1812
|
+
backup_path = _backup_path(workspace, entrypoint)
|
|
1813
|
+
os.makedirs(os.path.dirname(backup_path), exist_ok=True)
|
|
1335
1814
|
shutil.copy2(entrypoint, backup_path)
|
|
1815
|
+
|
|
1816
|
+
# `dotnet add package` rewrites the csproj: back it up so revert can undo it.
|
|
1817
|
+
project_backup = project_before = project_after = None
|
|
1818
|
+
try:
|
|
1819
|
+
with open(project, "r", encoding="utf-8") as handle:
|
|
1820
|
+
project_before_content = handle.read()
|
|
1821
|
+
except OSError:
|
|
1822
|
+
project_before_content = ""
|
|
1823
|
+
if _DOTNET_PACKAGE not in project_before_content:
|
|
1824
|
+
project_backup = _backup_path(workspace, project)
|
|
1825
|
+
os.makedirs(os.path.dirname(project_backup), exist_ok=True)
|
|
1826
|
+
shutil.copy2(project, project_backup)
|
|
1827
|
+
project_before = _sha256_file(project)
|
|
1828
|
+
|
|
1336
1829
|
with open(entrypoint, "w", encoding="utf-8") as handle:
|
|
1337
1830
|
handle.write(patched)
|
|
1338
1831
|
|
|
1339
|
-
dependency_note = _ensure_dotnet_dependency(project)
|
|
1832
|
+
dependency_note, mutated = _ensure_dotnet_dependency(project)
|
|
1833
|
+
if mutated and project_backup:
|
|
1834
|
+
project_after = _sha256_file(project)
|
|
1340
1835
|
build_ok, build_output = _dotnet_build(project) if dependency_note is None else (False, "skipped")
|
|
1341
1836
|
if not build_ok:
|
|
1342
1837
|
shutil.copy2(backup_path, entrypoint)
|
|
1343
1838
|
os.unlink(backup_path)
|
|
1839
|
+
if project_backup and mutated and os.path.isfile(project_backup):
|
|
1840
|
+
shutil.copy2(project_backup, project)
|
|
1841
|
+
os.unlink(project_backup)
|
|
1344
1842
|
return {
|
|
1345
1843
|
"status": "reverted",
|
|
1346
1844
|
"entrypoint": os.path.relpath(entrypoint, workspace),
|
|
@@ -1348,8 +1846,17 @@ def apply_dotnet_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
|
|
|
1348
1846
|
"build": build_output[-800:],
|
|
1349
1847
|
}
|
|
1350
1848
|
|
|
1351
|
-
_write_manifest(workspace, "dotnet",
|
|
1352
|
-
|
|
1849
|
+
_write_manifest(workspace, "dotnet", {
|
|
1850
|
+
"kind": "dotnet",
|
|
1851
|
+
"app": root,
|
|
1852
|
+
"entrypoint": entrypoint,
|
|
1853
|
+
"backup": backup_path,
|
|
1854
|
+
"framework": "aspnetcore",
|
|
1855
|
+
"project": project,
|
|
1856
|
+
"project_backup": project_backup,
|
|
1857
|
+
"project_before_sha": project_before,
|
|
1858
|
+
"project_after_sha": project_after,
|
|
1859
|
+
})
|
|
1353
1860
|
return {
|
|
1354
1861
|
"status": "patched",
|
|
1355
1862
|
"entrypoint": os.path.relpath(entrypoint, workspace),
|
|
@@ -1361,8 +1868,11 @@ def apply_dotnet_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
|
|
|
1361
1868
|
}
|
|
1362
1869
|
|
|
1363
1870
|
|
|
1364
|
-
def revert_dotnet_patch(
|
|
1365
|
-
|
|
1871
|
+
def revert_dotnet_patch(
|
|
1872
|
+
workspace: str, root: str = ".", manifest: Optional[Dict[str, Any]] = None
|
|
1873
|
+
) -> Dict[str, Any]:
|
|
1874
|
+
if manifest is None:
|
|
1875
|
+
manifest = _read_manifest(workspace, "dotnet", ("dotnet_mount",), app=root)
|
|
1366
1876
|
if manifest is None:
|
|
1367
1877
|
return {"status": "clean", "reason": "no .NET patch manifest"}
|
|
1368
1878
|
entrypoint = manifest.get("entrypoint")
|
|
@@ -1370,8 +1880,37 @@ def revert_dotnet_patch(workspace: str) -> Dict[str, Any]:
|
|
|
1370
1880
|
if not (entrypoint and backup and os.path.isfile(backup)):
|
|
1371
1881
|
return {"status": "error", "reason": "backup missing; restore manually"}
|
|
1372
1882
|
shutil.copy2(backup, entrypoint)
|
|
1883
|
+
project = manifest.get("project") or _dotnet_web_project(workspace)
|
|
1884
|
+
project_backup = manifest.get("project_backup")
|
|
1885
|
+
project_after = manifest.get("project_after_sha")
|
|
1886
|
+
project_status = "unchanged"
|
|
1887
|
+
if project and project_backup and os.path.isfile(project_backup):
|
|
1888
|
+
if project_after and os.path.isfile(project) and _sha256_file(project) != project_after:
|
|
1889
|
+
project_status = "project_modified"
|
|
1890
|
+
else:
|
|
1891
|
+
shutil.copy2(project_backup, project)
|
|
1892
|
+
project_status = "restored"
|
|
1893
|
+
elif project and os.path.isfile(project):
|
|
1894
|
+
# Legacy manifest: no csproj backup, remove only the exact PackageReference.
|
|
1895
|
+
pattern = re.compile(
|
|
1896
|
+
r'[ \t]*<PackageReference\s+Include="' + re.escape(_DOTNET_PACKAGE) + r'"[^>]*/>[ \t]*\r?\n?'
|
|
1897
|
+
)
|
|
1898
|
+
try:
|
|
1899
|
+
with open(project, "r", encoding="utf-8") as handle:
|
|
1900
|
+
content = handle.read()
|
|
1901
|
+
except OSError:
|
|
1902
|
+
content = ""
|
|
1903
|
+
stripped, count = pattern.subn("", content)
|
|
1904
|
+
if count:
|
|
1905
|
+
with open(project, "w", encoding="utf-8") as handle:
|
|
1906
|
+
handle.write(stripped)
|
|
1907
|
+
project_status = "package_reference_removed"
|
|
1373
1908
|
_delete_manifest(manifest)
|
|
1374
|
-
return {
|
|
1909
|
+
return {
|
|
1910
|
+
"status": "reverted",
|
|
1911
|
+
"entrypoint": os.path.relpath(entrypoint, workspace),
|
|
1912
|
+
"project": project_status,
|
|
1913
|
+
}
|
|
1375
1914
|
|
|
1376
1915
|
|
|
1377
1916
|
# Pinned to the backend release: the sidecars are single files, so the cache is
|
|
@@ -1427,13 +1966,28 @@ def sidecar_run_command(kind: str, sidecar_path: str, workspace: str) -> Optiona
|
|
|
1427
1966
|
return None
|
|
1428
1967
|
|
|
1429
1968
|
|
|
1969
|
+
def sidecar_cached(kind: str) -> Tuple[Optional[str], str]:
|
|
1970
|
+
"""Cache-only lookup: `inject --status` must never touch the network."""
|
|
1971
|
+
if kind not in _SIDECARS:
|
|
1972
|
+
return None, f"unknown sidecar {kind!r}"
|
|
1973
|
+
_, filename, expected_sha = _SIDECARS[kind]
|
|
1974
|
+
target = os.path.join(_sidecar_cache_dir(), filename)
|
|
1975
|
+
if os.path.isfile(target) and _sha256_file(target) == expected_sha:
|
|
1976
|
+
return target, f"cached at {_SIDECAR_RELEASE_TAG}"
|
|
1977
|
+
return None, (
|
|
1978
|
+
f"not cached — run `tokensafe inject` to download {_SIDECAR_RELEASE_TAG} "
|
|
1979
|
+
"(or set OUMV_BACKEND_REPO for an unpinned local checkout)"
|
|
1980
|
+
)
|
|
1981
|
+
|
|
1982
|
+
|
|
1430
1983
|
def ensure_sidecar(kind: str) -> Tuple[Optional[str], str]:
|
|
1431
1984
|
"""Caches OumvSpring.java / oumv-php at the pinned release and verifies SHA-256.
|
|
1432
1985
|
|
|
1433
1986
|
Order: a valid cache → a local checkout whose bytes match the pin (developer
|
|
1434
1987
|
flow, no network) → download from the release tag. A hash mismatch is never
|
|
1435
1988
|
accepted silently; the note says what failed instead of handing back a
|
|
1436
|
-
different file under the certified name.
|
|
1989
|
+
different file under the certified name. An explicit `OUMV_BACKEND_REPO` is
|
|
1990
|
+
the only way to use unpinned local bytes, and the note says so.
|
|
1437
1991
|
"""
|
|
1438
1992
|
if kind not in _SIDECARS:
|
|
1439
1993
|
return None, f"unknown sidecar {kind!r}"
|
|
@@ -1453,6 +2007,7 @@ def ensure_sidecar(kind: str) -> Tuple[Optional[str], str]:
|
|
|
1453
2007
|
|
|
1454
2008
|
repo_candidates = []
|
|
1455
2009
|
env_repo = os.environ.get("OUMV_BACKEND_REPO")
|
|
2010
|
+
explicit_repo = bool(env_repo)
|
|
1456
2011
|
if env_repo:
|
|
1457
2012
|
repo_candidates.append(env_repo)
|
|
1458
2013
|
here = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
@@ -1461,6 +2016,7 @@ def ensure_sidecar(kind: str) -> Tuple[Optional[str], str]:
|
|
|
1461
2016
|
os.path.join(here, "..", "tokensafe-backend"),
|
|
1462
2017
|
]
|
|
1463
2018
|
local_mismatch = None
|
|
2019
|
+
explicit_mismatch = None
|
|
1464
2020
|
for repo in repo_candidates:
|
|
1465
2021
|
candidate = os.path.join(os.path.abspath(repo), rel_source)
|
|
1466
2022
|
if not os.path.isfile(candidate):
|
|
@@ -1468,11 +2024,21 @@ def ensure_sidecar(kind: str) -> Tuple[Optional[str], str]:
|
|
|
1468
2024
|
if _sha256_file(candidate) == expected_sha:
|
|
1469
2025
|
return adopt(candidate, f"cached from local checkout matching {_SIDECAR_RELEASE_TAG}")
|
|
1470
2026
|
local_mismatch = candidate
|
|
2027
|
+
if explicit_repo and os.path.abspath(repo) == os.path.abspath(env_repo):
|
|
2028
|
+
explicit_mismatch = candidate
|
|
2029
|
+
|
|
2030
|
+
def explicit_unpinned(note: str) -> Tuple[Optional[str], str]:
|
|
2031
|
+
if explicit_repo and explicit_mismatch:
|
|
2032
|
+
return adopt(explicit_mismatch, f"unpinned (OUMV_BACKEND_REPO): {explicit_mismatch}")
|
|
2033
|
+
return None, note
|
|
1471
2034
|
|
|
1472
2035
|
if os.environ.get("TOKENSAFE_SIDECAR_OFFLINE") == "1":
|
|
1473
2036
|
if local_mismatch:
|
|
1474
|
-
return
|
|
1475
|
-
|
|
2037
|
+
return explicit_unpinned(
|
|
2038
|
+
f"offline and no local sidecar matches {_SIDECAR_RELEASE_TAG}; "
|
|
2039
|
+
f"candidate {local_mismatch} is unpinned (set OUMV_BACKEND_REPO to use it)"
|
|
2040
|
+
)
|
|
2041
|
+
return None, f"offline (TOKENSAFE_SIDECAR_OFFLINE=1) and no cached sidecar matching {_SIDECAR_RELEASE_TAG}"
|
|
1476
2042
|
|
|
1477
2043
|
url = (
|
|
1478
2044
|
f"https://raw.githubusercontent.com/tokensafe-dev/tokensafe-backend/"
|
|
@@ -1485,7 +2051,10 @@ def ensure_sidecar(kind: str) -> Tuple[Optional[str], str]:
|
|
|
1485
2051
|
payload = response.read()
|
|
1486
2052
|
except Exception as exc:
|
|
1487
2053
|
if local_mismatch:
|
|
1488
|
-
return
|
|
2054
|
+
return explicit_unpinned(
|
|
2055
|
+
f"download failed ({exc}); local candidate {local_mismatch} is unpinned "
|
|
2056
|
+
f"(set OUMV_BACKEND_REPO to use it)"
|
|
2057
|
+
)
|
|
1489
2058
|
return None, f"cannot download {url}: {exc}"
|
|
1490
2059
|
|
|
1491
2060
|
actual = hashlib.sha256(payload).hexdigest()
|
|
@@ -1499,76 +2068,160 @@ def ensure_sidecar(kind: str) -> Tuple[Optional[str], str]:
|
|
|
1499
2068
|
return target, f"downloaded from {_SIDECAR_RELEASE_TAG}"
|
|
1500
2069
|
|
|
1501
2070
|
|
|
2071
|
+
def _injectable_apps(stack: Dict[str, Any]) -> List[Dict[str, Any]]:
|
|
2072
|
+
"""Every detected app that can be planned/injected, root first.
|
|
2073
|
+
|
|
2074
|
+
`packages` already holds one row per manifest (role, path, framework), so a
|
|
2075
|
+
monorepo must not collapse to stack["frontend"]/stack["backend"].
|
|
2076
|
+
"""
|
|
2077
|
+
apps: List[Dict[str, Any]] = []
|
|
2078
|
+
seen = set()
|
|
2079
|
+
|
|
2080
|
+
def add(role, app, framework, provider, supported, status, reason=None, info=None):
|
|
2081
|
+
key = (role, app or ".", framework)
|
|
2082
|
+
if key in seen:
|
|
2083
|
+
return
|
|
2084
|
+
seen.add(key)
|
|
2085
|
+
apps.append({
|
|
2086
|
+
"role": role,
|
|
2087
|
+
"app": app or ".",
|
|
2088
|
+
"framework": framework,
|
|
2089
|
+
"provider": provider,
|
|
2090
|
+
"supported": bool(supported),
|
|
2091
|
+
"status": status or "ready",
|
|
2092
|
+
"reason": reason,
|
|
2093
|
+
"info": info or {},
|
|
2094
|
+
})
|
|
2095
|
+
|
|
2096
|
+
for pkg in stack.get("packages") or []:
|
|
2097
|
+
role = pkg.get("role")
|
|
2098
|
+
if role not in ("frontend", "backend"):
|
|
2099
|
+
continue
|
|
2100
|
+
add(role, pkg.get("path") or ".", pkg.get("framework"), pkg.get("provider"),
|
|
2101
|
+
pkg.get("oumvSupported"), pkg.get("status"), pkg.get("reason"), pkg)
|
|
2102
|
+
|
|
2103
|
+
# Defensive: a detector row missing from `packages` still gets an action.
|
|
2104
|
+
for role in ("frontend", "backend"):
|
|
2105
|
+
info = stack.get(role) or {}
|
|
2106
|
+
if not info:
|
|
2107
|
+
continue
|
|
2108
|
+
add(role, info.get("root") or ".", info.get("framework"), info.get("provider"),
|
|
2109
|
+
info.get("oumv_supported", True), info.get("status"), info.get("note"), info)
|
|
2110
|
+
return apps
|
|
2111
|
+
|
|
2112
|
+
|
|
2113
|
+
def _frontend_run(app: str, framework: Optional[str]) -> str:
|
|
2114
|
+
run = "tokensafe dev" if app in (".", "") else f"tokensafe dev {app}"
|
|
2115
|
+
if framework and framework != "react":
|
|
2116
|
+
run += f" --framework {framework}"
|
|
2117
|
+
return run
|
|
2118
|
+
|
|
2119
|
+
|
|
2120
|
+
def _backend_install(catalog: Dict[str, Any], provider: str) -> Optional[str]:
|
|
2121
|
+
entry_id = {
|
|
2122
|
+
"fastapi": "backend/fastapi",
|
|
2123
|
+
"python": "backend/starlette",
|
|
2124
|
+
"go": "backend/go",
|
|
2125
|
+
"node": "backend/node",
|
|
2126
|
+
"elysia": "backend/elysia",
|
|
2127
|
+
"spring": "backend/spring",
|
|
2128
|
+
"php": "backend/php",
|
|
2129
|
+
"dotnet": "backend/aspnetcore",
|
|
2130
|
+
}.get(provider, "backend/go")
|
|
2131
|
+
return catalog.get(entry_id, {}).get("technology", {}).get("package", {}).get("install")
|
|
2132
|
+
|
|
2133
|
+
|
|
1502
2134
|
def plan(workspace: str) -> Dict[str, Any]:
|
|
1503
|
-
"""Describes what apply would do, without touching anything."""
|
|
2135
|
+
"""Describes what apply would do, without touching anything (or the network)."""
|
|
1504
2136
|
stack = detect_project_stack(workspace)
|
|
1505
2137
|
catalog = {entry["id"]: entry for entry in get_adapters_catalog()}
|
|
2138
|
+
apps = _injectable_apps(stack)
|
|
1506
2139
|
actions: List[Dict[str, Any]] = []
|
|
1507
2140
|
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
2141
|
+
for app in apps:
|
|
2142
|
+
root = app["app"]
|
|
2143
|
+
role = app["role"]
|
|
2144
|
+
framework = app["framework"] or ""
|
|
2145
|
+
provider = app["provider"] or ""
|
|
2146
|
+
info = app["info"]
|
|
2147
|
+
if role == "frontend":
|
|
2148
|
+
if framework == "nextjs":
|
|
2149
|
+
root_dir = _app_root(workspace, root)
|
|
2150
|
+
next_state = next_patch_state(workspace, root)
|
|
2151
|
+
action = {
|
|
2152
|
+
"kind": "next_route_handler",
|
|
2153
|
+
"profile": "backend",
|
|
2154
|
+
"app": root,
|
|
2155
|
+
"framework": "nextjs",
|
|
2156
|
+
"writes_repo": True,
|
|
2157
|
+
"already_patched": next_state["patched"],
|
|
2158
|
+
"entrypoint": next_state["entrypoint"]
|
|
2159
|
+
or os.path.relpath(next_route_path(root_dir), workspace),
|
|
2160
|
+
"files": next_state["files"],
|
|
2161
|
+
"missing": next_state["missing"],
|
|
2162
|
+
"bridge": next_state["bridge"],
|
|
2163
|
+
"description": (
|
|
2164
|
+
"three App Router files: api/tokensafe/route.ts (createNextRouteHandlers with bridge: true), "
|
|
2165
|
+
"api/tokensafe/bridge/route.ts (the browser bridge) and instrumentation-client.ts "
|
|
2166
|
+
"(installNextBridge). Server profile plus client components; delete them or --revert to unmount"
|
|
2167
|
+
),
|
|
2168
|
+
"install": "npm install --save-dev tokensafe-backend-node",
|
|
2169
|
+
"run": "next dev",
|
|
2170
|
+
}
|
|
2171
|
+
if next_state["bridge"] == "manual":
|
|
2172
|
+
action["bridge_manual"] = {
|
|
2173
|
+
"reason": "instrumentation-client requires Next >= 15.3; the route files are written, the client loader is not",
|
|
2174
|
+
"snippet": "import { installNextBridge } from 'tokensafe-backend-node/next-bridge';\ninstallNextBridge();",
|
|
2175
|
+
}
|
|
2176
|
+
actions.append(action)
|
|
2177
|
+
continue
|
|
2178
|
+
if not app["supported"]:
|
|
2179
|
+
reason = app["reason"] or f"no OUMV adapter for {framework} yet"
|
|
2180
|
+
actions.append({
|
|
2181
|
+
"kind": "frontend_unsupported",
|
|
2182
|
+
"profile": "frontend",
|
|
2183
|
+
"app": root,
|
|
2184
|
+
"framework": framework,
|
|
2185
|
+
"status": "planned",
|
|
2186
|
+
"writes_repo": False,
|
|
2187
|
+
"reason": reason,
|
|
2188
|
+
"description": reason,
|
|
2189
|
+
})
|
|
2190
|
+
continue
|
|
2191
|
+
frontend_entry = catalog.get(f"frontend/{provider}") or {}
|
|
2192
|
+
actions.append({
|
|
2193
|
+
"kind": "frontend_zero_footprint",
|
|
2194
|
+
"profile": "frontend",
|
|
2195
|
+
"app": root,
|
|
2196
|
+
"framework": f"{provider}/{framework}",
|
|
2197
|
+
"writes_repo": False,
|
|
2198
|
+
"description": "served by `tokensafe dev` (inline Vite config, descriptor in ~/.tokensafe/runtimes)",
|
|
2199
|
+
"run": _frontend_run(root, framework),
|
|
2200
|
+
"install": frontend_entry.get("technology", {}).get("package", {}).get("install"),
|
|
2201
|
+
})
|
|
2202
|
+
continue
|
|
2203
|
+
|
|
2204
|
+
if not app["supported"]:
|
|
2205
|
+
reason = app["reason"] or f"no OUMV adapter for {framework} yet"
|
|
2206
|
+
actions.append({
|
|
2207
|
+
"kind": "backend_unsupported",
|
|
2208
|
+
"profile": "backend",
|
|
2209
|
+
"app": root,
|
|
2210
|
+
"framework": framework,
|
|
2211
|
+
"status": "planned",
|
|
2212
|
+
"writes_repo": False,
|
|
2213
|
+
"reason": reason,
|
|
2214
|
+
"description": reason,
|
|
2215
|
+
})
|
|
2216
|
+
continue
|
|
2217
|
+
|
|
2218
|
+
install = _backend_install(catalog, provider)
|
|
2219
|
+
if provider in ("fastapi", "python") and framework in ("fastapi", "starlette"):
|
|
1568
2220
|
actions.append({
|
|
1569
2221
|
"kind": "python_autoload",
|
|
1570
2222
|
"profile": "backend",
|
|
1571
|
-
"
|
|
2223
|
+
"app": root,
|
|
2224
|
+
"framework": framework,
|
|
1572
2225
|
"writes_repo": False,
|
|
1573
2226
|
"description": (
|
|
1574
2227
|
"sitecustomize patches uvicorn; mount_tokensafe(app) runs on import and detects "
|
|
@@ -1578,22 +2231,40 @@ def plan(workspace: str) -> Dict[str, Any]:
|
|
|
1578
2231
|
"run": python_run_hint(workspace),
|
|
1579
2232
|
})
|
|
1580
2233
|
elif provider == "go":
|
|
1581
|
-
state = go_patch_state(workspace)
|
|
1582
|
-
|
|
1583
|
-
"
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
2234
|
+
state = go_patch_state(workspace, root)
|
|
2235
|
+
if state.get("entrypoint") and (
|
|
2236
|
+
framework == "net/http" or state.get("framework") in ("nethttp", "stdhttp")
|
|
2237
|
+
):
|
|
2238
|
+
actions.append({
|
|
2239
|
+
"kind": "go_manual_recipe",
|
|
2240
|
+
"profile": "backend",
|
|
2241
|
+
"app": root,
|
|
2242
|
+
"framework": "net/http",
|
|
2243
|
+
"writes_repo": True,
|
|
2244
|
+
"entrypoint": state.get("entrypoint"),
|
|
2245
|
+
"status": "manual",
|
|
2246
|
+
"snippet": _GO_MANUAL_SNIPPET,
|
|
2247
|
+
"reason": info.get("note") or "net/http needs the stdhttp adapter's mux",
|
|
2248
|
+
"install": install,
|
|
2249
|
+
})
|
|
2250
|
+
else:
|
|
2251
|
+
actions.append({
|
|
2252
|
+
"kind": "go_one_line_patch",
|
|
2253
|
+
"profile": "backend",
|
|
2254
|
+
"app": root,
|
|
2255
|
+
"framework": framework or "go",
|
|
2256
|
+
"writes_repo": True,
|
|
2257
|
+
"already_patched": state["patched"],
|
|
2258
|
+
"entrypoint": state["entrypoint"],
|
|
2259
|
+
"description": "one AutoMount() line between tokensafe markers; byte-exact backup + --revert",
|
|
2260
|
+
"install": install,
|
|
2261
|
+
})
|
|
1592
2262
|
elif provider == "elysia":
|
|
1593
|
-
state = elysia_patch_state(workspace)
|
|
2263
|
+
state = elysia_patch_state(workspace, root)
|
|
1594
2264
|
actions.append({
|
|
1595
2265
|
"kind": "elysia_plugin_patch",
|
|
1596
2266
|
"profile": "backend",
|
|
2267
|
+
"app": root,
|
|
1597
2268
|
"framework": "elysia",
|
|
1598
2269
|
"writes_repo": True,
|
|
1599
2270
|
"already_patched": state["patched"],
|
|
@@ -1602,11 +2273,12 @@ def plan(workspace: str) -> Dict[str, Any]:
|
|
|
1602
2273
|
"install": install or "bun add tokensafe-backend-node",
|
|
1603
2274
|
})
|
|
1604
2275
|
elif provider == "node":
|
|
1605
|
-
state = node_patch_state(workspace)
|
|
2276
|
+
state = node_patch_state(workspace, root)
|
|
1606
2277
|
actions.append({
|
|
1607
2278
|
"kind": "node_one_line_patch",
|
|
1608
2279
|
"profile": "backend",
|
|
1609
|
-
"
|
|
2280
|
+
"app": root,
|
|
2281
|
+
"framework": state.get("framework") or framework,
|
|
1610
2282
|
"writes_repo": True,
|
|
1611
2283
|
"already_patched": state["patched"],
|
|
1612
2284
|
"entrypoint": state["entrypoint"],
|
|
@@ -1614,10 +2286,11 @@ def plan(workspace: str) -> Dict[str, Any]:
|
|
|
1614
2286
|
"install": install or "npm install tokensafe-backend-node",
|
|
1615
2287
|
})
|
|
1616
2288
|
elif provider == "dotnet":
|
|
1617
|
-
state = dotnet_patch_state(workspace)
|
|
2289
|
+
state = dotnet_patch_state(workspace, root)
|
|
1618
2290
|
actions.append({
|
|
1619
2291
|
"kind": "dotnet_one_line_patch",
|
|
1620
2292
|
"profile": "backend",
|
|
2293
|
+
"app": root,
|
|
1621
2294
|
"framework": "aspnetcore",
|
|
1622
2295
|
"writes_repo": True,
|
|
1623
2296
|
"already_patched": state["patched"],
|
|
@@ -1628,26 +2301,18 @@ def plan(workspace: str) -> Dict[str, Any]:
|
|
|
1628
2301
|
"run": "dotnet run",
|
|
1629
2302
|
})
|
|
1630
2303
|
elif provider in ("spring", "php"):
|
|
1631
|
-
sidecar_path, note =
|
|
1632
|
-
command = sidecar_run_command(provider, sidecar_path or "", workspace)
|
|
2304
|
+
sidecar_path, note = sidecar_cached(provider)
|
|
1633
2305
|
actions.append({
|
|
1634
2306
|
"kind": "sidecar",
|
|
1635
2307
|
"profile": "backend",
|
|
1636
|
-
"
|
|
2308
|
+
"app": root,
|
|
2309
|
+
"framework": framework or provider,
|
|
1637
2310
|
"writes_repo": False,
|
|
1638
2311
|
"sidecar": sidecar_path,
|
|
1639
2312
|
"install": note,
|
|
1640
|
-
"run":
|
|
2313
|
+
"run": sidecar_run_command(provider, sidecar_path or "", workspace),
|
|
1641
2314
|
"description": "static route scan + OCC edits + verify through the single-file sidecar; nothing is written into the project",
|
|
1642
2315
|
})
|
|
1643
|
-
else:
|
|
1644
|
-
actions.append({
|
|
1645
|
-
"kind": "unsupported",
|
|
1646
|
-
"profile": "backend",
|
|
1647
|
-
"framework": backend.get("framework"),
|
|
1648
|
-
"writes_repo": False,
|
|
1649
|
-
"description": "no OUMV adapter for this stack yet — use tokensafe tools instead",
|
|
1650
|
-
})
|
|
1651
2316
|
|
|
1652
2317
|
db = detect_orm(workspace)
|
|
1653
2318
|
for action in actions:
|
|
@@ -1655,7 +2320,7 @@ def plan(workspace: str) -> Dict[str, Any]:
|
|
|
1655
2320
|
|
|
1656
2321
|
return {
|
|
1657
2322
|
"workspace": workspace,
|
|
1658
|
-
"profiles": [p for p in ("frontend", "backend") if
|
|
2323
|
+
"profiles": [p for p in ("frontend", "backend") if any(a["role"] == p for a in apps)],
|
|
1659
2324
|
"actions": actions,
|
|
1660
2325
|
"python_autoload_present": python_autoload_present(),
|
|
1661
2326
|
"revertable": bool(glob.glob(os.path.join(_inject_dir(workspace), "manifests", "*.json")))
|
|
@@ -1664,65 +2329,187 @@ def plan(workspace: str) -> Dict[str, Any]:
|
|
|
1664
2329
|
|
|
1665
2330
|
|
|
1666
2331
|
def apply(workspace: str, dry_run: bool = False, include_go: bool = True) -> Dict[str, Any]:
|
|
1667
|
-
"""Wires
|
|
2332
|
+
"""Wires every detected supported app; a monorepo is not truncated to the first."""
|
|
1668
2333
|
results: Dict[str, Any] = {"workspace": workspace, "actions": []}
|
|
2334
|
+
stack = detect_project_stack(workspace)
|
|
1669
2335
|
|
|
1670
|
-
config, conf_path, created = generate_config(workspace, dry_run=dry_run)
|
|
2336
|
+
config, conf_path, created = generate_config(workspace, stack=stack, dry_run=dry_run)
|
|
1671
2337
|
results["config"] = {
|
|
1672
2338
|
"path": conf_path,
|
|
1673
2339
|
"created": created,
|
|
1674
2340
|
"mutate": config.get("permissions", {}).get("mutate", True),
|
|
2341
|
+
"skipped": config.get("_skipped_reason"),
|
|
1675
2342
|
}
|
|
2343
|
+
if not dry_run and conf_path:
|
|
2344
|
+
_write_config_state(workspace, conf_path, created)
|
|
2345
|
+
|
|
2346
|
+
python_written: Optional[Dict[str, Any]] = None
|
|
2347
|
+
sidecars: Dict[str, Tuple[Optional[str], str]] = {}
|
|
2348
|
+
for app in _injectable_apps(stack):
|
|
2349
|
+
root = app["app"]
|
|
2350
|
+
role = app["role"]
|
|
2351
|
+
framework = app["framework"] or ""
|
|
2352
|
+
provider = app["provider"] or ""
|
|
2353
|
+
if role == "frontend":
|
|
2354
|
+
if framework == "nextjs":
|
|
2355
|
+
results["actions"].append({
|
|
2356
|
+
"kind": "next_route_handler",
|
|
2357
|
+
"profile": "backend",
|
|
2358
|
+
"app": root,
|
|
2359
|
+
**apply_next_patch(workspace, dry_run=dry_run, root=root),
|
|
2360
|
+
})
|
|
2361
|
+
elif not app["supported"]:
|
|
2362
|
+
results["actions"].append({
|
|
2363
|
+
"kind": "frontend_unsupported",
|
|
2364
|
+
"profile": "frontend",
|
|
2365
|
+
"app": root,
|
|
2366
|
+
"status": "planned",
|
|
2367
|
+
"framework": framework,
|
|
2368
|
+
"reason": app["reason"] or f"no OUMV adapter for {framework} yet",
|
|
2369
|
+
})
|
|
2370
|
+
else:
|
|
2371
|
+
results["actions"].append({
|
|
2372
|
+
"kind": "frontend_zero_footprint",
|
|
2373
|
+
"profile": "frontend",
|
|
2374
|
+
"app": root,
|
|
2375
|
+
"status": "ready",
|
|
2376
|
+
"run": _frontend_run(root, framework),
|
|
2377
|
+
"note": "no repository files are written; the bridge lives in the dev-server wrapper",
|
|
2378
|
+
})
|
|
2379
|
+
continue
|
|
1676
2380
|
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
"
|
|
1714
|
-
|
|
1715
|
-
|
|
2381
|
+
if not app["supported"]:
|
|
2382
|
+
results["actions"].append({
|
|
2383
|
+
"kind": "backend_unsupported",
|
|
2384
|
+
"profile": "backend",
|
|
2385
|
+
"app": root,
|
|
2386
|
+
"status": "skipped",
|
|
2387
|
+
"framework": framework,
|
|
2388
|
+
"reason": app["reason"] or f"no OUMV adapter for {framework} yet",
|
|
2389
|
+
})
|
|
2390
|
+
continue
|
|
2391
|
+
|
|
2392
|
+
if provider in ("fastapi", "python") and framework in ("fastapi", "starlette"):
|
|
2393
|
+
if dry_run:
|
|
2394
|
+
action = {
|
|
2395
|
+
"kind": "python_autoload",
|
|
2396
|
+
"status": "would-write",
|
|
2397
|
+
"path": os.path.join(pyhooks_dir(), "sitecustomize.py"),
|
|
2398
|
+
}
|
|
2399
|
+
else:
|
|
2400
|
+
if python_written is None:
|
|
2401
|
+
python_written = ensure_python_autoload()
|
|
2402
|
+
_write_manifest(workspace, "python", {
|
|
2403
|
+
"kind": "python",
|
|
2404
|
+
"app": ".",
|
|
2405
|
+
"path": python_written.get("path"),
|
|
2406
|
+
})
|
|
2407
|
+
action = {"kind": "python_autoload", **python_written, "run": python_run_hint(workspace)}
|
|
2408
|
+
results["actions"].append({"kind": "python_autoload", "profile": "backend", "app": root, **action})
|
|
2409
|
+
elif provider == "go" and include_go:
|
|
2410
|
+
results["actions"].append({
|
|
2411
|
+
"kind": "go_one_line_patch",
|
|
2412
|
+
"profile": "backend",
|
|
2413
|
+
"app": root,
|
|
2414
|
+
**apply_go_patch(workspace, dry_run=dry_run, root=root),
|
|
2415
|
+
})
|
|
2416
|
+
elif provider == "elysia":
|
|
2417
|
+
results["actions"].append({
|
|
2418
|
+
"kind": "elysia_plugin_patch",
|
|
2419
|
+
"profile": "backend",
|
|
2420
|
+
"app": root,
|
|
2421
|
+
**apply_elysia_patch(workspace, dry_run=dry_run, root=root),
|
|
2422
|
+
})
|
|
2423
|
+
elif provider == "node":
|
|
2424
|
+
results["actions"].append({
|
|
2425
|
+
"kind": "node_one_line_patch",
|
|
2426
|
+
"profile": "backend",
|
|
2427
|
+
"app": root,
|
|
2428
|
+
**apply_node_patch(workspace, dry_run=dry_run, root=root),
|
|
2429
|
+
})
|
|
2430
|
+
elif provider == "dotnet":
|
|
2431
|
+
results["actions"].append({
|
|
2432
|
+
"kind": "dotnet_one_line_patch",
|
|
2433
|
+
"profile": "backend",
|
|
2434
|
+
"app": root,
|
|
2435
|
+
**apply_dotnet_patch(workspace, dry_run=dry_run, root=root),
|
|
2436
|
+
})
|
|
2437
|
+
elif provider in ("spring", "php"):
|
|
2438
|
+
if provider not in sidecars:
|
|
2439
|
+
sidecars[provider] = (
|
|
2440
|
+
sidecar_cached(provider) if dry_run else ensure_sidecar(provider)
|
|
2441
|
+
)
|
|
2442
|
+
sidecar_path, note = sidecars[provider]
|
|
2443
|
+
results["actions"].append({
|
|
2444
|
+
"kind": "sidecar",
|
|
2445
|
+
"profile": "backend",
|
|
2446
|
+
"app": root,
|
|
2447
|
+
"status": "ready" if sidecar_path else "needs-source",
|
|
2448
|
+
"sidecar": sidecar_path,
|
|
2449
|
+
"note": note,
|
|
2450
|
+
"run": sidecar_run_command(provider, sidecar_path or "", workspace),
|
|
2451
|
+
})
|
|
1716
2452
|
|
|
1717
2453
|
return results
|
|
1718
2454
|
|
|
1719
2455
|
|
|
2456
|
+
def _revert_manifest(workspace: str, kind: str, manifest: Dict[str, Any]) -> Dict[str, Any]:
|
|
2457
|
+
app = manifest.get("app") or "."
|
|
2458
|
+
if kind == "go":
|
|
2459
|
+
return revert_go_patch(workspace, app, manifest)
|
|
2460
|
+
if kind == "node":
|
|
2461
|
+
return revert_node_patch(workspace, app, manifest)
|
|
2462
|
+
if kind == "elysia":
|
|
2463
|
+
return revert_elysia_patch(workspace, app, manifest)
|
|
2464
|
+
if kind == "dotnet":
|
|
2465
|
+
return revert_dotnet_patch(workspace, app, manifest)
|
|
2466
|
+
if kind == "next":
|
|
2467
|
+
return revert_next_patch(workspace, app, manifest)
|
|
2468
|
+
if kind == "python":
|
|
2469
|
+
return revert_python_autoload(workspace, manifest)
|
|
2470
|
+
return {"status": "error", "reason": f"unknown manifest kind {kind!r}"}
|
|
2471
|
+
|
|
2472
|
+
|
|
1720
2473
|
def revert(workspace: str) -> Dict[str, Any]:
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
"
|
|
1725
|
-
|
|
1726
|
-
|
|
1727
|
-
|
|
1728
|
-
|
|
2474
|
+
"""Reverts every per-app manifest, then the config state."""
|
|
2475
|
+
results: Dict[str, Any] = {"workspace": workspace}
|
|
2476
|
+
for kind in ("go", "node", "elysia", "dotnet", "next", "python"):
|
|
2477
|
+
results[kind] = {"status": "nothing-to-revert"}
|
|
2478
|
+
|
|
2479
|
+
base = os.path.join(_inject_dir(workspace), "manifests")
|
|
2480
|
+
for path in sorted(glob.glob(os.path.join(base, "*.json"))):
|
|
2481
|
+
try:
|
|
2482
|
+
with open(path, "r", encoding="utf-8") as handle:
|
|
2483
|
+
manifest = json.load(handle)
|
|
2484
|
+
except Exception:
|
|
2485
|
+
continue
|
|
2486
|
+
manifest["_manifest"] = path
|
|
2487
|
+
kind = manifest.get("kind") or os.path.basename(path).split("--")[0][:-5]
|
|
2488
|
+
app = manifest.get("app") or "."
|
|
2489
|
+
key = kind if app in (".", "") else f"{kind}@{app}"
|
|
2490
|
+
results[key] = _revert_manifest(workspace, kind, manifest)
|
|
2491
|
+
|
|
2492
|
+
legacy = os.path.join(_inject_dir(workspace), "manifest.json")
|
|
2493
|
+
if os.path.isfile(legacy):
|
|
2494
|
+
try:
|
|
2495
|
+
with open(legacy, "r", encoding="utf-8") as handle:
|
|
2496
|
+
manifest = json.load(handle)
|
|
2497
|
+
except Exception:
|
|
2498
|
+
manifest = {}
|
|
2499
|
+
if manifest:
|
|
2500
|
+
manifest["_manifest"] = legacy
|
|
2501
|
+
kind = {
|
|
2502
|
+
"serve": "go",
|
|
2503
|
+
"mount": "go",
|
|
2504
|
+
"go_patch": "go",
|
|
2505
|
+
"node_mount": "node",
|
|
2506
|
+
"elysia_plugin": "elysia",
|
|
2507
|
+
"dotnet_mount": "dotnet",
|
|
2508
|
+
"next_route": "next",
|
|
2509
|
+
"next_route_v2": "next",
|
|
2510
|
+
}.get(manifest.get("mode"), "")
|
|
2511
|
+
if kind:
|
|
2512
|
+
results[kind] = _revert_manifest(workspace, kind, manifest)
|
|
2513
|
+
|
|
2514
|
+
results["config"] = revert_config(workspace)
|
|
2515
|
+
return results
|