tokensafe 4.6.1 → 4.6.3
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/hooks/__pycache__/claude_code_hook.cpython-312.pyc +0 -0
- package/hooks/__pycache__/cursor_hook.cpython-312.pyc +0 -0
- package/hooks/__pycache__/kimi_hook.cpython-312.pyc +0 -0
- package/hooks/__pycache__/pre_invocation.cpython-312.pyc +0 -0
- package/hooks/__pycache__/pre_tool_use.cpython-312.pyc +0 -0
- package/hooks/__pycache__/session_start.cpython-312.pyc +0 -0
- package/hooks/__pycache__/stop_hook.cpython-312.pyc +0 -0
- package/hooks/__pycache__/zcode_hook.cpython-312.pyc +0 -0
- package/hooks/pre_tool_use.py +17 -0
- package/hooks/session_start.py +12 -2
- package/kimi.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/rules/AGENTS.md +1 -1
- package/server.json +3 -3
- package/skills/token-optimizer/SKILL.md +6 -1
- package/src/adapter_core.py +91 -12
- package/src/batch_editor.py +36 -2
- package/src/batch_search.py +31 -5
- package/src/cli.py +57 -1
- package/src/command_sanitizer.py +126 -0
- package/src/guard.py +47 -0
- package/src/installer.py +61 -5
- package/src/mcp_server.py +92 -30
- package/src/oumv_gateway.py +326 -37
- package/src/proxy.py +11 -4
- package/src/retrofit.py +467 -99
- package/src/snapshot.py +3 -2
- package/src/telemetry_sync.py +6 -2
- package/src/transcript_analyzer.py +13 -9
- package/src/version_checker.py +1 -1
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
package/hooks/pre_tool_use.py
CHANGED
|
@@ -268,6 +268,14 @@ def _handle(payload: dict) -> dict:
|
|
|
268
268
|
|
|
269
269
|
# Step 3A: If model explicitly specified line range, respect it
|
|
270
270
|
if start_line is not None and end_line is not None:
|
|
271
|
+
if not response.get("reason"):
|
|
272
|
+
try:
|
|
273
|
+
from src.adapter_core import get_oumv_read_edit_advisory
|
|
274
|
+
oumv_note = get_oumv_read_edit_advisory(hook_cwd, path or raw_path, conversation_id)
|
|
275
|
+
if oumv_note:
|
|
276
|
+
response["reason"] = oumv_note
|
|
277
|
+
except Exception:
|
|
278
|
+
pass
|
|
271
279
|
return response
|
|
272
280
|
|
|
273
281
|
# Step 3B: If a specific symbol/function is targeted in user prompt, check graph-guided skeleton first
|
|
@@ -341,6 +349,15 @@ def _handle(payload: dict) -> dict:
|
|
|
341
349
|
)
|
|
342
350
|
return response
|
|
343
351
|
|
|
352
|
+
if not response.get("reason"):
|
|
353
|
+
try:
|
|
354
|
+
from src.adapter_core import get_oumv_read_edit_advisory
|
|
355
|
+
oumv_note = get_oumv_read_edit_advisory(hook_cwd, path or raw_path, conversation_id)
|
|
356
|
+
if oumv_note:
|
|
357
|
+
response["reason"] = oumv_note
|
|
358
|
+
except Exception:
|
|
359
|
+
pass
|
|
360
|
+
|
|
344
361
|
# 4. run_command Optimization & TokenSafe Guard
|
|
345
362
|
elif canon_tool == "bash":
|
|
346
363
|
from src.guard import TokenSafeGuard
|
package/hooks/session_start.py
CHANGED
|
@@ -107,13 +107,23 @@ def main():
|
|
|
107
107
|
from src.graph_engine import GraphEngine
|
|
108
108
|
graph = GraphEngine.get_instance(workspace_root)
|
|
109
109
|
banner = graph.format_topology_banner()
|
|
110
|
+
extra = []
|
|
110
111
|
if banner:
|
|
111
|
-
|
|
112
|
-
f"{directives}\n\n"
|
|
112
|
+
extra.append(
|
|
113
113
|
f"{banner}\n"
|
|
114
114
|
"⚡ Core God Nodes and dependency hubs mapped above. "
|
|
115
115
|
"Call 'tokensafe:repo_map(view=\"graph\", project_path=...)' for full dependency trees."
|
|
116
116
|
)
|
|
117
|
+
# Separate try: an OUMV brief failure must not drop the God-Nodes banner.
|
|
118
|
+
try:
|
|
119
|
+
from src.retrofit import format_oumv_workspace_brief
|
|
120
|
+
oumv_brief = format_oumv_workspace_brief(workspace_root, include_live=True)
|
|
121
|
+
if oumv_brief:
|
|
122
|
+
extra.append(oumv_brief)
|
|
123
|
+
except Exception:
|
|
124
|
+
pass
|
|
125
|
+
if extra:
|
|
126
|
+
directives = f"{directives}\n\n" + "\n".join(extra)
|
|
117
127
|
except Exception:
|
|
118
128
|
pass
|
|
119
129
|
|
package/kimi.plugin.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
|
-
"version": "4.6.
|
|
3
|
+
"version": "4.6.3",
|
|
4
4
|
"description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
|
|
5
5
|
"homepage": "https://tokensafe.dev",
|
|
6
6
|
"license": "MIT",
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"mcpName": "dev.tokensafe/tokensafe",
|
|
4
|
-
"version": "4.6.
|
|
4
|
+
"version": "4.6.3",
|
|
5
5
|
"description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
|
|
6
6
|
"main": "bin/tokensafe.js",
|
|
7
7
|
"bin": {
|
package/plugin.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"displayName": "TokenSafe",
|
|
4
|
-
"version": "4.6.
|
|
4
|
+
"version": "4.6.3",
|
|
5
5
|
"description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
|
|
6
6
|
"logo": "assets/logo.png",
|
|
7
7
|
"developerName": "TokenSafe",
|
package/rules/AGENTS.md
CHANGED
|
@@ -45,7 +45,7 @@ Execute the specified action directly based on these extracted parameters.
|
|
|
45
45
|
- `"diff"` (`diff`): slice unified git diffs
|
|
46
46
|
- `"image"` (`image_path`, `max_edge=1024`): downscale screenshots (-50-75% vision tokens)
|
|
47
47
|
- `"compress"` (`prompt`): TOCP S-expression compression
|
|
48
|
-
7. **Universal OUMV Protocol (`oumv`)**:
|
|
48
|
+
7. **Universal OUMV Protocol (`oumv` — Mandatory When Supported)**: When a project uses an OUMV-supported stack (`frontend/react` Vite, `frontend/vue`, `frontend/solid`, `backend/go`, `backend/fastapi`), ALWAYS prefer `tokensafe:oumv(action="status"|"observe"|"understand"|"verify"|"mutate"|"graph", ...)` BEFORE full file crawls, raw `curl`, or headless browsers — even for read/edit tasks (static AST OUMV works offline without running dev/build). For Vite+React, use `tokensafe dev` to start live OUMV with zero repository footprint. In mixed monorepos (e.g. React + Node.js), inspect `oumv(action="status")` / `[TokenSafe OUMV Workspace Matrix]`: use `oumv` on supported profiles and fall back to `repo_map` + `smart_read_file` + `scoped_search` for unsupported stacks (`backend/node`).
|
|
49
49
|
8. **Bounded Reads & Styles**: Never call raw `read_file` without `StartLine`/`EndLine` on files > 100 lines. `smart_read_file` preserves CSS/SCSS/Tailwind design tokens (`:root`, `@theme`) in full.
|
|
50
50
|
|
|
51
51
|
### 4. Turn Token Savings Footer (Proof-of-Savings — always in English)
|
package/server.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"name": "dev.tokensafe/tokensafe",
|
|
4
4
|
"title": "TokenSafe",
|
|
5
5
|
"description": "Your AI agent is smart enough to code all day. Local firewall & zero-loss runtime.",
|
|
6
|
-
"version": "4.6.
|
|
6
|
+
"version": "4.6.3",
|
|
7
7
|
"websiteUrl": "https://tokensafe.dev",
|
|
8
8
|
"repository": {
|
|
9
9
|
"url": "https://github.com/tokensafe-dev/tokensafe",
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
"registryType": "npm",
|
|
24
24
|
"registryBaseUrl": "https://registry.npmjs.org",
|
|
25
25
|
"identifier": "tokensafe",
|
|
26
|
-
"version": "4.6.
|
|
26
|
+
"version": "4.6.3",
|
|
27
27
|
"runtimeHint": "npx",
|
|
28
28
|
"transport": {
|
|
29
29
|
"type": "stdio"
|
|
@@ -39,7 +39,7 @@
|
|
|
39
39
|
"registryType": "pypi",
|
|
40
40
|
"registryBaseUrl": "https://pypi.org",
|
|
41
41
|
"identifier": "tokensafe",
|
|
42
|
-
"version": "4.6.
|
|
42
|
+
"version": "4.6.3",
|
|
43
43
|
"runtimeHint": "uvx",
|
|
44
44
|
"transport": {
|
|
45
45
|
"type": "stdio"
|
|
@@ -110,7 +110,12 @@ TokenSafe actively maximizes provider KV-cache hit rates alongside token compres
|
|
|
110
110
|
|
|
111
111
|
## Universal OUMV Protocol (Runtime Introspection & Verification)
|
|
112
112
|
|
|
113
|
-
TokenSafe integrates the **Universal Agent-Runtime Protocol (UARP / OUMV)** to inspect, reason about, edit, and verify
|
|
113
|
+
TokenSafe integrates the **Universal Agent-Runtime Protocol (UARP / OUMV)** to inspect, reason about, edit, and verify Frontend (`tokensafe-ui`, React 18/19 + Vite, Vue 3) and Backend (`Go` Gin/Chi/net-http, `FastAPI`) services without heavy headless browsers or unconstrained shell curls.
|
|
114
|
+
|
|
115
|
+
### OUMV-First Policy, Zero-Footprint & Mixed Monorepos
|
|
116
|
+
- **Mandatory When Supported (Even Without Dev/Build Running)**: If the workspace contains a supported profile (`frontend/react`, `frontend/vue`, `frontend/solid`, `backend/go`, `backend/fastapi`), prefer `tokensafe:oumv` (`status` -> `observe` L0/L1/L2 -> `understand` impact -> `mutate` -> `verify`) BEFORE brute-force reading components or running `curl`/browsers. Static OUMV works offline even when the agent only reads and edits files.
|
|
117
|
+
- **Zero-Footprint Vite+React (`tokensafe dev`)**: Running `tokensafe dev` (or `vite` / `npm run dev` rewritten automatically by `CommandSanitizer`) starts the project's Vite+React DevServer with `tokensafeReact()` injected in memory and runtime state stored under `~/.tokensafe/runtimes/<hash>.json` (sidecar L2 contracts in `~/.tokensafe/contracts/<hash>.json`) — leaving **0 modified/untracked files** in the repository.
|
|
118
|
+
- **Monorepo Capability Boundaries**: In mixed monorepos (e.g., `apps/web` in React + `apps/api` in Node.js/Express), check `oumv(action="status")` or `[TokenSafe OUMV Workspace Matrix]`. Use `tokensafe:oumv(runtime="frontend")` for React, and use `repo_map` + `smart_read_file` + `scoped_search` + normal tests for unsupported backends like `backend/node` (`status: planned`).
|
|
114
119
|
|
|
115
120
|
1. **LIVE RUNTIME HEALTH (`oumv(action="status")`)**:
|
|
116
121
|
- Call `tokensafe:oumv(action="status")` to inspect connection status and capabilities of running DevServers (Frontend ports 5173/3000, Backend ports 8080/8000).
|
package/src/adapter_core.py
CHANGED
|
@@ -44,7 +44,8 @@ TOKENSAFE_DIRECTIVES = (
|
|
|
44
44
|
"• Before large multi-step tasks: call 'tokensafe:session_context(action=\"budget\", model=...)' to check context headroom and Quality Score (Grade S-F).\n"
|
|
45
45
|
"• When context budget reports warning/critical or Grade C/F: call 'tokensafe:session_context(action=\"compact\", transcript_path=...)' to fold history before continuing.\n"
|
|
46
46
|
"• Prohibited File Edits: NEVER use 'sed -i', 'perl -i', or stream editors to modify source files; ALWAYS use 'edit_file' with exact string targets. NEVER suppress errors with '2>/dev/null'.\n"
|
|
47
|
-
"• Prefer 'edit_file' over 'write_file' for existing files
|
|
47
|
+
"• Prefer 'edit_file' over 'write_file' for existing files.\n"
|
|
48
|
+
"• Universal OUMV Protocol (Mandatory When Supported): If the workspace reports an OUMV-supported stack (React+Vite, Vue, Solid, Go, FastAPI), ALWAYS prefer the 'oumv' MCP tool (status/observe/understand/verify) before full file crawls, raw curl, or browser checks — even when only reading/editing files (static AST OUMV works offline; use 'tokensafe dev' for zero-footprint live Vite+React). Check capability boundaries in mixed monorepos (for unsupported stacks like backend/node Express/Fastify/Nest, use repo_map/smart_read_file/scoped_search)."
|
|
48
49
|
)
|
|
49
50
|
|
|
50
51
|
# High-precision deny patterns: secrets and irreversible destruction only.
|
|
@@ -456,6 +457,77 @@ def _extract_path(tool_input: Dict[str, Any]) -> str:
|
|
|
456
457
|
return ""
|
|
457
458
|
|
|
458
459
|
|
|
460
|
+
_NUDGE_GC_AGE_SEC = 7 * 86400
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
def _gc_oumv_markers(data_dir: str) -> None:
|
|
464
|
+
"""Drops one-shot OUMV markers older than a week: one accrues per session forever."""
|
|
465
|
+
try:
|
|
466
|
+
now = time.time()
|
|
467
|
+
for name in os.listdir(data_dir):
|
|
468
|
+
if not name.startswith((".oumv_nudge_", ".oumv_used_")):
|
|
469
|
+
continue
|
|
470
|
+
marker_path = os.path.join(data_dir, name)
|
|
471
|
+
try:
|
|
472
|
+
if now - os.path.getmtime(marker_path) > _NUDGE_GC_AGE_SEC:
|
|
473
|
+
os.unlink(marker_path)
|
|
474
|
+
except OSError:
|
|
475
|
+
pass
|
|
476
|
+
except Exception:
|
|
477
|
+
pass
|
|
478
|
+
|
|
479
|
+
|
|
480
|
+
def get_oumv_read_edit_advisory(workspace_dir: str, file_path: str, session_id: str = "") -> Optional[str]:
|
|
481
|
+
"""One-shot per-session advisory when reading/editing files inside an OUMV-supported stack
|
|
482
|
+
(React+Vite, Vue, Solid, Go, FastAPI) without having called `tokensafe:oumv` recently.
|
|
483
|
+
|
|
484
|
+
Returns None immediately for unsupported stacks in mixed monorepos (e.g. backend/node),
|
|
485
|
+
when OUMV was already used in this workspace, or if already nudged in this session.
|
|
486
|
+
"""
|
|
487
|
+
if not file_path:
|
|
488
|
+
return None
|
|
489
|
+
try:
|
|
490
|
+
from src.paths import get_active_workspace, resolve_data_dir
|
|
491
|
+
from src.retrofit import is_path_in_supported_oumv_scope
|
|
492
|
+
from src.oumv_gateway import OUMVGateway
|
|
493
|
+
import hashlib
|
|
494
|
+
|
|
495
|
+
ws = workspace_dir or get_active_workspace()
|
|
496
|
+
if not ws or not os.path.isdir(ws):
|
|
497
|
+
return None
|
|
498
|
+
# Cheap marker first: resolving the owning stack walks every manifest in
|
|
499
|
+
# the monorepo, and this runs on every read/write hook.
|
|
500
|
+
if OUMVGateway.was_recently_used(ws):
|
|
501
|
+
return None
|
|
502
|
+
pkg = is_path_in_supported_oumv_scope(ws, file_path, use_cache=True)
|
|
503
|
+
if not pkg:
|
|
504
|
+
return None
|
|
505
|
+
|
|
506
|
+
sess_key = hashlib.sha256(f"{session_id or 'default'}:{os.path.realpath(ws)}".encode("utf-8")).hexdigest()[:16]
|
|
507
|
+
data_dir = resolve_data_dir()
|
|
508
|
+
marker = os.path.join(data_dir, f".oumv_nudge_{sess_key}")
|
|
509
|
+
if os.path.isfile(marker):
|
|
510
|
+
return None
|
|
511
|
+
os.makedirs(data_dir, exist_ok=True)
|
|
512
|
+
_gc_oumv_markers(data_dir)
|
|
513
|
+
with open(marker, "w", encoding="utf-8") as f:
|
|
514
|
+
f.write(str(time.time()))
|
|
515
|
+
|
|
516
|
+
live_ports = OUMVGateway.get_live_ports(ws)
|
|
517
|
+
if live_ports:
|
|
518
|
+
return (
|
|
519
|
+
f"[TokenSafe OUMV]: Live {pkg.get('provider')}/{pkg.get('framework')} OUMV runtime is active (port {live_ports[0]}). "
|
|
520
|
+
f"Prefer tokensafe:oumv(action='observe'|'understand'|'verify') for live DOM/state/causality instead of manual file crawling."
|
|
521
|
+
)
|
|
522
|
+
vite_tip = "; run 'tokensafe dev' for zero-footprint live Vite+React RPC" if pkg.get("vite") else ""
|
|
523
|
+
return (
|
|
524
|
+
f"[TokenSafe OUMV]: '{os.path.basename(file_path)}' belongs to an OUMV-supported {pkg.get('provider')}/{pkg.get('framework')} stack. "
|
|
525
|
+
f"Use tokensafe:oumv(action='observe', level='L1') or oumv(action='understand', query='impact') first (works statically offline{vite_tip})."
|
|
526
|
+
)
|
|
527
|
+
except Exception:
|
|
528
|
+
return None
|
|
529
|
+
|
|
530
|
+
|
|
459
531
|
def _large_read_advisory(file_path: str, tool_input: Dict[str, Any]) -> Optional[str]:
|
|
460
532
|
"""Non-blocking advisory when an agent reads an entire large code file unbounded."""
|
|
461
533
|
if not file_path or not os.path.isfile(file_path):
|
|
@@ -502,15 +574,14 @@ def evaluate_cc_pre_tool_use(payload: Dict[str, Any], agent: str) -> Dict[str, A
|
|
|
502
574
|
tp = str(payload.get("transcript_path") or "")
|
|
503
575
|
canon = canonical_tool_name(tool)
|
|
504
576
|
|
|
505
|
-
def _cc_decision(decision: str, reason: str
|
|
506
|
-
|
|
507
|
-
"
|
|
508
|
-
|
|
509
|
-
|
|
577
|
+
def _cc_decision(decision: str, reason: str) -> Dict[str, Any]:
|
|
578
|
+
return {
|
|
579
|
+
"hookSpecificOutput": {
|
|
580
|
+
"hookEventName": "PreToolUse",
|
|
581
|
+
"permissionDecision": decision,
|
|
582
|
+
"permissionDecisionReason": reason,
|
|
583
|
+
}
|
|
510
584
|
}
|
|
511
|
-
if extra_ctx:
|
|
512
|
-
inner["additionalContext"] = extra_ctx
|
|
513
|
-
return {"hookSpecificOutput": inner}
|
|
514
585
|
|
|
515
586
|
# 1. Loop Detector Guard (all tools)
|
|
516
587
|
try:
|
|
@@ -609,6 +680,9 @@ def evaluate_cc_pre_tool_use(payload: Dict[str, Any], agent: str) -> Dict[str, A
|
|
|
609
680
|
)
|
|
610
681
|
except Exception:
|
|
611
682
|
pass
|
|
683
|
+
# No OUMV advisory on edit: PreToolUse could only deliver it by returning an
|
|
684
|
+
# explicit permissionDecision, and "allow" auto-approves the edit (bypassing the
|
|
685
|
+
# user's permission prompt). The read branch already delivers the same nudge.
|
|
612
686
|
return {}
|
|
613
687
|
|
|
614
688
|
if canon == "read":
|
|
@@ -616,13 +690,18 @@ def evaluate_cc_pre_tool_use(payload: Dict[str, Any], agent: str) -> Dict[str, A
|
|
|
616
690
|
verdict = guard_read(file_path, agent, session_id, transcript_path=tp)
|
|
617
691
|
if verdict["decision"] == "deny":
|
|
618
692
|
return _cc_decision("deny", verdict["reason"])
|
|
619
|
-
|
|
620
|
-
|
|
693
|
+
advisories = [
|
|
694
|
+
msg for msg in (
|
|
695
|
+
_large_read_advisory(file_path, tool_input),
|
|
696
|
+
get_oumv_read_edit_advisory(cwd, file_path, session_id),
|
|
697
|
+
) if msg
|
|
698
|
+
]
|
|
699
|
+
if advisories:
|
|
621
700
|
return {
|
|
622
701
|
"hookSpecificOutput": {
|
|
623
702
|
"hookEventName": "PreToolUse",
|
|
624
703
|
"permissionDecision": "allow",
|
|
625
|
-
"additionalContext":
|
|
704
|
+
"additionalContext": "\n".join(advisories),
|
|
626
705
|
}
|
|
627
706
|
}
|
|
628
707
|
return {}
|
package/src/batch_editor.py
CHANGED
|
@@ -452,6 +452,7 @@ def execute_batch_edits(
|
|
|
452
452
|
"allow_overwrite": overwrite,
|
|
453
453
|
"hunk_count": 0,
|
|
454
454
|
"noop_hunks": 0,
|
|
455
|
+
"clamped_hunks": 0,
|
|
455
456
|
}
|
|
456
457
|
continue
|
|
457
458
|
|
|
@@ -465,6 +466,7 @@ def execute_batch_edits(
|
|
|
465
466
|
current_text = prior_prepared["new_content"]
|
|
466
467
|
prev_hunk_count = prior_prepared["hunk_count"]
|
|
467
468
|
prev_noop_count = prior_prepared.get("noop_hunks", 0)
|
|
469
|
+
prev_clamped_count = prior_prepared.get("clamped_hunks", 0)
|
|
468
470
|
is_create = prior_prepared["is_create"]
|
|
469
471
|
else:
|
|
470
472
|
if not os.path.exists(abs_path):
|
|
@@ -486,11 +488,14 @@ def execute_batch_edits(
|
|
|
486
488
|
continue
|
|
487
489
|
prev_hunk_count = 0
|
|
488
490
|
prev_noop_count = 0
|
|
491
|
+
prev_clamped_count = 0
|
|
489
492
|
is_create = False
|
|
490
493
|
|
|
491
494
|
file_failed = False
|
|
492
495
|
applied_hunk_count = 0
|
|
493
496
|
noop_hunk_count = prev_noop_count
|
|
497
|
+
clamped_hunk_count = 0
|
|
498
|
+
hunk_clamped = False
|
|
494
499
|
|
|
495
500
|
for hunk_idx, hunk in enumerate(hunks):
|
|
496
501
|
if not isinstance(hunk, dict):
|
|
@@ -524,6 +529,15 @@ def execute_batch_edits(
|
|
|
524
529
|
file_failed = True
|
|
525
530
|
break
|
|
526
531
|
|
|
532
|
+
# Clamp end_line beyond EOF: clients routinely read N lines and pass
|
|
533
|
+
# start+limit, and a hard error costs a whole extra turn. The result
|
|
534
|
+
# reports clamped_hunks so a shrunken region is never silent.
|
|
535
|
+
if e_val is not None and e_val > 0:
|
|
536
|
+
line_count = len(current_text.splitlines(keepends=True))
|
|
537
|
+
if e_val > line_count:
|
|
538
|
+
e_val = line_count
|
|
539
|
+
hunk_clamped = True
|
|
540
|
+
|
|
527
541
|
new_text, err = _apply_hunk_to_text(
|
|
528
542
|
current_text,
|
|
529
543
|
target=str(target),
|
|
@@ -544,6 +558,9 @@ def execute_batch_edits(
|
|
|
544
558
|
|
|
545
559
|
current_text = new_text
|
|
546
560
|
applied_hunk_count += 1
|
|
561
|
+
if hunk_clamped:
|
|
562
|
+
clamped_hunk_count += 1
|
|
563
|
+
hunk_clamped = False
|
|
547
564
|
|
|
548
565
|
if not file_failed:
|
|
549
566
|
prepared_files[abs_path] = {
|
|
@@ -552,6 +569,7 @@ def execute_batch_edits(
|
|
|
552
569
|
"is_create": is_create,
|
|
553
570
|
"hunk_count": prev_hunk_count + applied_hunk_count,
|
|
554
571
|
"noop_hunks": noop_hunk_count,
|
|
572
|
+
"clamped_hunks": prev_clamped_count + clamped_hunk_count,
|
|
555
573
|
}
|
|
556
574
|
|
|
557
575
|
# Atomic enforcement: if any file failed and not best_effort, reject all
|
|
@@ -589,6 +607,18 @@ def execute_batch_edits(
|
|
|
589
607
|
write_aborted = False
|
|
590
608
|
for abs_p, p_info in prepared_files.items():
|
|
591
609
|
try:
|
|
610
|
+
if p_info["hunk_count"] == 0 and not p_info["is_create"]:
|
|
611
|
+
# Pure no-op batch entry: report it, but never rewrite identical
|
|
612
|
+
# bytes (that would bump mtime/inode and invalidate readers).
|
|
613
|
+
applied_files_info.append({
|
|
614
|
+
"path": p_info["rel_path"],
|
|
615
|
+
"hunks": 0,
|
|
616
|
+
"noop_hunks": p_info.get("noop_hunks", 0),
|
|
617
|
+
"clamped_hunks": p_info.get("clamped_hunks", 0),
|
|
618
|
+
"is_create": False,
|
|
619
|
+
"unchanged": True,
|
|
620
|
+
})
|
|
621
|
+
continue
|
|
592
622
|
existed = os.path.exists(abs_p)
|
|
593
623
|
orig_bytes: Optional[bytes] = None
|
|
594
624
|
orig_mode: Optional[int] = None
|
|
@@ -610,6 +640,7 @@ def execute_batch_edits(
|
|
|
610
640
|
"path": p_info["rel_path"],
|
|
611
641
|
"hunks": p_info["hunk_count"],
|
|
612
642
|
"noop_hunks": p_info.get("noop_hunks", 0),
|
|
643
|
+
"clamped_hunks": p_info.get("clamped_hunks", 0),
|
|
613
644
|
"is_create": not existed,
|
|
614
645
|
})
|
|
615
646
|
except Exception as e:
|
|
@@ -627,14 +658,17 @@ def execute_batch_edits(
|
|
|
627
658
|
"path": p_info["rel_path"],
|
|
628
659
|
"hunks": p_info["hunk_count"],
|
|
629
660
|
"noop_hunks": p_info.get("noop_hunks", 0),
|
|
661
|
+
"clamped_hunks": p_info.get("clamped_hunks", 0),
|
|
630
662
|
"is_create": p_info["is_create"],
|
|
631
663
|
"dry_run": True
|
|
632
664
|
})
|
|
633
665
|
|
|
666
|
+
total_changed_hunks = sum(int(p.get("hunk_count") or 0) for p in prepared_files.values())
|
|
634
667
|
result: Dict[str, Any] = {
|
|
635
668
|
"success": len(applied_files_info) > 0 and len(failed_files) == 0,
|
|
636
669
|
"applied_count": len(applied_files_info),
|
|
637
670
|
"applied_files": applied_files_info,
|
|
671
|
+
"changed_hunks": total_changed_hunks,
|
|
638
672
|
"failed_count": len(failed_files),
|
|
639
673
|
"failed_files": failed_files,
|
|
640
674
|
"dry_run": dry_run,
|
|
@@ -655,8 +689,8 @@ def execute_batch_edits(
|
|
|
655
689
|
if isinstance(result.get("verify"), dict):
|
|
656
690
|
result["verify"]["rolled_back"] = True
|
|
657
691
|
|
|
658
|
-
# Execute inline verify command if requested and
|
|
659
|
-
if verified_argv and applied_files_info and not dry_run:
|
|
692
|
+
# Execute inline verify command if requested and at least one byte actually changed
|
|
693
|
+
if verified_argv and applied_files_info and not dry_run and total_changed_hunks > 0:
|
|
660
694
|
cmd_str = str(verify).strip()
|
|
661
695
|
t0 = time.time()
|
|
662
696
|
try:
|
package/src/batch_search.py
CHANGED
|
@@ -137,7 +137,13 @@ def _run_git_query(pattern: str, cwd: str, timeout_sec: int = 5, max_results: in
|
|
|
137
137
|
raw_out = strip_ansi(proc.stdout or "").strip()
|
|
138
138
|
lines = [l for l in raw_out.splitlines() if l.strip()]
|
|
139
139
|
limited = lines[:max_results]
|
|
140
|
-
return {
|
|
140
|
+
return {
|
|
141
|
+
"matches": limited,
|
|
142
|
+
# count is the true number of matching lines; matches may be truncated.
|
|
143
|
+
"count": len(lines),
|
|
144
|
+
"truncated": len(lines) > len(limited),
|
|
145
|
+
"raw": "\n".join(limited),
|
|
146
|
+
}
|
|
141
147
|
except subprocess.TimeoutExpired:
|
|
142
148
|
return {"error": f"git query timed out after {timeout_sec}s", "matches": [], "count": 0}
|
|
143
149
|
except Exception as e:
|
|
@@ -152,7 +158,8 @@ def _run_rg_query(
|
|
|
152
158
|
case_sensitive: bool = False,
|
|
153
159
|
file_type: Optional[str] = None,
|
|
154
160
|
glob_filter: Optional[str] = None,
|
|
155
|
-
max_results: int = 25
|
|
161
|
+
max_results: int = 25,
|
|
162
|
+
scope: str = "all"
|
|
156
163
|
) -> Optional[List[Dict[str, Any]]]:
|
|
157
164
|
"""Attempts fast search via ripgrep if available."""
|
|
158
165
|
rg_bin = shutil.which("rg")
|
|
@@ -195,6 +202,7 @@ def _run_rg_query(
|
|
|
195
202
|
# rg exits 1 for "no matches" (not an error) and 2 for real failures.
|
|
196
203
|
if proc.returncode not in (0, 1) and err_text:
|
|
197
204
|
raise RuntimeError(f"ripgrep failed: {err_text.splitlines()[0]}")
|
|
205
|
+
scope_all = str(scope or "all").lower() in ("", "all")
|
|
198
206
|
matches = []
|
|
199
207
|
_rg_line_re = re.compile(r"^(.*):(\d+):(.*)$")
|
|
200
208
|
for line in proc.stdout.splitlines():
|
|
@@ -204,6 +212,15 @@ def _run_rg_query(
|
|
|
204
212
|
if m_line:
|
|
205
213
|
raw_file, raw_lnum, raw_txt = m_line.groups()
|
|
206
214
|
f_path = os.path.relpath(raw_file, cwd)
|
|
215
|
+
# ripgrep has no notion of TokenSafe scopes: apply the same matcher
|
|
216
|
+
# the Python fallback uses so results do not change with rg presence.
|
|
217
|
+
if not scope_all:
|
|
218
|
+
try:
|
|
219
|
+
from src.scoped_search import ScopedSearch
|
|
220
|
+
if not ScopedSearch.is_match_file(f_path, f_path, str(scope).lower()):
|
|
221
|
+
continue
|
|
222
|
+
except Exception:
|
|
223
|
+
pass
|
|
207
224
|
try:
|
|
208
225
|
l_num = int(raw_lnum)
|
|
209
226
|
except ValueError:
|
|
@@ -304,8 +321,16 @@ def _run_python_text_search(
|
|
|
304
321
|
ext = os.path.splitext(full_path)[1].lower()
|
|
305
322
|
if ext in IGNORED_EXTENSIONS:
|
|
306
323
|
continue
|
|
307
|
-
|
|
308
|
-
|
|
324
|
+
# One matcher for every scope ("code", "config", extensions, globs):
|
|
325
|
+
# reusing ScopedSearch keeps the fallback identical to the rg path.
|
|
326
|
+
if str(scope or "all").lower() not in ("", "all"):
|
|
327
|
+
try:
|
|
328
|
+
from src.scoped_search import ScopedSearch
|
|
329
|
+
if not ScopedSearch.is_match_file(full_path, rel_p, str(scope).lower()):
|
|
330
|
+
continue
|
|
331
|
+
except Exception:
|
|
332
|
+
if scope == "code" and ext not in CODE_EXTENSIONS:
|
|
333
|
+
continue
|
|
309
334
|
if type_exts is not None and ext not in type_exts:
|
|
310
335
|
continue
|
|
311
336
|
if glob_filter and not (fnmatch.fnmatch(os.path.basename(full_path), glob_filter) or fnmatch.fnmatch(rel_p, glob_filter)):
|
|
@@ -431,7 +456,8 @@ def _execute_single_query(query_dict: Dict[str, Any], cwd: str) -> Dict[str, Any
|
|
|
431
456
|
case_sensitive=case_sensitive,
|
|
432
457
|
file_type=file_type,
|
|
433
458
|
glob_filter=glob_filter,
|
|
434
|
-
max_results=max_res
|
|
459
|
+
max_results=max_res,
|
|
460
|
+
scope=scope
|
|
435
461
|
)
|
|
436
462
|
|
|
437
463
|
try:
|
package/src/cli.py
CHANGED
|
@@ -97,6 +97,7 @@ def summarize_unittest_output(raw: str, full_traceback: bool = False) -> str:
|
|
|
97
97
|
def _print_help():
|
|
98
98
|
print("TokenSafe CLI — usage: tokensafe <command> [args]\n")
|
|
99
99
|
print("Commands:")
|
|
100
|
+
print(" dev [dir] [--port N] [--host H] [--open] Start Vite+React DevServer with OUMV (zero repo footprint)")
|
|
100
101
|
print(" integrate [--dry-run] Retrofit OUMV into existing project (React, Vue, FastAPI, Go)")
|
|
101
102
|
print(" adapters [list] Catalog of frontend/backend OUMV runtime adapters")
|
|
102
103
|
print(" oumv doctor / status Diagnose OUMV configuration, ports, and permissions")
|
|
@@ -694,8 +695,14 @@ def main(argv: Optional[List[str]] = None):
|
|
|
694
695
|
print(f" \033[33m[DRY-RUN]\033[0m Proposed configuration (.tokensafe/oumv.json):")
|
|
695
696
|
print(json.dumps(cfg, indent=4))
|
|
696
697
|
elif created:
|
|
698
|
+
mutate_enabled = cfg.get("permissions", {}).get("mutate", True)
|
|
699
|
+
policy = (
|
|
700
|
+
"\033[32menabled out-of-the-box (OCC + syntax guard + backups)\033[0m"
|
|
701
|
+
if mutate_enabled
|
|
702
|
+
else "\033[33mread-only (mutate: false)\033[0m"
|
|
703
|
+
)
|
|
697
704
|
print(f" ✔ Generated OUMV config: \033[1m{conf_file}\033[0m")
|
|
698
|
-
print(f" ✔ Mutation policy:
|
|
705
|
+
print(f" ✔ Mutation policy: {policy}")
|
|
699
706
|
print(f" ✔ Profiles enabled: {', '.join(cfg.get('oumv', {}).get('profiles', []))}")
|
|
700
707
|
print("\n Project is now retrofitted for OUMV. AI coding agents can inspect components and endpoints.\n")
|
|
701
708
|
else:
|
|
@@ -734,6 +741,55 @@ def main(argv: Optional[List[str]] = None):
|
|
|
734
741
|
print(f" Backend Runtime: {status['backend'].get('status', 'OK')} ({status['backend'].get('name', 'N/A')})")
|
|
735
742
|
print(f" Workspace: {status.get('workspace')}\n")
|
|
736
743
|
|
|
744
|
+
elif command == "dev":
|
|
745
|
+
from src.retrofit import resolve_zero_footprint_vite_command
|
|
746
|
+
target_dir = os.getcwd()
|
|
747
|
+
port_val: Optional[int] = None
|
|
748
|
+
host_val: Optional[str] = None
|
|
749
|
+
open_browser = False
|
|
750
|
+
unknown_flags: List[str] = []
|
|
751
|
+
i = 1
|
|
752
|
+
while i < len(args):
|
|
753
|
+
a = args[i]
|
|
754
|
+
nxt = args[i + 1] if i + 1 < len(args) else None
|
|
755
|
+
if a.startswith("--port="):
|
|
756
|
+
try:
|
|
757
|
+
port_val = int(a.split("=", 1)[1])
|
|
758
|
+
except ValueError:
|
|
759
|
+
pass
|
|
760
|
+
elif a == "--port":
|
|
761
|
+
if nxt is not None:
|
|
762
|
+
try:
|
|
763
|
+
port_val = int(nxt)
|
|
764
|
+
i += 1
|
|
765
|
+
except ValueError:
|
|
766
|
+
unknown_flags.append(a)
|
|
767
|
+
else:
|
|
768
|
+
unknown_flags.append(a)
|
|
769
|
+
elif a.startswith("--host="):
|
|
770
|
+
host_val = a.split("=", 1)[1]
|
|
771
|
+
elif a == "--host":
|
|
772
|
+
if nxt is not None and not nxt.startswith("-"):
|
|
773
|
+
host_val = nxt
|
|
774
|
+
i += 1
|
|
775
|
+
else:
|
|
776
|
+
host_val = "true"
|
|
777
|
+
elif a == "--open":
|
|
778
|
+
open_browser = True
|
|
779
|
+
elif a.startswith("-"):
|
|
780
|
+
unknown_flags.append(a)
|
|
781
|
+
else:
|
|
782
|
+
target_dir = os.path.abspath(a)
|
|
783
|
+
i += 1
|
|
784
|
+
if unknown_flags:
|
|
785
|
+
print(f"⚠ Ignoring unsupported 'tokensafe dev' flag(s): {' '.join(unknown_flags)}")
|
|
786
|
+
cmd, source = resolve_zero_footprint_vite_command(
|
|
787
|
+
target_dir, port=port_val, host=host_val, open_browser=open_browser
|
|
788
|
+
)
|
|
789
|
+
print(f"⚡ Launching Zero-Footprint Vite+React OUMV server ({source})...")
|
|
790
|
+
proc = subprocess.run(cmd, cwd=target_dir)
|
|
791
|
+
sys.exit(proc.returncode)
|
|
792
|
+
|
|
737
793
|
elif command in ("burn", "burn-monitor"):
|
|
738
794
|
from src.burn_monitor import collect_live_burn_snapshot, evaluate_burn_warnings, is_zai_peak_hour
|
|
739
795
|
from src.transcript_analyzer import discover_transcript_paths, analyze_transcript, render_transcripts_report
|