tokensafe 4.12.3 → 4.13.1
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 +1026 -279
- 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/proxy.py +6 -5
- 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,73 @@ 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
|
+
payload = {
|
|
271
|
+
"path": path,
|
|
272
|
+
"created": bool(created),
|
|
273
|
+
"sha": _sha256_file(path) if created and path and os.path.isfile(path) else None,
|
|
274
|
+
}
|
|
275
|
+
with open(state_path, "w", encoding="utf-8") as handle:
|
|
276
|
+
json.dump(payload, handle, indent=2)
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def revert_config(workspace: str) -> Dict[str, Any]:
|
|
280
|
+
"""Removes .tokensafe/oumv.json only when inject created it and it is unchanged."""
|
|
281
|
+
state_path = _config_state_path(workspace)
|
|
282
|
+
if not os.path.isfile(state_path):
|
|
283
|
+
return {"status": "nothing-to-revert"}
|
|
284
|
+
try:
|
|
285
|
+
with open(state_path, "r", encoding="utf-8") as handle:
|
|
286
|
+
state = json.load(handle)
|
|
287
|
+
except Exception:
|
|
288
|
+
return {"status": "error", "reason": "unreadable config state"}
|
|
289
|
+
os.unlink(state_path)
|
|
290
|
+
path = state.get("path")
|
|
291
|
+
if not state.get("created"):
|
|
292
|
+
return {"status": "preserved", "reason": "config existed before inject"}
|
|
293
|
+
if not path or not os.path.isfile(path):
|
|
294
|
+
return {"status": "absent"}
|
|
295
|
+
sha = state.get("sha")
|
|
296
|
+
if sha and _sha256_file(path) != sha:
|
|
297
|
+
return {"status": "config_modified", "path": path}
|
|
298
|
+
os.remove(path)
|
|
299
|
+
return {"status": "removed", "path": path}
|
|
300
|
+
|
|
301
|
+
|
|
198
302
|
def backend_env(env: Optional[Dict[str, str]] = None) -> Dict[str, str]:
|
|
199
303
|
"""Environment that activates the Python autoload hook without touching the repo."""
|
|
200
304
|
base = dict(env if env is not None else os.environ)
|
|
@@ -232,7 +336,11 @@ def _go_candidates(workspace: str) -> List[str]:
|
|
|
232
336
|
|
|
233
337
|
|
|
234
338
|
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.
|
|
339
|
+
"""Returns (path, framework) for the first main.go that looks mountable.
|
|
340
|
+
|
|
341
|
+
`nethttp`/`stdhttp` are returned too: they cannot be auto-patched, but a
|
|
342
|
+
silent miss reads as "no Go app" when the honest answer is a manual recipe.
|
|
343
|
+
"""
|
|
236
344
|
for path in _go_candidates(workspace):
|
|
237
345
|
try:
|
|
238
346
|
with open(path, "r", encoding="utf-8", errors="replace") as f:
|
|
@@ -247,9 +355,11 @@ def find_go_entrypoint(workspace: str, framework: Optional[str] = None) -> Tuple
|
|
|
247
355
|
detected = "chi"
|
|
248
356
|
elif "tokensafe-dev/tokensafe-backend/go/pkg/adapters/stdhttp" in source:
|
|
249
357
|
detected = "stdhttp"
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
if detected
|
|
358
|
+
elif "http.NewServeMux(" in source:
|
|
359
|
+
detected = "nethttp"
|
|
360
|
+
if detected in _GO_ADAPTERS and "func main(" in source:
|
|
361
|
+
return path, detected
|
|
362
|
+
if detected in ("stdhttp", "nethttp") and "func main(" in source:
|
|
253
363
|
return path, detected
|
|
254
364
|
return None, None
|
|
255
365
|
|
|
@@ -278,8 +388,8 @@ def _go_anchor(source: str, framework: str) -> Optional[int]:
|
|
|
278
388
|
return None
|
|
279
389
|
|
|
280
390
|
|
|
281
|
-
def go_patch_state(workspace: str) -> Dict[str, Any]:
|
|
282
|
-
path, framework = find_go_entrypoint(workspace)
|
|
391
|
+
def go_patch_state(workspace: str, root: str = ".") -> Dict[str, Any]:
|
|
392
|
+
path, framework = find_go_entrypoint(_app_root(workspace, root))
|
|
283
393
|
if not path:
|
|
284
394
|
return {"patched": False, "entrypoint": None, "framework": None}
|
|
285
395
|
with open(path, "r", encoding="utf-8") as f:
|
|
@@ -417,6 +527,51 @@ def _wrap_go_serve(source: str, framework: str) -> Optional[Tuple[str, str]]:
|
|
|
417
527
|
return None
|
|
418
528
|
|
|
419
529
|
|
|
530
|
+
def _go_origin_from_addr(addr: str, scheme: str = "http") -> Optional[str]:
|
|
531
|
+
"""`":8080"` / `"0.0.0.0:8080"` -> `http://127.0.0.1:8080`; dynamic addrs -> None."""
|
|
532
|
+
addr = str(addr or "").strip().strip('"').strip()
|
|
533
|
+
if not addr or "(" in addr or "$" in addr:
|
|
534
|
+
return None
|
|
535
|
+
host, sep, port = addr.rpartition(":")
|
|
536
|
+
if not sep or not port.isdigit() or int(port) == 0:
|
|
537
|
+
return None
|
|
538
|
+
host = host.strip("[]")
|
|
539
|
+
if host in ("", "0.0.0.0", "::", "+", "*"):
|
|
540
|
+
host = "127.0.0.1"
|
|
541
|
+
return f"{scheme}://{host}:{port}"
|
|
542
|
+
|
|
543
|
+
|
|
544
|
+
def _go_literal_listen_addr(source: str, framework: str) -> Optional[str]:
|
|
545
|
+
"""The origin a mounted runtime can honestly advertise, when the source names it.
|
|
546
|
+
|
|
547
|
+
The port must be a literal: `r.Run(port())` or an env lookup is not a fact the
|
|
548
|
+
injector may bake into the discovery registry.
|
|
549
|
+
"""
|
|
550
|
+
if framework == "gin":
|
|
551
|
+
for match in re.finditer(r'\.Run\(\s*"([^"]+)"\s*\)', source):
|
|
552
|
+
origin = _go_origin_from_addr(match.group(1))
|
|
553
|
+
if origin:
|
|
554
|
+
return origin
|
|
555
|
+
return None
|
|
556
|
+
if framework == "chi":
|
|
557
|
+
match = re.search(r'http\.ListenAndServeTLS\(\s*"([^"]+)"', source)
|
|
558
|
+
if match:
|
|
559
|
+
origin = _go_origin_from_addr(match.group(1), "https")
|
|
560
|
+
if origin:
|
|
561
|
+
return origin
|
|
562
|
+
match = re.search(r'http\.ListenAndServe\(\s*"([^"]+)"', source)
|
|
563
|
+
if match:
|
|
564
|
+
origin = _go_origin_from_addr(match.group(1))
|
|
565
|
+
if origin:
|
|
566
|
+
return origin
|
|
567
|
+
# `srv := &http.Server{Addr: ":9090", ...}; srv.ListenAndServe()`
|
|
568
|
+
match = re.search(r'Addr:\s*"([^"]+)"', source)
|
|
569
|
+
if match:
|
|
570
|
+
scheme = "https" if "ListenAndServeTLS(" in source else "http"
|
|
571
|
+
return _go_origin_from_addr(match.group(1), scheme)
|
|
572
|
+
return None
|
|
573
|
+
|
|
574
|
+
|
|
420
575
|
def _ensure_std_import(source: str, package: str) -> str:
|
|
421
576
|
if re.search(r'^\s*(?:\w+\s+)?"%s"\s*$' % re.escape(package), source, re.M):
|
|
422
577
|
return source
|
|
@@ -429,17 +584,29 @@ def _ensure_std_import(source: str, package: str) -> str:
|
|
|
429
584
|
return source[: line_end + 1] + f'\t"{package}"\n' + source[line_end + 1 :]
|
|
430
585
|
|
|
431
586
|
|
|
432
|
-
def apply_go_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
|
|
587
|
+
def apply_go_patch(workspace: str, dry_run: bool = False, root: str = ".") -> Dict[str, Any]:
|
|
433
588
|
"""Ensures the module dependency, inserts the AutoMount call, validates with `go build`.
|
|
434
589
|
|
|
435
590
|
The original file is backed up first and restored byte-for-byte if any step fails.
|
|
436
591
|
"""
|
|
437
|
-
|
|
592
|
+
root_dir = _app_root(workspace, root)
|
|
593
|
+
path, framework = find_go_entrypoint(root_dir)
|
|
438
594
|
if not path or not framework:
|
|
439
595
|
return {"status": "skipped", "reason": "no mountable Go entrypoint (main.go with gin/chi/net/http) found"}
|
|
596
|
+
if framework in ("nethttp", "stdhttp"):
|
|
597
|
+
return {
|
|
598
|
+
"status": "manual",
|
|
599
|
+
"entrypoint": os.path.relpath(path, workspace),
|
|
600
|
+
"framework": "net/http",
|
|
601
|
+
"reason": (
|
|
602
|
+
"net/http needs the stdhttp adapter's mux; replace http.NewServeMux() "
|
|
603
|
+
"with oumvstdhttp.NewServeMux(rt) and mount the RPC path"
|
|
604
|
+
),
|
|
605
|
+
"snippet": _GO_MANUAL_SNIPPET,
|
|
606
|
+
}
|
|
440
607
|
|
|
441
608
|
if not dry_run:
|
|
442
|
-
dep_error = _ensure_go_dependency(
|
|
609
|
+
dep_error = _ensure_go_dependency(root_dir)
|
|
443
610
|
if dep_error:
|
|
444
611
|
return {"status": "skipped", "reason": dep_error}
|
|
445
612
|
|
|
@@ -462,7 +629,15 @@ def apply_go_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
|
|
|
462
629
|
patched, preview = wrapped
|
|
463
630
|
patched = _ensure_std_import(patched, "log")
|
|
464
631
|
else:
|
|
465
|
-
|
|
632
|
+
mount_call = call.rstrip("\n")
|
|
633
|
+
public_url = _go_literal_listen_addr(original, framework)
|
|
634
|
+
if public_url:
|
|
635
|
+
# §9.2: a mounted runtime cannot recover the listen address itself, so the
|
|
636
|
+
# literal one from the serve call is handed over explicitly.
|
|
637
|
+
mount_call = mount_call.replace(
|
|
638
|
+
"AutoMount(r)", f'AutoMount(r, {alias}.Options{{PublicURL: "{public_url}"}})'
|
|
639
|
+
)
|
|
640
|
+
insert = f"\t{_MARK_BEGIN}\n{mount_call}\n\t{_MARK_END}\n"
|
|
466
641
|
patched = original[:anchor] + insert + original[anchor:]
|
|
467
642
|
preview = insert.strip()
|
|
468
643
|
|
|
@@ -483,28 +658,31 @@ def apply_go_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
|
|
|
483
658
|
"preview": preview,
|
|
484
659
|
}
|
|
485
660
|
|
|
486
|
-
|
|
487
|
-
os.makedirs(
|
|
488
|
-
suffix = os.path.relpath(path, workspace).replace(os.sep, "__") + ".bak"
|
|
489
|
-
backup_path = os.path.join(backup_dir, suffix)
|
|
661
|
+
backup_path = _backup_path(workspace, path)
|
|
662
|
+
os.makedirs(os.path.dirname(backup_path), exist_ok=True)
|
|
490
663
|
shutil.copy2(path, backup_path)
|
|
491
|
-
module_backups: List[
|
|
664
|
+
module_backups: List[Dict[str, str]] = []
|
|
492
665
|
for mod_file in ("go.mod", "go.sum"):
|
|
493
|
-
src = os.path.join(
|
|
666
|
+
src = os.path.join(root_dir, mod_file)
|
|
494
667
|
if os.path.isfile(src):
|
|
495
|
-
dst =
|
|
668
|
+
dst = _backup_path(workspace, src)
|
|
669
|
+
os.makedirs(os.path.dirname(dst), exist_ok=True)
|
|
496
670
|
shutil.copy2(src, dst)
|
|
497
|
-
module_backups.append(
|
|
671
|
+
module_backups.append({
|
|
672
|
+
"path": src,
|
|
673
|
+
"backup": dst,
|
|
674
|
+
"before_sha": _sha256_file(src),
|
|
675
|
+
})
|
|
498
676
|
|
|
499
677
|
with open(path, "w", encoding="utf-8") as f:
|
|
500
678
|
f.write(patched)
|
|
501
679
|
|
|
502
|
-
tidy_ok, tidy_output = _go_tidy(
|
|
503
|
-
build_ok, build_output = _go_build(
|
|
680
|
+
tidy_ok, tidy_output = _go_tidy(root_dir)
|
|
681
|
+
build_ok, build_output = _go_build(root_dir) if tidy_ok else (False, tidy_output)
|
|
504
682
|
if not build_ok:
|
|
505
683
|
shutil.copy2(backup_path, path)
|
|
506
|
-
for
|
|
507
|
-
shutil.copy2(
|
|
684
|
+
for module in module_backups:
|
|
685
|
+
shutil.copy2(module["backup"], module["path"])
|
|
508
686
|
first_error = next((line for line in build_output.splitlines() if line.strip()), "")
|
|
509
687
|
return {
|
|
510
688
|
"status": "reverted",
|
|
@@ -513,11 +691,16 @@ def apply_go_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
|
|
|
513
691
|
"build_output": build_output[-1200:],
|
|
514
692
|
}
|
|
515
693
|
|
|
694
|
+
for module in module_backups:
|
|
695
|
+
module["after_sha"] = _sha256_file(module["path"])
|
|
516
696
|
_write_manifest(workspace, "go", {
|
|
697
|
+
"kind": "go",
|
|
698
|
+
"app": root,
|
|
517
699
|
"entrypoint": path,
|
|
518
700
|
"backup": backup_path,
|
|
519
701
|
"framework": framework,
|
|
520
702
|
"mode": "serve" if wrapped is not None else "mount",
|
|
703
|
+
"modules": module_backups,
|
|
521
704
|
})
|
|
522
705
|
|
|
523
706
|
return {
|
|
@@ -547,8 +730,11 @@ def _go_build(workspace: str) -> Tuple[bool, str]:
|
|
|
547
730
|
return True, f"build validation failed to run: {exc}"
|
|
548
731
|
|
|
549
732
|
|
|
550
|
-
def revert_go_patch(
|
|
551
|
-
|
|
733
|
+
def revert_go_patch(
|
|
734
|
+
workspace: str, root: str = ".", manifest: Optional[Dict[str, Any]] = None
|
|
735
|
+
) -> Dict[str, Any]:
|
|
736
|
+
if manifest is None:
|
|
737
|
+
manifest = _read_manifest(workspace, "go", ("serve", "mount", "go_patch"), app=root)
|
|
552
738
|
if manifest is None:
|
|
553
739
|
return {"status": "nothing-to-revert"}
|
|
554
740
|
target = manifest.get("entrypoint")
|
|
@@ -556,8 +742,24 @@ def revert_go_patch(workspace: str) -> Dict[str, Any]:
|
|
|
556
742
|
if not target or not backup or not os.path.isfile(backup):
|
|
557
743
|
return {"status": "error", "reason": "backup missing"}
|
|
558
744
|
shutil.copy2(backup, target)
|
|
745
|
+
modules: List[Dict[str, str]] = []
|
|
746
|
+
for module in manifest.get("modules") or []:
|
|
747
|
+
path, module_backup = module.get("path"), module.get("backup")
|
|
748
|
+
after = module.get("after_sha")
|
|
749
|
+
if not (path and module_backup and os.path.isfile(module_backup)):
|
|
750
|
+
modules.append({"path": path or "?", "status": "backup-missing"})
|
|
751
|
+
continue
|
|
752
|
+
if after and os.path.isfile(path) and _sha256_file(path) != after:
|
|
753
|
+
modules.append({"path": os.path.relpath(path, workspace), "status": "modules_modified"})
|
|
754
|
+
continue
|
|
755
|
+
shutil.copy2(module_backup, path)
|
|
756
|
+
modules.append({"path": os.path.relpath(path, workspace), "status": "restored"})
|
|
559
757
|
_delete_manifest(manifest)
|
|
560
|
-
return {
|
|
758
|
+
return {
|
|
759
|
+
"status": "reverted",
|
|
760
|
+
"entrypoint": os.path.relpath(target, workspace),
|
|
761
|
+
"modules": modules,
|
|
762
|
+
}
|
|
561
763
|
|
|
562
764
|
|
|
563
765
|
# --------------------------------------------------------------------------- #
|
|
@@ -605,27 +807,112 @@ def _node_framework_of(workspace: str) -> Optional[str]:
|
|
|
605
807
|
return None
|
|
606
808
|
|
|
607
809
|
|
|
608
|
-
def node_patch_state(workspace: str) -> Dict[str, Any]:
|
|
810
|
+
def node_patch_state(workspace: str, root: str = ".") -> Dict[str, Any]:
|
|
609
811
|
"""Reports whether the one-line OUMV mount is already in the Node entrypoint."""
|
|
610
|
-
|
|
812
|
+
root_dir = _app_root(workspace, root)
|
|
813
|
+
path = _find_node_entrypoint(root_dir)
|
|
814
|
+
framework = _node_framework_of(root_dir)
|
|
611
815
|
if not path:
|
|
612
|
-
return {"entrypoint": None, "patched": False, "framework":
|
|
816
|
+
return {"entrypoint": None, "patched": False, "framework": framework}
|
|
613
817
|
try:
|
|
614
818
|
with open(path, "r", encoding="utf-8") as f:
|
|
615
819
|
source = f.read()
|
|
616
820
|
except OSError:
|
|
617
|
-
return {"entrypoint": path, "patched": False, "framework":
|
|
821
|
+
return {"entrypoint": path, "patched": False, "framework": framework}
|
|
618
822
|
return {
|
|
619
823
|
"entrypoint": os.path.relpath(path, workspace),
|
|
620
824
|
"patched": _MARK_BEGIN in source and _MARK_END in source,
|
|
621
|
-
"framework":
|
|
825
|
+
"framework": framework,
|
|
622
826
|
}
|
|
623
827
|
|
|
624
828
|
|
|
625
|
-
|
|
829
|
+
_NODE_PACKAGE = "tokensafe-backend-node"
|
|
830
|
+
|
|
831
|
+
|
|
832
|
+
def _node_package_dir(workspace: str, entrypoint: str) -> str:
|
|
833
|
+
"""Nearest directory holding a package.json, confined to the workspace."""
|
|
834
|
+
root = os.path.abspath(workspace)
|
|
835
|
+
current = os.path.dirname(os.path.abspath(entrypoint))
|
|
836
|
+
while True:
|
|
837
|
+
if os.path.isfile(os.path.join(current, "package.json")):
|
|
838
|
+
return current
|
|
839
|
+
parent = os.path.dirname(current)
|
|
840
|
+
if parent == current or os.path.abspath(current) == root:
|
|
841
|
+
return current if os.path.isdir(current) else root
|
|
842
|
+
current = parent
|
|
843
|
+
|
|
844
|
+
|
|
845
|
+
def _node_install_command(package_dir: str) -> Tuple[List[str], str]:
|
|
846
|
+
"""(argv, manager) for an exact install of the Node adapter package."""
|
|
847
|
+
package = f"{_NODE_PACKAGE}@{BACKEND_NPM_VERSION}"
|
|
848
|
+
markers = (
|
|
849
|
+
("bun.lock", ["bun", "add"], "bun"),
|
|
850
|
+
("bun.lockb", ["bun", "add"], "bun"),
|
|
851
|
+
("pnpm-lock.yaml", ["pnpm", "add", "--save-exact"], "pnpm"),
|
|
852
|
+
("yarn.lock", ["yarn", "add", "--exact"], "yarn"),
|
|
853
|
+
("package-lock.json", ["npm", "install", "--save-exact"], "npm"),
|
|
854
|
+
)
|
|
855
|
+
for marker, prefix, manager in markers:
|
|
856
|
+
if os.path.isfile(os.path.join(package_dir, marker)):
|
|
857
|
+
return [*prefix, package], manager
|
|
858
|
+
return ["npm", "install", "--save-exact", package], "npm"
|
|
859
|
+
|
|
860
|
+
|
|
861
|
+
def _node_package_installed(package_dir: str) -> bool:
|
|
862
|
+
return os.path.isdir(os.path.join(package_dir, "node_modules", _NODE_PACKAGE))
|
|
863
|
+
|
|
864
|
+
|
|
865
|
+
def _install_node_package(workspace: str, entrypoint: str) -> Dict[str, Any]:
|
|
866
|
+
"""Installs the adapter through the app's own package manager.
|
|
867
|
+
|
|
868
|
+
A missing or failed install must never leave an unresolvable `require`
|
|
869
|
+
behind, so the caller skips the patch instead of writing a broken line.
|
|
870
|
+
``TOKENSAFE_INJECT_NO_INSTALL=1`` is the explicit opt-out (the plan already
|
|
871
|
+
names the exact command).
|
|
872
|
+
"""
|
|
873
|
+
package_dir = _node_package_dir(workspace, entrypoint)
|
|
874
|
+
argv, manager = _node_install_command(package_dir)
|
|
875
|
+
command = " ".join(argv)
|
|
876
|
+
if _node_package_installed(package_dir):
|
|
877
|
+
return {"status": "already_installed", "manager": manager, "command": command}
|
|
878
|
+
if os.environ.get("TOKENSAFE_INJECT_NO_INSTALL") == "1":
|
|
879
|
+
return {"status": "opted_out", "manager": manager, "command": command}
|
|
880
|
+
try:
|
|
881
|
+
proc = subprocess.run(
|
|
882
|
+
argv, cwd=package_dir, capture_output=True, text=True, timeout=180
|
|
883
|
+
)
|
|
884
|
+
except FileNotFoundError:
|
|
885
|
+
return {
|
|
886
|
+
"status": "unavailable",
|
|
887
|
+
"manager": manager,
|
|
888
|
+
"command": command,
|
|
889
|
+
"reason": f"{argv[0]} is not on PATH",
|
|
890
|
+
}
|
|
891
|
+
except subprocess.TimeoutExpired:
|
|
892
|
+
return {
|
|
893
|
+
"status": "unavailable",
|
|
894
|
+
"manager": manager,
|
|
895
|
+
"command": command,
|
|
896
|
+
"reason": "install timed out after 180s",
|
|
897
|
+
}
|
|
898
|
+
except OSError as exc:
|
|
899
|
+
return {"status": "unavailable", "manager": manager, "command": command, "reason": str(exc)}
|
|
900
|
+
if proc.returncode != 0:
|
|
901
|
+
tail = (proc.stderr or proc.stdout or "").strip().splitlines()
|
|
902
|
+
return {
|
|
903
|
+
"status": "failed",
|
|
904
|
+
"manager": manager,
|
|
905
|
+
"command": command,
|
|
906
|
+
"reason": f"exit {proc.returncode}: {tail[-1] if tail else 'no output'}",
|
|
907
|
+
}
|
|
908
|
+
return {"status": "installed", "manager": manager, "command": command}
|
|
909
|
+
|
|
910
|
+
|
|
911
|
+
def apply_node_patch(workspace: str, dry_run: bool = False, root: str = ".") -> Dict[str, Any]:
|
|
626
912
|
"""Inserts one mount line between tokensafe markers, with a byte-exact backup."""
|
|
627
|
-
|
|
628
|
-
|
|
913
|
+
root_dir = _app_root(workspace, root)
|
|
914
|
+
framework = _node_framework_of(root_dir)
|
|
915
|
+
path = _find_node_entrypoint(root_dir)
|
|
629
916
|
if framework not in ("express", "fastify"):
|
|
630
917
|
return {"status": "skipped", "reason": "no supported Node framework (express/fastify) found"}
|
|
631
918
|
if not path:
|
|
@@ -662,16 +949,42 @@ def apply_node_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
|
|
|
662
949
|
insert_at = len(source) if line_end < 0 else line_end + 1
|
|
663
950
|
patched = source[:insert_at] + mount + source[insert_at:]
|
|
664
951
|
|
|
952
|
+
argv, manager = _node_install_command(_node_package_dir(root_dir, path))
|
|
953
|
+
planned_install = {"status": "planned", "manager": manager, "command": " ".join(argv)}
|
|
665
954
|
if dry_run:
|
|
666
|
-
return {
|
|
955
|
+
return {
|
|
956
|
+
"status": "dry_run",
|
|
957
|
+
"entrypoint": os.path.relpath(path, workspace),
|
|
958
|
+
"preview": mount.strip(),
|
|
959
|
+
"install": planned_install,
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
install = _install_node_package(root_dir, path)
|
|
963
|
+
if install["status"] in ("failed", "unavailable"):
|
|
964
|
+
return {
|
|
965
|
+
"status": "skipped",
|
|
966
|
+
"entrypoint": os.path.relpath(path, workspace),
|
|
967
|
+
"framework": framework,
|
|
968
|
+
"install": install,
|
|
969
|
+
"reason": (
|
|
970
|
+
f"could not install {_NODE_PACKAGE} ({install.get('reason')}); "
|
|
971
|
+
f"run `{install['command']}` and retry"
|
|
972
|
+
),
|
|
973
|
+
}
|
|
667
974
|
|
|
668
|
-
|
|
669
|
-
os.makedirs(
|
|
670
|
-
backup_path = os.path.join(backup_dir, os.path.relpath(path, workspace).replace(os.sep, "__") + ".bak")
|
|
975
|
+
backup_path = _backup_path(workspace, path)
|
|
976
|
+
os.makedirs(os.path.dirname(backup_path), exist_ok=True)
|
|
671
977
|
shutil.copy2(path, backup_path)
|
|
672
978
|
with open(path, "w", encoding="utf-8") as f:
|
|
673
979
|
f.write(patched)
|
|
674
|
-
_write_manifest(workspace, "node", {
|
|
980
|
+
_write_manifest(workspace, "node", {
|
|
981
|
+
"kind": "node",
|
|
982
|
+
"app": root,
|
|
983
|
+
"entrypoint": path,
|
|
984
|
+
"backup": backup_path,
|
|
985
|
+
"framework": framework,
|
|
986
|
+
"install": install,
|
|
987
|
+
})
|
|
675
988
|
return {
|
|
676
989
|
"status": "patched",
|
|
677
990
|
"entrypoint": os.path.relpath(path, workspace),
|
|
@@ -679,11 +992,15 @@ def apply_node_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
|
|
|
679
992
|
"mode": "node_mount",
|
|
680
993
|
"backup": backup_path,
|
|
681
994
|
"line": mount.splitlines()[1],
|
|
995
|
+
"install": install,
|
|
682
996
|
}
|
|
683
997
|
|
|
684
998
|
|
|
685
|
-
def revert_node_patch(
|
|
686
|
-
|
|
999
|
+
def revert_node_patch(
|
|
1000
|
+
workspace: str, root: str = ".", manifest: Optional[Dict[str, Any]] = None
|
|
1001
|
+
) -> Dict[str, Any]:
|
|
1002
|
+
if manifest is None:
|
|
1003
|
+
manifest = _read_manifest(workspace, "node", ("node_mount",), app=root)
|
|
687
1004
|
if manifest is None:
|
|
688
1005
|
return {"status": "clean", "reason": "no Node patch manifest"}
|
|
689
1006
|
entrypoint = manifest.get("entrypoint")
|
|
@@ -718,10 +1035,12 @@ def _elysia_app_reference(source: str) -> Optional[Tuple[str, str, int]]:
|
|
|
718
1035
|
return created.group("var"), created.group("indent"), insert_at
|
|
719
1036
|
|
|
720
1037
|
|
|
721
|
-
def elysia_patch_state(workspace: str) -> Dict[str, Any]:
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
1038
|
+
def elysia_patch_state(workspace: str, root: str = ".") -> Dict[str, Any]:
|
|
1039
|
+
root_dir = _app_root(workspace, root)
|
|
1040
|
+
path = _find_node_entrypoint(root_dir)
|
|
1041
|
+
framework = _node_framework_of(root_dir)
|
|
1042
|
+
if not path or framework != "elysia":
|
|
1043
|
+
return {"entrypoint": None, "patched": False, "framework": framework}
|
|
725
1044
|
try:
|
|
726
1045
|
with open(path, "r", encoding="utf-8") as f:
|
|
727
1046
|
source = f.read()
|
|
@@ -734,11 +1053,12 @@ def elysia_patch_state(workspace: str) -> Dict[str, Any]:
|
|
|
734
1053
|
}
|
|
735
1054
|
|
|
736
1055
|
|
|
737
|
-
def apply_elysia_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
|
|
1056
|
+
def apply_elysia_patch(workspace: str, dry_run: bool = False, root: str = ".") -> Dict[str, Any]:
|
|
738
1057
|
"""Adds `app.use(oumv())` to an Elysia app, with a byte-exact backup."""
|
|
739
|
-
|
|
1058
|
+
root_dir = _app_root(workspace, root)
|
|
1059
|
+
if _node_framework_of(root_dir) != "elysia":
|
|
740
1060
|
return {"status": "skipped", "reason": "no Elysia dependency in package.json"}
|
|
741
|
-
path = _find_node_entrypoint(
|
|
1061
|
+
path = _find_node_entrypoint(root_dir)
|
|
742
1062
|
if not path:
|
|
743
1063
|
return {"status": "skipped", "reason": "no Bun entrypoint found"}
|
|
744
1064
|
|
|
@@ -762,21 +1082,43 @@ def apply_elysia_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
|
|
|
762
1082
|
)
|
|
763
1083
|
patched = source[:insert_at] + mount + source[insert_at:]
|
|
764
1084
|
|
|
1085
|
+
argv, manager = _node_install_command(_node_package_dir(root_dir, path))
|
|
1086
|
+
planned_install = {"status": "planned", "manager": manager, "command": " ".join(argv)}
|
|
765
1087
|
if dry_run:
|
|
766
1088
|
return {
|
|
767
1089
|
"status": "dry_run",
|
|
768
1090
|
"entrypoint": os.path.relpath(path, workspace),
|
|
769
1091
|
"framework": "elysia",
|
|
770
1092
|
"preview": f"{var}.use(_oumv());",
|
|
1093
|
+
"install": planned_install,
|
|
771
1094
|
}
|
|
772
1095
|
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
1096
|
+
install = _install_node_package(root_dir, path)
|
|
1097
|
+
if install["status"] in ("failed", "unavailable"):
|
|
1098
|
+
return {
|
|
1099
|
+
"status": "skipped",
|
|
1100
|
+
"entrypoint": os.path.relpath(path, workspace),
|
|
1101
|
+
"framework": "elysia",
|
|
1102
|
+
"install": install,
|
|
1103
|
+
"reason": (
|
|
1104
|
+
f"could not install {_NODE_PACKAGE} ({install.get('reason')}); "
|
|
1105
|
+
f"run `{install['command']}` and retry"
|
|
1106
|
+
),
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1109
|
+
backup_path = _backup_path(workspace, path)
|
|
1110
|
+
os.makedirs(os.path.dirname(backup_path), exist_ok=True)
|
|
776
1111
|
shutil.copy2(path, backup_path)
|
|
777
1112
|
with open(path, "w", encoding="utf-8") as f:
|
|
778
1113
|
f.write(patched)
|
|
779
|
-
_write_manifest(workspace, "elysia", {
|
|
1114
|
+
_write_manifest(workspace, "elysia", {
|
|
1115
|
+
"kind": "elysia",
|
|
1116
|
+
"app": root,
|
|
1117
|
+
"entrypoint": path,
|
|
1118
|
+
"backup": backup_path,
|
|
1119
|
+
"framework": "elysia",
|
|
1120
|
+
"install": install,
|
|
1121
|
+
})
|
|
780
1122
|
return {
|
|
781
1123
|
"status": "patched",
|
|
782
1124
|
"entrypoint": os.path.relpath(path, workspace),
|
|
@@ -784,11 +1126,15 @@ def apply_elysia_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
|
|
|
784
1126
|
"mode": "elysia_plugin",
|
|
785
1127
|
"backup": backup_path,
|
|
786
1128
|
"line": f"{var}.use(_oumv());",
|
|
1129
|
+
"install": install,
|
|
787
1130
|
}
|
|
788
1131
|
|
|
789
1132
|
|
|
790
|
-
def revert_elysia_patch(
|
|
791
|
-
|
|
1133
|
+
def revert_elysia_patch(
|
|
1134
|
+
workspace: str, root: str = ".", manifest: Optional[Dict[str, Any]] = None
|
|
1135
|
+
) -> Dict[str, Any]:
|
|
1136
|
+
if manifest is None:
|
|
1137
|
+
manifest = _read_manifest(workspace, "elysia", ("elysia_plugin",), app=root)
|
|
792
1138
|
if manifest is None:
|
|
793
1139
|
return {"status": "clean", "reason": "no Elysia patch manifest"}
|
|
794
1140
|
entrypoint = manifest.get("entrypoint")
|
|
@@ -956,12 +1302,13 @@ def next_bridge_mode(workspace: str) -> str:
|
|
|
956
1302
|
return "instrumentation" if version >= _NEXT_INSTRUMENTATION_MIN else "manual"
|
|
957
1303
|
|
|
958
1304
|
|
|
959
|
-
def next_patch_state(workspace: str) -> Dict[str, Any]:
|
|
960
|
-
|
|
1305
|
+
def next_patch_state(workspace: str, root: str = ".") -> Dict[str, Any]:
|
|
1306
|
+
root_dir = _app_root(workspace, root)
|
|
1307
|
+
files = _next_files(root_dir)
|
|
961
1308
|
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(
|
|
1309
|
+
loader = _next_existing_instrumentation(root_dir)
|
|
1310
|
+
installed = _next_instrumentation_installed(root_dir)
|
|
1311
|
+
mode = next_bridge_mode(root_dir)
|
|
965
1312
|
return {
|
|
966
1313
|
"entrypoint": existing[0] if existing else None,
|
|
967
1314
|
"patched": len(existing) == len(files) and (mode != "instrumentation" or installed),
|
|
@@ -981,19 +1328,39 @@ def _next_route_has_bridge(path: str) -> bool:
|
|
|
981
1328
|
return False
|
|
982
1329
|
|
|
983
1330
|
|
|
984
|
-
def
|
|
985
|
-
|
|
986
|
-
mode
|
|
1331
|
+
def _next_manual_note(workspace: str, root_dir: str, files: List[Tuple[str, str]], mode: str) -> Optional[Dict[str, str]]:
|
|
1332
|
+
snippet = "import { installNextBridge } from 'tokensafe-backend-node/next-bridge';\ninstallNextBridge();"
|
|
1333
|
+
if mode == "manual":
|
|
1334
|
+
return {
|
|
1335
|
+
"reason": "instrumentation-client requires Next >= 15.3; load the bridge by hand in this app",
|
|
1336
|
+
"snippet": snippet,
|
|
1337
|
+
}
|
|
1338
|
+
loader = _next_existing_instrumentation(root_dir)
|
|
1339
|
+
own_paths = {path for path, _ in files}
|
|
1340
|
+
if loader and loader not in own_paths and not _next_instrumentation_installed(root_dir):
|
|
1341
|
+
return {
|
|
1342
|
+
"reason": f"{os.path.relpath(loader, workspace)} already exists — add the installer call to it instead of letting the engine shadow it",
|
|
1343
|
+
"snippet": snippet,
|
|
1344
|
+
}
|
|
1345
|
+
return None
|
|
1346
|
+
|
|
1347
|
+
|
|
1348
|
+
def apply_next_patch(workspace: str, dry_run: bool = False, root: str = ".") -> Dict[str, Any]:
|
|
1349
|
+
root_dir = _app_root(workspace, root)
|
|
1350
|
+
files = _next_files(root_dir)
|
|
1351
|
+
mode = next_bridge_mode(root_dir)
|
|
987
1352
|
entrypoint = os.path.relpath(files[0][0], workspace)
|
|
988
1353
|
actions: List[Dict[str, str]] = []
|
|
989
|
-
|
|
1354
|
+
created: List[str] = []
|
|
1355
|
+
restore: Dict[str, str] = {}
|
|
990
1356
|
|
|
991
1357
|
for path, source in files:
|
|
992
1358
|
rel = os.path.relpath(path, workspace)
|
|
993
1359
|
if os.path.isfile(path):
|
|
994
1360
|
if path == files[0][0] and not _next_route_has_bridge(path):
|
|
995
1361
|
try:
|
|
996
|
-
|
|
1362
|
+
with open(path, "r", encoding="utf-8") as handle:
|
|
1363
|
+
current = handle.read()
|
|
997
1364
|
except Exception:
|
|
998
1365
|
current = ""
|
|
999
1366
|
if current != _NEXT_LEGACY_ROUTE_SOURCE:
|
|
@@ -1003,12 +1370,12 @@ def apply_next_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
|
|
|
1003
1370
|
"entrypoint": rel,
|
|
1004
1371
|
}
|
|
1005
1372
|
actions.append({"path": rel, "action": "upgrade"})
|
|
1006
|
-
|
|
1373
|
+
restore[path] = _backup_path(workspace, path)
|
|
1007
1374
|
else:
|
|
1008
1375
|
actions.append({"path": rel, "action": "keep"})
|
|
1009
1376
|
continue
|
|
1010
1377
|
actions.append({"path": rel, "action": "create"})
|
|
1011
|
-
|
|
1378
|
+
created.append(path)
|
|
1012
1379
|
|
|
1013
1380
|
if dry_run:
|
|
1014
1381
|
return {
|
|
@@ -1016,65 +1383,65 @@ def apply_next_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
|
|
|
1016
1383
|
"entrypoint": entrypoint,
|
|
1017
1384
|
"bridge": mode,
|
|
1018
1385
|
"files": actions,
|
|
1019
|
-
"would_create": [os.path.relpath(path, workspace) for path in
|
|
1386
|
+
"would_create": [os.path.relpath(path, workspace) for path in created],
|
|
1387
|
+
"would_upgrade": [os.path.relpath(path, workspace) for path in restore],
|
|
1020
1388
|
}
|
|
1021
1389
|
|
|
1022
|
-
|
|
1390
|
+
# Nothing was written: a manifest here would let revert delete user files.
|
|
1391
|
+
if not created and not restore:
|
|
1392
|
+
result: Dict[str, Any] = {
|
|
1393
|
+
"status": "already_patched",
|
|
1394
|
+
"entrypoint": entrypoint,
|
|
1395
|
+
"bridge": mode,
|
|
1396
|
+
"files": actions,
|
|
1397
|
+
"created": [],
|
|
1398
|
+
}
|
|
1399
|
+
note = _next_manual_note(workspace, root_dir, files, mode)
|
|
1400
|
+
if note:
|
|
1401
|
+
result["bridge_manual"] = note
|
|
1402
|
+
return result
|
|
1403
|
+
|
|
1404
|
+
# An upgraded v1 route is the user's file; keep its bytes for revert.
|
|
1405
|
+
for path, backup in restore.items():
|
|
1406
|
+
os.makedirs(os.path.dirname(backup), exist_ok=True)
|
|
1407
|
+
shutil.copy2(path, backup)
|
|
1408
|
+
|
|
1023
1409
|
for path, source in files:
|
|
1024
|
-
if
|
|
1410
|
+
if path not in created and path not in restore:
|
|
1025
1411
|
continue
|
|
1026
1412
|
parent = os.path.dirname(path)
|
|
1027
1413
|
if parent:
|
|
1028
1414
|
os.makedirs(parent, exist_ok=True)
|
|
1029
1415
|
with open(path, "w", encoding="utf-8") as handle:
|
|
1030
1416
|
handle.write(source)
|
|
1031
|
-
if path not in created:
|
|
1032
|
-
created.append(path)
|
|
1033
1417
|
|
|
1034
1418
|
_write_manifest(workspace, "next", {
|
|
1419
|
+
"kind": "next",
|
|
1420
|
+
"app": root,
|
|
1421
|
+
"ownership": 2,
|
|
1035
1422
|
"entrypoint": files[0][0],
|
|
1036
1423
|
"framework": "nextjs",
|
|
1037
1424
|
"mode": "next_route_v2",
|
|
1038
1425
|
"bridge": mode,
|
|
1039
1426
|
"files": [path for path, _ in files],
|
|
1040
|
-
"owned": owned or [path for path, _ in files],
|
|
1041
1427
|
"created": created,
|
|
1428
|
+
"restore": restore,
|
|
1042
1429
|
})
|
|
1043
|
-
result
|
|
1044
|
-
"status": "patched"
|
|
1430
|
+
result = {
|
|
1431
|
+
"status": "patched",
|
|
1045
1432
|
"entrypoint": entrypoint,
|
|
1046
1433
|
"bridge": mode,
|
|
1047
1434
|
"files": actions,
|
|
1048
1435
|
"created": [os.path.relpath(path, workspace) for path in created],
|
|
1436
|
+
"upgraded": [os.path.relpath(path, workspace) for path in restore],
|
|
1049
1437
|
}
|
|
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
|
-
}
|
|
1438
|
+
note = _next_manual_note(workspace, root_dir, files, mode)
|
|
1439
|
+
if note:
|
|
1440
|
+
result["bridge_manual"] = note
|
|
1063
1441
|
return result
|
|
1064
1442
|
|
|
1065
1443
|
|
|
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)
|
|
1444
|
+
def _remove_empty_dirs(workspace: str, removed: List[str]) -> None:
|
|
1078
1445
|
# Remove only directories this adapter emptied, never a non-empty parent.
|
|
1079
1446
|
for directory in sorted({os.path.dirname(path) for path in removed}, key=len, reverse=True):
|
|
1080
1447
|
while os.path.abspath(directory) != os.path.abspath(workspace) and os.path.isdir(directory):
|
|
@@ -1083,11 +1450,77 @@ def revert_next_patch(workspace: str) -> Dict[str, Any]:
|
|
|
1083
1450
|
except OSError:
|
|
1084
1451
|
break
|
|
1085
1452
|
directory = os.path.dirname(directory)
|
|
1453
|
+
|
|
1454
|
+
|
|
1455
|
+
def _revert_legacy_next_patch(workspace: str, manifest: Dict[str, Any]) -> Dict[str, Any]:
|
|
1456
|
+
"""Manifests before `ownership: 2` cannot tell created files from pre-existing
|
|
1457
|
+
ones. Delete only bytes this adapter wrote; keep everything else."""
|
|
1458
|
+
candidates = manifest.get("owned") or manifest.get("created") or []
|
|
1459
|
+
if not candidates and manifest.get("entrypoint"):
|
|
1460
|
+
candidates = [manifest["entrypoint"]]
|
|
1461
|
+
removed: List[str] = []
|
|
1462
|
+
kept: List[Dict[str, str]] = []
|
|
1463
|
+
for path in candidates:
|
|
1464
|
+
if not path or not os.path.isfile(path):
|
|
1465
|
+
continue
|
|
1466
|
+
try:
|
|
1467
|
+
with open(path, "r", encoding="utf-8") as handle:
|
|
1468
|
+
content = handle.read()
|
|
1469
|
+
except OSError:
|
|
1470
|
+
kept.append({"path": os.path.relpath(path, workspace), "reason": "unreadable; left in place"})
|
|
1471
|
+
continue
|
|
1472
|
+
if content in (_NEXT_RPC_SOURCE, _NEXT_BRIDGE_SOURCE, _NEXT_INSTRUMENTATION_SOURCE):
|
|
1473
|
+
os.remove(path)
|
|
1474
|
+
removed.append(path)
|
|
1475
|
+
elif content == _NEXT_LEGACY_ROUTE_SOURCE:
|
|
1476
|
+
kept.append({"path": os.path.relpath(path, workspace), "reason": "pre-existing legacy route; left in place"})
|
|
1477
|
+
else:
|
|
1478
|
+
kept.append({"path": os.path.relpath(path, workspace), "reason": "content was not generated by this adapter"})
|
|
1479
|
+
_remove_empty_dirs(workspace, removed)
|
|
1086
1480
|
_delete_manifest(manifest)
|
|
1087
1481
|
return {
|
|
1088
|
-
"status": "reverted",
|
|
1482
|
+
"status": "reverted" if removed else "kept",
|
|
1483
|
+
"entrypoint": manifest.get("entrypoint"),
|
|
1484
|
+
"removed": [os.path.relpath(path, workspace) for path in removed],
|
|
1485
|
+
"kept": kept,
|
|
1486
|
+
}
|
|
1487
|
+
|
|
1488
|
+
|
|
1489
|
+
def revert_next_patch(
|
|
1490
|
+
workspace: str, root: str = ".", manifest: Optional[Dict[str, Any]] = None
|
|
1491
|
+
) -> Dict[str, Any]:
|
|
1492
|
+
if manifest is None:
|
|
1493
|
+
manifest = _read_manifest(workspace, "next", ("next_route", "next_route_v2"), app=root)
|
|
1494
|
+
if not manifest:
|
|
1495
|
+
return {"status": "nothing-to-revert"}
|
|
1496
|
+
if manifest.get("ownership") != 2:
|
|
1497
|
+
return _revert_legacy_next_patch(workspace, manifest)
|
|
1498
|
+
created = manifest.get("created") or []
|
|
1499
|
+
restore = manifest.get("restore") or {}
|
|
1500
|
+
removed: List[str] = []
|
|
1501
|
+
restored: List[str] = []
|
|
1502
|
+
kept: List[Dict[str, str]] = []
|
|
1503
|
+
for path in created:
|
|
1504
|
+
if path and os.path.isfile(path):
|
|
1505
|
+
os.remove(path)
|
|
1506
|
+
removed.append(path)
|
|
1507
|
+
for path, backup in restore.items():
|
|
1508
|
+
if path and backup and os.path.isfile(backup):
|
|
1509
|
+
parent = os.path.dirname(path)
|
|
1510
|
+
if parent:
|
|
1511
|
+
os.makedirs(parent, exist_ok=True)
|
|
1512
|
+
shutil.copy2(backup, path)
|
|
1513
|
+
restored.append(path)
|
|
1514
|
+
else:
|
|
1515
|
+
kept.append({"path": os.path.relpath(path, workspace) if path else "?", "reason": "backup missing; left in place"})
|
|
1516
|
+
_remove_empty_dirs(workspace, removed)
|
|
1517
|
+
_delete_manifest(manifest)
|
|
1518
|
+
return {
|
|
1519
|
+
"status": "reverted" if (removed or restored) else "clean",
|
|
1089
1520
|
"entrypoint": manifest.get("entrypoint"),
|
|
1090
1521
|
"removed": [os.path.relpath(path, workspace) for path in removed],
|
|
1522
|
+
"restored": [os.path.relpath(path, workspace) for path in restored],
|
|
1523
|
+
"kept": kept,
|
|
1091
1524
|
}
|
|
1092
1525
|
|
|
1093
1526
|
|
|
@@ -1155,7 +1588,7 @@ def _sidecar_cache_dir() -> str:
|
|
|
1155
1588
|
_DOTNET_MARK_BEGIN = "// tokensafe:oumv:begin"
|
|
1156
1589
|
_DOTNET_MARK_END = "// tokensafe:oumv:end"
|
|
1157
1590
|
_DOTNET_PACKAGE = "TokenSafe.Oumv.AspNetCore"
|
|
1158
|
-
_DOTNET_PACKAGE_VERSION =
|
|
1591
|
+
_DOTNET_PACKAGE_VERSION = BACKEND_DOTNET_VERSION
|
|
1159
1592
|
|
|
1160
1593
|
|
|
1161
1594
|
|
|
@@ -1204,10 +1637,11 @@ def _find_dotnet_entrypoint(workspace: str, project: Optional[str] = None) -> Op
|
|
|
1204
1637
|
return candidate if os.path.isfile(candidate) else None
|
|
1205
1638
|
|
|
1206
1639
|
|
|
1207
|
-
def dotnet_patch_state(workspace: str) -> Dict[str, Any]:
|
|
1640
|
+
def dotnet_patch_state(workspace: str, root: str = ".") -> Dict[str, Any]:
|
|
1208
1641
|
"""Reports whether the OUMV mount is already present in Program.cs."""
|
|
1209
|
-
|
|
1210
|
-
|
|
1642
|
+
root_dir = _app_root(workspace, root)
|
|
1643
|
+
project = _dotnet_web_project(root_dir)
|
|
1644
|
+
entrypoint = _find_dotnet_entrypoint(root_dir, project)
|
|
1211
1645
|
if not entrypoint:
|
|
1212
1646
|
return {"entrypoint": None, "patched": False, "project": project}
|
|
1213
1647
|
try:
|
|
@@ -1237,15 +1671,15 @@ def _dotnet_build(project: str) -> Tuple[bool, str]:
|
|
|
1237
1671
|
return False, "dotnet build timed out"
|
|
1238
1672
|
|
|
1239
1673
|
|
|
1240
|
-
def _ensure_dotnet_dependency(project: str) -> Optional[str]:
|
|
1241
|
-
"""Adds the NuGet package once; returns
|
|
1674
|
+
def _ensure_dotnet_dependency(project: str) -> Tuple[Optional[str], bool]:
|
|
1675
|
+
"""Adds the NuGet package once; returns (note, mutated)."""
|
|
1242
1676
|
try:
|
|
1243
1677
|
with open(project, "r", encoding="utf-8") as handle:
|
|
1244
1678
|
content = handle.read()
|
|
1245
1679
|
except OSError:
|
|
1246
|
-
return f"could not read {project}"
|
|
1680
|
+
return f"could not read {project}", False
|
|
1247
1681
|
if _DOTNET_PACKAGE in content:
|
|
1248
|
-
return None
|
|
1682
|
+
return None, False
|
|
1249
1683
|
try:
|
|
1250
1684
|
result = subprocess.run(
|
|
1251
1685
|
[_dotnet_cli(), "add", project, "package", _DOTNET_PACKAGE, "--version", _DOTNET_PACKAGE_VERSION],
|
|
@@ -1254,20 +1688,29 @@ def _ensure_dotnet_dependency(project: str) -> Optional[str]:
|
|
|
1254
1688
|
timeout=300,
|
|
1255
1689
|
)
|
|
1256
1690
|
except FileNotFoundError:
|
|
1257
|
-
return
|
|
1691
|
+
return (
|
|
1692
|
+
f"dotnet SDK not found; add <PackageReference Include=\"{_DOTNET_PACKAGE}\" "
|
|
1693
|
+
f"Version=\"{_DOTNET_PACKAGE_VERSION}\" /> manually",
|
|
1694
|
+
False,
|
|
1695
|
+
)
|
|
1258
1696
|
except subprocess.TimeoutExpired:
|
|
1259
|
-
return "dotnet add package timed out"
|
|
1697
|
+
return "dotnet add package timed out", False
|
|
1260
1698
|
if result.returncode != 0:
|
|
1261
|
-
return
|
|
1262
|
-
|
|
1699
|
+
return (
|
|
1700
|
+
f"dotnet add package failed; add the PackageReference manually: "
|
|
1701
|
+
f"{(result.stdout + result.stderr)[-300:]}",
|
|
1702
|
+
False,
|
|
1703
|
+
)
|
|
1704
|
+
return None, True
|
|
1263
1705
|
|
|
1264
1706
|
|
|
1265
|
-
def apply_dotnet_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
|
|
1707
|
+
def apply_dotnet_patch(workspace: str, dry_run: bool = False, root: str = ".") -> Dict[str, Any]:
|
|
1266
1708
|
"""Inserts `using`, `AddTokensafe()` and `UseTokensafe()` between tokensafe markers."""
|
|
1267
|
-
|
|
1709
|
+
root_dir = _app_root(workspace, root)
|
|
1710
|
+
project = _dotnet_web_project(root_dir)
|
|
1268
1711
|
if not project:
|
|
1269
1712
|
return {"status": "skipped", "reason": "no ASP.NET Core (Microsoft.NET.Sdk.Web) project found"}
|
|
1270
|
-
entrypoint = _find_dotnet_entrypoint(
|
|
1713
|
+
entrypoint = _find_dotnet_entrypoint(root_dir, project)
|
|
1271
1714
|
if not entrypoint:
|
|
1272
1715
|
return {"status": "skipped", "reason": "no Program.cs next to the web project"}
|
|
1273
1716
|
|
|
@@ -1329,18 +1772,36 @@ def apply_dotnet_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
|
|
|
1329
1772
|
"preview": f"{builder.group('builder')}.Services.AddTokensafe();\n{app.group('app')}.UseTokensafe();",
|
|
1330
1773
|
}
|
|
1331
1774
|
|
|
1332
|
-
|
|
1333
|
-
os.makedirs(
|
|
1334
|
-
backup_path = os.path.join(backup_dir, os.path.relpath(entrypoint, workspace).replace(os.sep, "__") + ".bak")
|
|
1775
|
+
backup_path = _backup_path(workspace, entrypoint)
|
|
1776
|
+
os.makedirs(os.path.dirname(backup_path), exist_ok=True)
|
|
1335
1777
|
shutil.copy2(entrypoint, backup_path)
|
|
1778
|
+
|
|
1779
|
+
# `dotnet add package` rewrites the csproj: back it up so revert can undo it.
|
|
1780
|
+
project_backup = project_before = project_after = None
|
|
1781
|
+
try:
|
|
1782
|
+
with open(project, "r", encoding="utf-8") as handle:
|
|
1783
|
+
project_before_content = handle.read()
|
|
1784
|
+
except OSError:
|
|
1785
|
+
project_before_content = ""
|
|
1786
|
+
if _DOTNET_PACKAGE not in project_before_content:
|
|
1787
|
+
project_backup = _backup_path(workspace, project)
|
|
1788
|
+
os.makedirs(os.path.dirname(project_backup), exist_ok=True)
|
|
1789
|
+
shutil.copy2(project, project_backup)
|
|
1790
|
+
project_before = _sha256_file(project)
|
|
1791
|
+
|
|
1336
1792
|
with open(entrypoint, "w", encoding="utf-8") as handle:
|
|
1337
1793
|
handle.write(patched)
|
|
1338
1794
|
|
|
1339
|
-
dependency_note = _ensure_dotnet_dependency(project)
|
|
1795
|
+
dependency_note, mutated = _ensure_dotnet_dependency(project)
|
|
1796
|
+
if mutated and project_backup:
|
|
1797
|
+
project_after = _sha256_file(project)
|
|
1340
1798
|
build_ok, build_output = _dotnet_build(project) if dependency_note is None else (False, "skipped")
|
|
1341
1799
|
if not build_ok:
|
|
1342
1800
|
shutil.copy2(backup_path, entrypoint)
|
|
1343
1801
|
os.unlink(backup_path)
|
|
1802
|
+
if project_backup and mutated and os.path.isfile(project_backup):
|
|
1803
|
+
shutil.copy2(project_backup, project)
|
|
1804
|
+
os.unlink(project_backup)
|
|
1344
1805
|
return {
|
|
1345
1806
|
"status": "reverted",
|
|
1346
1807
|
"entrypoint": os.path.relpath(entrypoint, workspace),
|
|
@@ -1348,8 +1809,17 @@ def apply_dotnet_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
|
|
|
1348
1809
|
"build": build_output[-800:],
|
|
1349
1810
|
}
|
|
1350
1811
|
|
|
1351
|
-
_write_manifest(workspace, "dotnet",
|
|
1352
|
-
|
|
1812
|
+
_write_manifest(workspace, "dotnet", {
|
|
1813
|
+
"kind": "dotnet",
|
|
1814
|
+
"app": root,
|
|
1815
|
+
"entrypoint": entrypoint,
|
|
1816
|
+
"backup": backup_path,
|
|
1817
|
+
"framework": "aspnetcore",
|
|
1818
|
+
"project": project,
|
|
1819
|
+
"project_backup": project_backup,
|
|
1820
|
+
"project_before_sha": project_before,
|
|
1821
|
+
"project_after_sha": project_after,
|
|
1822
|
+
})
|
|
1353
1823
|
return {
|
|
1354
1824
|
"status": "patched",
|
|
1355
1825
|
"entrypoint": os.path.relpath(entrypoint, workspace),
|
|
@@ -1361,8 +1831,11 @@ def apply_dotnet_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
|
|
|
1361
1831
|
}
|
|
1362
1832
|
|
|
1363
1833
|
|
|
1364
|
-
def revert_dotnet_patch(
|
|
1365
|
-
|
|
1834
|
+
def revert_dotnet_patch(
|
|
1835
|
+
workspace: str, root: str = ".", manifest: Optional[Dict[str, Any]] = None
|
|
1836
|
+
) -> Dict[str, Any]:
|
|
1837
|
+
if manifest is None:
|
|
1838
|
+
manifest = _read_manifest(workspace, "dotnet", ("dotnet_mount",), app=root)
|
|
1366
1839
|
if manifest is None:
|
|
1367
1840
|
return {"status": "clean", "reason": "no .NET patch manifest"}
|
|
1368
1841
|
entrypoint = manifest.get("entrypoint")
|
|
@@ -1370,8 +1843,37 @@ def revert_dotnet_patch(workspace: str) -> Dict[str, Any]:
|
|
|
1370
1843
|
if not (entrypoint and backup and os.path.isfile(backup)):
|
|
1371
1844
|
return {"status": "error", "reason": "backup missing; restore manually"}
|
|
1372
1845
|
shutil.copy2(backup, entrypoint)
|
|
1846
|
+
project = manifest.get("project") or _dotnet_web_project(workspace)
|
|
1847
|
+
project_backup = manifest.get("project_backup")
|
|
1848
|
+
project_after = manifest.get("project_after_sha")
|
|
1849
|
+
project_status = "unchanged"
|
|
1850
|
+
if project and project_backup and os.path.isfile(project_backup):
|
|
1851
|
+
if project_after and os.path.isfile(project) and _sha256_file(project) != project_after:
|
|
1852
|
+
project_status = "project_modified"
|
|
1853
|
+
else:
|
|
1854
|
+
shutil.copy2(project_backup, project)
|
|
1855
|
+
project_status = "restored"
|
|
1856
|
+
elif project and os.path.isfile(project):
|
|
1857
|
+
# Legacy manifest: no csproj backup, remove only the exact PackageReference.
|
|
1858
|
+
pattern = re.compile(
|
|
1859
|
+
r'[ \t]*<PackageReference\s+Include="' + re.escape(_DOTNET_PACKAGE) + r'"[^>]*/>[ \t]*\r?\n?'
|
|
1860
|
+
)
|
|
1861
|
+
try:
|
|
1862
|
+
with open(project, "r", encoding="utf-8") as handle:
|
|
1863
|
+
content = handle.read()
|
|
1864
|
+
except OSError:
|
|
1865
|
+
content = ""
|
|
1866
|
+
stripped, count = pattern.subn("", content)
|
|
1867
|
+
if count:
|
|
1868
|
+
with open(project, "w", encoding="utf-8") as handle:
|
|
1869
|
+
handle.write(stripped)
|
|
1870
|
+
project_status = "package_reference_removed"
|
|
1373
1871
|
_delete_manifest(manifest)
|
|
1374
|
-
return {
|
|
1872
|
+
return {
|
|
1873
|
+
"status": "reverted",
|
|
1874
|
+
"entrypoint": os.path.relpath(entrypoint, workspace),
|
|
1875
|
+
"project": project_status,
|
|
1876
|
+
}
|
|
1375
1877
|
|
|
1376
1878
|
|
|
1377
1879
|
# Pinned to the backend release: the sidecars are single files, so the cache is
|
|
@@ -1427,13 +1929,28 @@ def sidecar_run_command(kind: str, sidecar_path: str, workspace: str) -> Optiona
|
|
|
1427
1929
|
return None
|
|
1428
1930
|
|
|
1429
1931
|
|
|
1932
|
+
def sidecar_cached(kind: str) -> Tuple[Optional[str], str]:
|
|
1933
|
+
"""Cache-only lookup: `inject --status` must never touch the network."""
|
|
1934
|
+
if kind not in _SIDECARS:
|
|
1935
|
+
return None, f"unknown sidecar {kind!r}"
|
|
1936
|
+
_, filename, expected_sha = _SIDECARS[kind]
|
|
1937
|
+
target = os.path.join(_sidecar_cache_dir(), filename)
|
|
1938
|
+
if os.path.isfile(target) and _sha256_file(target) == expected_sha:
|
|
1939
|
+
return target, f"cached at {_SIDECAR_RELEASE_TAG}"
|
|
1940
|
+
return None, (
|
|
1941
|
+
f"not cached — run `tokensafe inject` to download {_SIDECAR_RELEASE_TAG} "
|
|
1942
|
+
"(or set OUMV_BACKEND_REPO for an unpinned local checkout)"
|
|
1943
|
+
)
|
|
1944
|
+
|
|
1945
|
+
|
|
1430
1946
|
def ensure_sidecar(kind: str) -> Tuple[Optional[str], str]:
|
|
1431
1947
|
"""Caches OumvSpring.java / oumv-php at the pinned release and verifies SHA-256.
|
|
1432
1948
|
|
|
1433
1949
|
Order: a valid cache → a local checkout whose bytes match the pin (developer
|
|
1434
1950
|
flow, no network) → download from the release tag. A hash mismatch is never
|
|
1435
1951
|
accepted silently; the note says what failed instead of handing back a
|
|
1436
|
-
different file under the certified name.
|
|
1952
|
+
different file under the certified name. An explicit `OUMV_BACKEND_REPO` is
|
|
1953
|
+
the only way to use unpinned local bytes, and the note says so.
|
|
1437
1954
|
"""
|
|
1438
1955
|
if kind not in _SIDECARS:
|
|
1439
1956
|
return None, f"unknown sidecar {kind!r}"
|
|
@@ -1453,6 +1970,7 @@ def ensure_sidecar(kind: str) -> Tuple[Optional[str], str]:
|
|
|
1453
1970
|
|
|
1454
1971
|
repo_candidates = []
|
|
1455
1972
|
env_repo = os.environ.get("OUMV_BACKEND_REPO")
|
|
1973
|
+
explicit_repo = bool(env_repo)
|
|
1456
1974
|
if env_repo:
|
|
1457
1975
|
repo_candidates.append(env_repo)
|
|
1458
1976
|
here = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
@@ -1469,10 +1987,18 @@ def ensure_sidecar(kind: str) -> Tuple[Optional[str], str]:
|
|
|
1469
1987
|
return adopt(candidate, f"cached from local checkout matching {_SIDECAR_RELEASE_TAG}")
|
|
1470
1988
|
local_mismatch = candidate
|
|
1471
1989
|
|
|
1990
|
+
def explicit_unpinned(note: str) -> Tuple[Optional[str], str]:
|
|
1991
|
+
if explicit_repo and local_mismatch:
|
|
1992
|
+
return adopt(local_mismatch, f"unpinned (OUMV_BACKEND_REPO): {local_mismatch}")
|
|
1993
|
+
return None, note
|
|
1994
|
+
|
|
1472
1995
|
if os.environ.get("TOKENSAFE_SIDECAR_OFFLINE") == "1":
|
|
1473
1996
|
if local_mismatch:
|
|
1474
|
-
return
|
|
1475
|
-
|
|
1997
|
+
return explicit_unpinned(
|
|
1998
|
+
f"offline and no local sidecar matches {_SIDECAR_RELEASE_TAG}; "
|
|
1999
|
+
f"candidate {local_mismatch} is unpinned (set OUMV_BACKEND_REPO to use it)"
|
|
2000
|
+
)
|
|
2001
|
+
return None, f"offline (TOKENSAFE_SIDECAR_OFFLINE=1) and no cached sidecar matching {_SIDECAR_RELEASE_TAG}"
|
|
1476
2002
|
|
|
1477
2003
|
url = (
|
|
1478
2004
|
f"https://raw.githubusercontent.com/tokensafe-dev/tokensafe-backend/"
|
|
@@ -1485,7 +2011,10 @@ def ensure_sidecar(kind: str) -> Tuple[Optional[str], str]:
|
|
|
1485
2011
|
payload = response.read()
|
|
1486
2012
|
except Exception as exc:
|
|
1487
2013
|
if local_mismatch:
|
|
1488
|
-
return
|
|
2014
|
+
return explicit_unpinned(
|
|
2015
|
+
f"download failed ({exc}); local candidate {local_mismatch} is unpinned "
|
|
2016
|
+
f"(set OUMV_BACKEND_REPO to use it)"
|
|
2017
|
+
)
|
|
1489
2018
|
return None, f"cannot download {url}: {exc}"
|
|
1490
2019
|
|
|
1491
2020
|
actual = hashlib.sha256(payload).hexdigest()
|
|
@@ -1499,76 +2028,160 @@ def ensure_sidecar(kind: str) -> Tuple[Optional[str], str]:
|
|
|
1499
2028
|
return target, f"downloaded from {_SIDECAR_RELEASE_TAG}"
|
|
1500
2029
|
|
|
1501
2030
|
|
|
2031
|
+
def _injectable_apps(stack: Dict[str, Any]) -> List[Dict[str, Any]]:
|
|
2032
|
+
"""Every detected app that can be planned/injected, root first.
|
|
2033
|
+
|
|
2034
|
+
`packages` already holds one row per manifest (role, path, framework), so a
|
|
2035
|
+
monorepo must not collapse to stack["frontend"]/stack["backend"].
|
|
2036
|
+
"""
|
|
2037
|
+
apps: List[Dict[str, Any]] = []
|
|
2038
|
+
seen = set()
|
|
2039
|
+
|
|
2040
|
+
def add(role, app, framework, provider, supported, status, reason=None, info=None):
|
|
2041
|
+
key = (role, app or ".", framework)
|
|
2042
|
+
if key in seen:
|
|
2043
|
+
return
|
|
2044
|
+
seen.add(key)
|
|
2045
|
+
apps.append({
|
|
2046
|
+
"role": role,
|
|
2047
|
+
"app": app or ".",
|
|
2048
|
+
"framework": framework,
|
|
2049
|
+
"provider": provider,
|
|
2050
|
+
"supported": bool(supported),
|
|
2051
|
+
"status": status or "ready",
|
|
2052
|
+
"reason": reason,
|
|
2053
|
+
"info": info or {},
|
|
2054
|
+
})
|
|
2055
|
+
|
|
2056
|
+
for pkg in stack.get("packages") or []:
|
|
2057
|
+
role = pkg.get("role")
|
|
2058
|
+
if role not in ("frontend", "backend"):
|
|
2059
|
+
continue
|
|
2060
|
+
add(role, pkg.get("path") or ".", pkg.get("framework"), pkg.get("provider"),
|
|
2061
|
+
pkg.get("oumvSupported"), pkg.get("status"), pkg.get("reason"), pkg)
|
|
2062
|
+
|
|
2063
|
+
# Defensive: a detector row missing from `packages` still gets an action.
|
|
2064
|
+
for role in ("frontend", "backend"):
|
|
2065
|
+
info = stack.get(role) or {}
|
|
2066
|
+
if not info:
|
|
2067
|
+
continue
|
|
2068
|
+
add(role, info.get("root") or ".", info.get("framework"), info.get("provider"),
|
|
2069
|
+
info.get("oumv_supported", True), info.get("status"), info.get("note"), info)
|
|
2070
|
+
return apps
|
|
2071
|
+
|
|
2072
|
+
|
|
2073
|
+
def _frontend_run(app: str, framework: Optional[str]) -> str:
|
|
2074
|
+
run = "tokensafe dev" if app in (".", "") else f"tokensafe dev {app}"
|
|
2075
|
+
if framework and framework != "react":
|
|
2076
|
+
run += f" --framework {framework}"
|
|
2077
|
+
return run
|
|
2078
|
+
|
|
2079
|
+
|
|
2080
|
+
def _backend_install(catalog: Dict[str, Any], provider: str) -> Optional[str]:
|
|
2081
|
+
entry_id = {
|
|
2082
|
+
"fastapi": "backend/fastapi",
|
|
2083
|
+
"python": "backend/starlette",
|
|
2084
|
+
"go": "backend/go",
|
|
2085
|
+
"node": "backend/node",
|
|
2086
|
+
"elysia": "backend/elysia",
|
|
2087
|
+
"spring": "backend/spring",
|
|
2088
|
+
"php": "backend/php",
|
|
2089
|
+
"dotnet": "backend/aspnetcore",
|
|
2090
|
+
}.get(provider, "backend/go")
|
|
2091
|
+
return catalog.get(entry_id, {}).get("technology", {}).get("package", {}).get("install")
|
|
2092
|
+
|
|
2093
|
+
|
|
1502
2094
|
def plan(workspace: str) -> Dict[str, Any]:
|
|
1503
|
-
"""Describes what apply would do, without touching anything."""
|
|
2095
|
+
"""Describes what apply would do, without touching anything (or the network)."""
|
|
1504
2096
|
stack = detect_project_stack(workspace)
|
|
1505
2097
|
catalog = {entry["id"]: entry for entry in get_adapters_catalog()}
|
|
2098
|
+
apps = _injectable_apps(stack)
|
|
1506
2099
|
actions: List[Dict[str, Any]] = []
|
|
1507
2100
|
|
|
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
|
-
|
|
2101
|
+
for app in apps:
|
|
2102
|
+
root = app["app"]
|
|
2103
|
+
role = app["role"]
|
|
2104
|
+
framework = app["framework"] or ""
|
|
2105
|
+
provider = app["provider"] or ""
|
|
2106
|
+
info = app["info"]
|
|
2107
|
+
if role == "frontend":
|
|
2108
|
+
if framework == "nextjs":
|
|
2109
|
+
root_dir = _app_root(workspace, root)
|
|
2110
|
+
next_state = next_patch_state(workspace, root)
|
|
2111
|
+
action = {
|
|
2112
|
+
"kind": "next_route_handler",
|
|
2113
|
+
"profile": "backend",
|
|
2114
|
+
"app": root,
|
|
2115
|
+
"framework": "nextjs",
|
|
2116
|
+
"writes_repo": True,
|
|
2117
|
+
"already_patched": next_state["patched"],
|
|
2118
|
+
"entrypoint": next_state["entrypoint"]
|
|
2119
|
+
or os.path.relpath(next_route_path(root_dir), workspace),
|
|
2120
|
+
"files": next_state["files"],
|
|
2121
|
+
"missing": next_state["missing"],
|
|
2122
|
+
"bridge": next_state["bridge"],
|
|
2123
|
+
"description": (
|
|
2124
|
+
"three App Router files: api/tokensafe/route.ts (createNextRouteHandlers with bridge: true), "
|
|
2125
|
+
"api/tokensafe/bridge/route.ts (the browser bridge) and instrumentation-client.ts "
|
|
2126
|
+
"(installNextBridge). Server profile plus client components; delete them or --revert to unmount"
|
|
2127
|
+
),
|
|
2128
|
+
"install": "npm install --save-dev tokensafe-backend-node",
|
|
2129
|
+
"run": "next dev",
|
|
2130
|
+
}
|
|
2131
|
+
if next_state["bridge"] == "manual":
|
|
2132
|
+
action["bridge_manual"] = {
|
|
2133
|
+
"reason": "instrumentation-client requires Next >= 15.3; the route files are written, the client loader is not",
|
|
2134
|
+
"snippet": "import { installNextBridge } from 'tokensafe-backend-node/next-bridge';\ninstallNextBridge();",
|
|
2135
|
+
}
|
|
2136
|
+
actions.append(action)
|
|
2137
|
+
continue
|
|
2138
|
+
if not app["supported"]:
|
|
2139
|
+
reason = app["reason"] or f"no OUMV adapter for {framework} yet"
|
|
2140
|
+
actions.append({
|
|
2141
|
+
"kind": "frontend_unsupported",
|
|
2142
|
+
"profile": "frontend",
|
|
2143
|
+
"app": root,
|
|
2144
|
+
"framework": framework,
|
|
2145
|
+
"status": "planned",
|
|
2146
|
+
"writes_repo": False,
|
|
2147
|
+
"reason": reason,
|
|
2148
|
+
"description": reason,
|
|
2149
|
+
})
|
|
2150
|
+
continue
|
|
2151
|
+
frontend_entry = catalog.get(f"frontend/{provider}") or {}
|
|
2152
|
+
actions.append({
|
|
2153
|
+
"kind": "frontend_zero_footprint",
|
|
2154
|
+
"profile": "frontend",
|
|
2155
|
+
"app": root,
|
|
2156
|
+
"framework": f"{provider}/{framework}",
|
|
2157
|
+
"writes_repo": False,
|
|
2158
|
+
"description": "served by `tokensafe dev` (inline Vite config, descriptor in ~/.tokensafe/runtimes)",
|
|
2159
|
+
"run": _frontend_run(root, framework),
|
|
2160
|
+
"install": frontend_entry.get("technology", {}).get("package", {}).get("install"),
|
|
2161
|
+
})
|
|
2162
|
+
continue
|
|
2163
|
+
|
|
2164
|
+
if not app["supported"]:
|
|
2165
|
+
reason = app["reason"] or f"no OUMV adapter for {framework} yet"
|
|
2166
|
+
actions.append({
|
|
2167
|
+
"kind": "backend_unsupported",
|
|
2168
|
+
"profile": "backend",
|
|
2169
|
+
"app": root,
|
|
2170
|
+
"framework": framework,
|
|
2171
|
+
"status": "planned",
|
|
2172
|
+
"writes_repo": False,
|
|
2173
|
+
"reason": reason,
|
|
2174
|
+
"description": reason,
|
|
2175
|
+
})
|
|
2176
|
+
continue
|
|
2177
|
+
|
|
2178
|
+
install = _backend_install(catalog, provider)
|
|
2179
|
+
if provider in ("fastapi", "python") and framework in ("fastapi", "starlette"):
|
|
1568
2180
|
actions.append({
|
|
1569
2181
|
"kind": "python_autoload",
|
|
1570
2182
|
"profile": "backend",
|
|
1571
|
-
"
|
|
2183
|
+
"app": root,
|
|
2184
|
+
"framework": framework,
|
|
1572
2185
|
"writes_repo": False,
|
|
1573
2186
|
"description": (
|
|
1574
2187
|
"sitecustomize patches uvicorn; mount_tokensafe(app) runs on import and detects "
|
|
@@ -1578,22 +2191,40 @@ def plan(workspace: str) -> Dict[str, Any]:
|
|
|
1578
2191
|
"run": python_run_hint(workspace),
|
|
1579
2192
|
})
|
|
1580
2193
|
elif provider == "go":
|
|
1581
|
-
state = go_patch_state(workspace)
|
|
1582
|
-
|
|
1583
|
-
"
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
2194
|
+
state = go_patch_state(workspace, root)
|
|
2195
|
+
if state.get("entrypoint") and (
|
|
2196
|
+
framework == "net/http" or state.get("framework") in ("nethttp", "stdhttp")
|
|
2197
|
+
):
|
|
2198
|
+
actions.append({
|
|
2199
|
+
"kind": "go_manual_recipe",
|
|
2200
|
+
"profile": "backend",
|
|
2201
|
+
"app": root,
|
|
2202
|
+
"framework": "net/http",
|
|
2203
|
+
"writes_repo": True,
|
|
2204
|
+
"entrypoint": state.get("entrypoint"),
|
|
2205
|
+
"status": "manual",
|
|
2206
|
+
"snippet": _GO_MANUAL_SNIPPET,
|
|
2207
|
+
"reason": info.get("note") or "net/http needs the stdhttp adapter's mux",
|
|
2208
|
+
"install": install,
|
|
2209
|
+
})
|
|
2210
|
+
else:
|
|
2211
|
+
actions.append({
|
|
2212
|
+
"kind": "go_one_line_patch",
|
|
2213
|
+
"profile": "backend",
|
|
2214
|
+
"app": root,
|
|
2215
|
+
"framework": framework or "go",
|
|
2216
|
+
"writes_repo": True,
|
|
2217
|
+
"already_patched": state["patched"],
|
|
2218
|
+
"entrypoint": state["entrypoint"],
|
|
2219
|
+
"description": "one AutoMount() line between tokensafe markers; byte-exact backup + --revert",
|
|
2220
|
+
"install": install,
|
|
2221
|
+
})
|
|
1592
2222
|
elif provider == "elysia":
|
|
1593
|
-
state = elysia_patch_state(workspace)
|
|
2223
|
+
state = elysia_patch_state(workspace, root)
|
|
1594
2224
|
actions.append({
|
|
1595
2225
|
"kind": "elysia_plugin_patch",
|
|
1596
2226
|
"profile": "backend",
|
|
2227
|
+
"app": root,
|
|
1597
2228
|
"framework": "elysia",
|
|
1598
2229
|
"writes_repo": True,
|
|
1599
2230
|
"already_patched": state["patched"],
|
|
@@ -1602,11 +2233,12 @@ def plan(workspace: str) -> Dict[str, Any]:
|
|
|
1602
2233
|
"install": install or "bun add tokensafe-backend-node",
|
|
1603
2234
|
})
|
|
1604
2235
|
elif provider == "node":
|
|
1605
|
-
state = node_patch_state(workspace)
|
|
2236
|
+
state = node_patch_state(workspace, root)
|
|
1606
2237
|
actions.append({
|
|
1607
2238
|
"kind": "node_one_line_patch",
|
|
1608
2239
|
"profile": "backend",
|
|
1609
|
-
"
|
|
2240
|
+
"app": root,
|
|
2241
|
+
"framework": state.get("framework") or framework,
|
|
1610
2242
|
"writes_repo": True,
|
|
1611
2243
|
"already_patched": state["patched"],
|
|
1612
2244
|
"entrypoint": state["entrypoint"],
|
|
@@ -1614,10 +2246,11 @@ def plan(workspace: str) -> Dict[str, Any]:
|
|
|
1614
2246
|
"install": install or "npm install tokensafe-backend-node",
|
|
1615
2247
|
})
|
|
1616
2248
|
elif provider == "dotnet":
|
|
1617
|
-
state = dotnet_patch_state(workspace)
|
|
2249
|
+
state = dotnet_patch_state(workspace, root)
|
|
1618
2250
|
actions.append({
|
|
1619
2251
|
"kind": "dotnet_one_line_patch",
|
|
1620
2252
|
"profile": "backend",
|
|
2253
|
+
"app": root,
|
|
1621
2254
|
"framework": "aspnetcore",
|
|
1622
2255
|
"writes_repo": True,
|
|
1623
2256
|
"already_patched": state["patched"],
|
|
@@ -1628,26 +2261,18 @@ def plan(workspace: str) -> Dict[str, Any]:
|
|
|
1628
2261
|
"run": "dotnet run",
|
|
1629
2262
|
})
|
|
1630
2263
|
elif provider in ("spring", "php"):
|
|
1631
|
-
sidecar_path, note =
|
|
1632
|
-
command = sidecar_run_command(provider, sidecar_path or "", workspace)
|
|
2264
|
+
sidecar_path, note = sidecar_cached(provider)
|
|
1633
2265
|
actions.append({
|
|
1634
2266
|
"kind": "sidecar",
|
|
1635
2267
|
"profile": "backend",
|
|
1636
|
-
"
|
|
2268
|
+
"app": root,
|
|
2269
|
+
"framework": framework or provider,
|
|
1637
2270
|
"writes_repo": False,
|
|
1638
2271
|
"sidecar": sidecar_path,
|
|
1639
2272
|
"install": note,
|
|
1640
|
-
"run":
|
|
2273
|
+
"run": sidecar_run_command(provider, sidecar_path or "", workspace),
|
|
1641
2274
|
"description": "static route scan + OCC edits + verify through the single-file sidecar; nothing is written into the project",
|
|
1642
2275
|
})
|
|
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
2276
|
|
|
1652
2277
|
db = detect_orm(workspace)
|
|
1653
2278
|
for action in actions:
|
|
@@ -1655,7 +2280,7 @@ def plan(workspace: str) -> Dict[str, Any]:
|
|
|
1655
2280
|
|
|
1656
2281
|
return {
|
|
1657
2282
|
"workspace": workspace,
|
|
1658
|
-
"profiles": [p for p in ("frontend", "backend") if
|
|
2283
|
+
"profiles": [p for p in ("frontend", "backend") if any(a["role"] == p for a in apps)],
|
|
1659
2284
|
"actions": actions,
|
|
1660
2285
|
"python_autoload_present": python_autoload_present(),
|
|
1661
2286
|
"revertable": bool(glob.glob(os.path.join(_inject_dir(workspace), "manifests", "*.json")))
|
|
@@ -1664,65 +2289,187 @@ def plan(workspace: str) -> Dict[str, Any]:
|
|
|
1664
2289
|
|
|
1665
2290
|
|
|
1666
2291
|
def apply(workspace: str, dry_run: bool = False, include_go: bool = True) -> Dict[str, Any]:
|
|
1667
|
-
"""Wires
|
|
2292
|
+
"""Wires every detected supported app; a monorepo is not truncated to the first."""
|
|
1668
2293
|
results: Dict[str, Any] = {"workspace": workspace, "actions": []}
|
|
2294
|
+
stack = detect_project_stack(workspace)
|
|
1669
2295
|
|
|
1670
|
-
config, conf_path, created = generate_config(workspace, dry_run=dry_run)
|
|
2296
|
+
config, conf_path, created = generate_config(workspace, stack=stack, dry_run=dry_run)
|
|
1671
2297
|
results["config"] = {
|
|
1672
2298
|
"path": conf_path,
|
|
1673
2299
|
"created": created,
|
|
1674
2300
|
"mutate": config.get("permissions", {}).get("mutate", True),
|
|
2301
|
+
"skipped": config.get("_skipped_reason"),
|
|
1675
2302
|
}
|
|
2303
|
+
if not dry_run and conf_path:
|
|
2304
|
+
_write_config_state(workspace, conf_path, created)
|
|
2305
|
+
|
|
2306
|
+
python_written: Optional[Dict[str, Any]] = None
|
|
2307
|
+
sidecars: Dict[str, Tuple[Optional[str], str]] = {}
|
|
2308
|
+
for app in _injectable_apps(stack):
|
|
2309
|
+
root = app["app"]
|
|
2310
|
+
role = app["role"]
|
|
2311
|
+
framework = app["framework"] or ""
|
|
2312
|
+
provider = app["provider"] or ""
|
|
2313
|
+
if role == "frontend":
|
|
2314
|
+
if framework == "nextjs":
|
|
2315
|
+
results["actions"].append({
|
|
2316
|
+
"kind": "next_route_handler",
|
|
2317
|
+
"profile": "backend",
|
|
2318
|
+
"app": root,
|
|
2319
|
+
**apply_next_patch(workspace, dry_run=dry_run, root=root),
|
|
2320
|
+
})
|
|
2321
|
+
elif not app["supported"]:
|
|
2322
|
+
results["actions"].append({
|
|
2323
|
+
"kind": "frontend_unsupported",
|
|
2324
|
+
"profile": "frontend",
|
|
2325
|
+
"app": root,
|
|
2326
|
+
"status": "planned",
|
|
2327
|
+
"framework": framework,
|
|
2328
|
+
"reason": app["reason"] or f"no OUMV adapter for {framework} yet",
|
|
2329
|
+
})
|
|
2330
|
+
else:
|
|
2331
|
+
results["actions"].append({
|
|
2332
|
+
"kind": "frontend_zero_footprint",
|
|
2333
|
+
"profile": "frontend",
|
|
2334
|
+
"app": root,
|
|
2335
|
+
"status": "ready",
|
|
2336
|
+
"run": _frontend_run(root, framework),
|
|
2337
|
+
"note": "no repository files are written; the bridge lives in the dev-server wrapper",
|
|
2338
|
+
})
|
|
2339
|
+
continue
|
|
1676
2340
|
|
|
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
|
-
|
|
2341
|
+
if not app["supported"]:
|
|
2342
|
+
results["actions"].append({
|
|
2343
|
+
"kind": "backend_unsupported",
|
|
2344
|
+
"profile": "backend",
|
|
2345
|
+
"app": root,
|
|
2346
|
+
"status": "skipped",
|
|
2347
|
+
"framework": framework,
|
|
2348
|
+
"reason": app["reason"] or f"no OUMV adapter for {framework} yet",
|
|
2349
|
+
})
|
|
2350
|
+
continue
|
|
2351
|
+
|
|
2352
|
+
if provider in ("fastapi", "python") and framework in ("fastapi", "starlette"):
|
|
2353
|
+
if dry_run:
|
|
2354
|
+
action = {
|
|
2355
|
+
"kind": "python_autoload",
|
|
2356
|
+
"status": "would-write",
|
|
2357
|
+
"path": os.path.join(pyhooks_dir(), "sitecustomize.py"),
|
|
2358
|
+
}
|
|
2359
|
+
else:
|
|
2360
|
+
if python_written is None:
|
|
2361
|
+
python_written = ensure_python_autoload()
|
|
2362
|
+
_write_manifest(workspace, "python", {
|
|
2363
|
+
"kind": "python",
|
|
2364
|
+
"app": ".",
|
|
2365
|
+
"path": python_written.get("path"),
|
|
2366
|
+
})
|
|
2367
|
+
action = {"kind": "python_autoload", **python_written, "run": python_run_hint(workspace)}
|
|
2368
|
+
results["actions"].append({"kind": "python_autoload", "profile": "backend", "app": root, **action})
|
|
2369
|
+
elif provider == "go" and include_go:
|
|
2370
|
+
results["actions"].append({
|
|
2371
|
+
"kind": "go_one_line_patch",
|
|
2372
|
+
"profile": "backend",
|
|
2373
|
+
"app": root,
|
|
2374
|
+
**apply_go_patch(workspace, dry_run=dry_run, root=root),
|
|
2375
|
+
})
|
|
2376
|
+
elif provider == "elysia":
|
|
2377
|
+
results["actions"].append({
|
|
2378
|
+
"kind": "elysia_plugin_patch",
|
|
2379
|
+
"profile": "backend",
|
|
2380
|
+
"app": root,
|
|
2381
|
+
**apply_elysia_patch(workspace, dry_run=dry_run, root=root),
|
|
2382
|
+
})
|
|
2383
|
+
elif provider == "node":
|
|
2384
|
+
results["actions"].append({
|
|
2385
|
+
"kind": "node_one_line_patch",
|
|
2386
|
+
"profile": "backend",
|
|
2387
|
+
"app": root,
|
|
2388
|
+
**apply_node_patch(workspace, dry_run=dry_run, root=root),
|
|
2389
|
+
})
|
|
2390
|
+
elif provider == "dotnet":
|
|
2391
|
+
results["actions"].append({
|
|
2392
|
+
"kind": "dotnet_one_line_patch",
|
|
2393
|
+
"profile": "backend",
|
|
2394
|
+
"app": root,
|
|
2395
|
+
**apply_dotnet_patch(workspace, dry_run=dry_run, root=root),
|
|
2396
|
+
})
|
|
2397
|
+
elif provider in ("spring", "php"):
|
|
2398
|
+
if provider not in sidecars:
|
|
2399
|
+
sidecars[provider] = (
|
|
2400
|
+
sidecar_cached(provider) if dry_run else ensure_sidecar(provider)
|
|
2401
|
+
)
|
|
2402
|
+
sidecar_path, note = sidecars[provider]
|
|
2403
|
+
results["actions"].append({
|
|
2404
|
+
"kind": "sidecar",
|
|
2405
|
+
"profile": "backend",
|
|
2406
|
+
"app": root,
|
|
2407
|
+
"status": "ready" if sidecar_path else "needs-source",
|
|
2408
|
+
"sidecar": sidecar_path,
|
|
2409
|
+
"note": note,
|
|
2410
|
+
"run": sidecar_run_command(provider, sidecar_path or "", workspace),
|
|
2411
|
+
})
|
|
1716
2412
|
|
|
1717
2413
|
return results
|
|
1718
2414
|
|
|
1719
2415
|
|
|
2416
|
+
def _revert_manifest(workspace: str, kind: str, manifest: Dict[str, Any]) -> Dict[str, Any]:
|
|
2417
|
+
app = manifest.get("app") or "."
|
|
2418
|
+
if kind == "go":
|
|
2419
|
+
return revert_go_patch(workspace, app, manifest)
|
|
2420
|
+
if kind == "node":
|
|
2421
|
+
return revert_node_patch(workspace, app, manifest)
|
|
2422
|
+
if kind == "elysia":
|
|
2423
|
+
return revert_elysia_patch(workspace, app, manifest)
|
|
2424
|
+
if kind == "dotnet":
|
|
2425
|
+
return revert_dotnet_patch(workspace, app, manifest)
|
|
2426
|
+
if kind == "next":
|
|
2427
|
+
return revert_next_patch(workspace, app, manifest)
|
|
2428
|
+
if kind == "python":
|
|
2429
|
+
return revert_python_autoload(workspace, manifest)
|
|
2430
|
+
return {"status": "error", "reason": f"unknown manifest kind {kind!r}"}
|
|
2431
|
+
|
|
2432
|
+
|
|
1720
2433
|
def revert(workspace: str) -> Dict[str, Any]:
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
"
|
|
1725
|
-
|
|
1726
|
-
|
|
1727
|
-
|
|
1728
|
-
|
|
2434
|
+
"""Reverts every per-app manifest, then the config state."""
|
|
2435
|
+
results: Dict[str, Any] = {"workspace": workspace}
|
|
2436
|
+
for kind in ("go", "node", "elysia", "dotnet", "next", "python"):
|
|
2437
|
+
results[kind] = {"status": "nothing-to-revert"}
|
|
2438
|
+
|
|
2439
|
+
base = os.path.join(_inject_dir(workspace), "manifests")
|
|
2440
|
+
for path in sorted(glob.glob(os.path.join(base, "*.json"))):
|
|
2441
|
+
try:
|
|
2442
|
+
with open(path, "r", encoding="utf-8") as handle:
|
|
2443
|
+
manifest = json.load(handle)
|
|
2444
|
+
except Exception:
|
|
2445
|
+
continue
|
|
2446
|
+
manifest["_manifest"] = path
|
|
2447
|
+
kind = manifest.get("kind") or os.path.basename(path).split("--")[0][:-5]
|
|
2448
|
+
app = manifest.get("app") or "."
|
|
2449
|
+
key = kind if app in (".", "") else f"{kind}@{app}"
|
|
2450
|
+
results[key] = _revert_manifest(workspace, kind, manifest)
|
|
2451
|
+
|
|
2452
|
+
legacy = os.path.join(_inject_dir(workspace), "manifest.json")
|
|
2453
|
+
if os.path.isfile(legacy):
|
|
2454
|
+
try:
|
|
2455
|
+
with open(legacy, "r", encoding="utf-8") as handle:
|
|
2456
|
+
manifest = json.load(handle)
|
|
2457
|
+
except Exception:
|
|
2458
|
+
manifest = {}
|
|
2459
|
+
if manifest:
|
|
2460
|
+
manifest["_manifest"] = legacy
|
|
2461
|
+
kind = {
|
|
2462
|
+
"serve": "go",
|
|
2463
|
+
"mount": "go",
|
|
2464
|
+
"go_patch": "go",
|
|
2465
|
+
"node_mount": "node",
|
|
2466
|
+
"elysia_plugin": "elysia",
|
|
2467
|
+
"dotnet_mount": "dotnet",
|
|
2468
|
+
"next_route": "next",
|
|
2469
|
+
"next_route_v2": "next",
|
|
2470
|
+
}.get(manifest.get("mode"), "")
|
|
2471
|
+
if kind:
|
|
2472
|
+
results[kind] = _revert_manifest(workspace, kind, manifest)
|
|
2473
|
+
|
|
2474
|
+
results["config"] = revert_config(workspace)
|
|
2475
|
+
return results
|