tokensafe 4.7.0 → 4.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "4.7.0",
2
+ "version": "4.7.2",
3
3
  "name": "tokensafe",
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
  "author": {
package/README.md CHANGED
@@ -233,6 +233,27 @@ Full matrix and details: [docs/OUMV.md](docs/OUMV.md).
233
233
 
234
234
  ## Benchmarks
235
235
 
236
+ ### Measured agent matrix (Go, DeepSeek — 3 tasks × 5 runs × 3 arms)
237
+
238
+ Real 12-assertion oracle re-run after every step; tokens and cost from the provider's `usage`
239
+ payload. `baseline` = file/search/command tools, `tokensafe` = this product's MCP server
240
+ (`scoped_search` → `smart_read_file` → `apply_edits` with inline `verify="auto"`), `oumv` = the
241
+ OUMV protocol runtime. All three arms solve every session.
242
+
243
+ | Arm | Solved | Mean steps | Mean input | Mean output | Cost/run |
244
+ | :--- | ---: | ---: | ---: | ---: | ---: |
245
+ | `baseline` | 15/15 | 4.5 | 19,538 | 1,599 | $0.0035 |
246
+ | `tokensafe` | 15/15 | 4.7 | 17,616 | **750** | **$0.0025** |
247
+ | `oumv` | 15/15 | 4.3 | **12,323** | 1,735 | $0.0032 |
248
+
249
+ **vs baseline: −9.8% input tokens, −53.1% output tokens, −28.7% cost.** The output column is
250
+ where the product's advantage is structural: `apply_edits` sends the hunk and its target
251
+ snippet, so a one-line fix never resends the file — the other arms reread and rewrite whole
252
+ files. Full method, per-task table, artifacts and limits (including the ±5% run-to-run noise at
253
+ this sample size): [`OUMV_AGENT_MATRIX_V4.md`](https://github.com/tokensafe-dev/tokensafe-backend/blob/main/go/benchmark/OUMV_AGENT_MATRIX_V4.md)
254
+ in the backend repo, generated from the run JSON by
255
+ `go/benchmark/render_agent_matrix.py`.
256
+
236
257
  ### Agent Usability Benchmarks (AUB) — Full-Stack Agent Velocity
237
258
 
238
259
  > ⚠️ **Simulated, not measured.** These AER figures are computed from fixture traces in the
@@ -593,6 +614,7 @@ tokensafe tests
593
614
  - Contributing: [CONTRIBUTING.md](CONTRIBUTING.md)
594
615
  - Security policy and vulnerability reporting: [SECURITY.md](SECURITY.md)
595
616
  - Metrics and honesty contract: [METRICS.md](METRICS.md)
617
+ - Trademark policy and certification mark rules: [TRADEMARK.md](TRADEMARK.md)
596
618
 
597
619
  Apache-2.0 for versions 4.7.0 and newer. Versions up to and including 4.6.4 were released under MIT and remain MIT forever — that grant cannot be withdrawn, and those tags stay forkable.
598
620
 
@@ -74,12 +74,21 @@ def handle(event: str, payload: dict, agent: str = AGENT) -> dict:
74
74
  except Exception:
75
75
  pass
76
76
  # Routing brief: which stack is worked through OUMV vs TokenSafe tools.
77
+ # Hosts that report several roots get all of them classified, not just cwd.
77
78
  try:
78
79
  from src.paths import is_project_root as _is_project_root
79
- from src.session_brief import build_workspace_brief
80
+ from src.session_brief import (
81
+ build_workspace_brief,
82
+ workspace_roots_from_env,
83
+ workspace_roots_from_payload,
84
+ )
80
85
  cwd_for_brief = str(payload.get("cwd") or os.getcwd())
81
86
  if _is_project_root(cwd_for_brief):
82
- routing = build_workspace_brief(cwd_for_brief, include_live=True)
87
+ routing = build_workspace_brief(
88
+ cwd_for_brief,
89
+ include_live=True,
90
+ extra_workspaces=workspace_roots_from_payload(payload) + workspace_roots_from_env(),
91
+ )
83
92
  if routing:
84
93
  extra = f"{extra}\n\n{routing}"
85
94
  except Exception:
@@ -147,17 +156,10 @@ def handle(event: str, payload: dict, agent: str = AGENT) -> dict:
147
156
  )
148
157
 
149
158
  transcript_path = str(payload.get("transcript_path") or "")
150
- # Routing brief: which stack is worked through OUMV vs TokenSafe tools.
151
- try:
152
- from src.paths import is_project_root as _is_project_root
153
- from src.session_brief import build_workspace_brief
154
- cwd_for_brief = str(payload.get("cwd") or os.getcwd())
155
- if _is_project_root(cwd_for_brief):
156
- routing = build_workspace_brief(cwd_for_brief, include_live=True)
157
- if routing:
158
- extra = f"{extra}\n\n{routing}"
159
- except Exception:
160
- pass
159
+ # Routing brief is a session-level injection (SessionStart + MCP
160
+ # instructions). The per-turn copy that used to live here wrote to an
161
+ # undefined `extra` and was swallowed by its own except: reviving it
162
+ # would re-send ~1 KB on every prompt, so it stays out.
161
163
  try:
162
164
  from src.burn_monitor import get_burn_warnings
163
165
  burn_warn = get_burn_warnings(
@@ -55,12 +55,21 @@ def handle(event: str, payload: dict) -> dict:
55
55
  extra = f"{extra}\n\n{guard}"
56
56
  except Exception:
57
57
  pass
58
+ # Routing brief: every open folder is classified, not only cwd.
58
59
  try:
59
60
  from src.paths import is_project_root as _is_project_root
60
- from src.session_brief import build_workspace_brief
61
+ from src.session_brief import (
62
+ build_workspace_brief,
63
+ workspace_roots_from_env,
64
+ workspace_roots_from_payload,
65
+ )
61
66
  kimi_cwd = str(payload.get("cwd") or os.getcwd())
62
67
  if _is_project_root(kimi_cwd):
63
- routing = build_workspace_brief(kimi_cwd, include_live=True)
68
+ routing = build_workspace_brief(
69
+ kimi_cwd,
70
+ include_live=True,
71
+ extra_workspaces=workspace_roots_from_payload(payload) + workspace_roots_from_env(),
72
+ )
64
73
  if routing:
65
74
  extra = f"{extra}\n\n{routing}"
66
75
  except Exception:
@@ -126,16 +135,9 @@ def handle(event: str, payload: dict) -> dict:
126
135
  f"(TokenSafe: compacted ~{meta['saved_tokens']} prompt tokens, "
127
136
  f"-{meta.get('reduction_pct', 0)}% — original intent preserved.)"
128
137
  )
129
- try:
130
- from src.paths import is_project_root as _is_project_root
131
- from src.session_brief import build_workspace_brief
132
- kimi_cwd = str(payload.get("cwd") or os.getcwd())
133
- if _is_project_root(kimi_cwd):
134
- routing = build_workspace_brief(kimi_cwd, include_live=True)
135
- if routing:
136
- extra = f"{extra}\n\n{routing}"
137
- except Exception:
138
- pass
138
+ # Routing brief is session-scoped (SessionStart + MCP instructions); the
139
+ # per-turn copy here targeted an undefined `extra` and died in its own
140
+ # except. It stays dead: re-sending ~1 KB every prompt is pure tax.
139
141
  try:
140
142
  from src.burn_monitor import get_burn_warnings
141
143
  burn_warn = get_burn_warnings(
@@ -123,9 +123,15 @@ def main():
123
123
  except Exception:
124
124
  pass
125
125
  # Routing brief: what goes through OUMV, what goes through TokenSafe tools.
126
+ # Every open folder is routed: the first path is the session root, the
127
+ # rest are additional working directories the agent may edit.
126
128
  try:
127
- from src.session_brief import build_workspace_brief
128
- routing = build_workspace_brief(workspace_root, include_live=True)
129
+ from src.session_brief import build_workspace_brief, workspace_roots_from_env
130
+ routing = build_workspace_brief(
131
+ workspace_root,
132
+ include_live=True,
133
+ extra_workspaces=workspace_paths[1:] + workspace_roots_from_env(),
134
+ )
129
135
  if routing:
130
136
  extra.append(routing)
131
137
  except Exception:
package/kimi.plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokensafe",
3
- "version": "4.7.0",
3
+ "version": "4.7.2",
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": "Apache-2.0",
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "mcpName": "dev.tokensafe/tokensafe",
4
- "version": "4.7.0",
4
+ "version": "4.7.2",
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.7.0",
4
+ "version": "4.7.2",
5
5
  "license": "Apache-2.0",
6
6
  "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.",
7
7
  "logo": "assets/logo.png",
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` — 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`).
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`). **Multi-root sessions**: the routing brief is classified per workspace root — a verdict for one repo NEVER applies to another. Before editing a repo outside the roots listed in the brief, call `tokensafe:oumv(action="status", workspace_dir="<that repo>")`; never conclude "OUMV is unavailable" from a single-root brief.
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.7.0",
6
+ "version": "4.7.2",
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.7.0",
26
+ "version": "4.7.2",
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.7.0",
42
+ "version": "4.7.2",
43
43
  "runtimeHint": "uvx",
44
44
  "transport": {
45
45
  "type": "stdio"
@@ -45,7 +45,8 @@ TOKENSAFE_DIRECTIVES = (
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
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
+ "• 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).\n"
49
+ "• Multi-Root Sessions: the OUMV routing brief is classified PER workspace root (hosts that report several folders get every root listed). A single-root verdict never describes another repo — before editing a repo outside the listed roots, call 'oumv' with workspace_dir='<that repo>'; never conclude 'OUMV is unavailable' from one root's line."
49
50
  )
50
51
 
51
52
  # High-precision deny patterns: secrets and irreversible destruction only.
@@ -25,6 +25,11 @@ class AgentFirewall:
25
25
  _PRUNE_INTERVAL = 3600.0 # amortized hourly prune of the persistent layer
26
26
  _PRUNE_KEEP = 500
27
27
  _last_prune = 0.0
28
+ # Content this process has actually delivered. The cache is keyed by session_id,
29
+ # and host session ids like "mcp:<client>" outlive one process — so a DB hit alone
30
+ # does not mean the caller already has the bytes in context, and saying "reused
31
+ # session read" when it doesn't is how an agent talks itself out of a needed read.
32
+ _EMITTED_IN_PROCESS = set()
28
33
 
29
34
  @classmethod
30
35
  def _ensure_table(cls, tracker: MetricsTracker):
@@ -189,7 +194,14 @@ class AgentFirewall:
189
194
  )
190
195
  opt_tokens = count_tokens(payload)
191
196
  else:
192
- scope_label = "Persistent cache" if hit_scope == "persistent" else "Reused session read"
197
+ emitted_key = (abs_path, symbol_key)
198
+ if hit_scope == "persistent":
199
+ scope_label = "Persistent cache"
200
+ elif emitted_key in cls._EMITTED_IN_PROCESS:
201
+ scope_label = "Reused session read"
202
+ else:
203
+ scope_label = "Cached read (same file, unchanged on disk)"
204
+ cls._EMITTED_IN_PROCESS.add(emitted_key)
193
205
  sym_label = f"::{symbol_key}" if symbol_key else ""
194
206
  # Static deterministic header (no changing hit counters that bust LLM prefix KV-cache)
195
207
  header = (
@@ -251,6 +263,9 @@ class AgentFirewall:
251
263
  tokens = count_tokens(content)
252
264
  now = int(time.time())
253
265
  content_hash = cls._file_content_hash(abs_path)
266
+ # record_cache runs right after the caller received this content, so from here
267
+ # on a hit in this process really is a repeat of what the agent already has.
268
+ cls._EMITTED_IN_PROCESS.add((abs_path, symbol_key))
254
269
 
255
270
  def _insert():
256
271
  with tracker._get_connection() as conn:
@@ -291,6 +291,75 @@ def _go_tidy(workspace: str) -> Tuple[bool, str]:
291
291
  return proc.returncode == 0, (proc.stderr or proc.stdout or "").strip()
292
292
 
293
293
 
294
+ _GO_SERVE_PATTERNS = {
295
+ # `r.Run(":8080")` — gin
296
+ "gin": re.compile(r'(?m)^(?P<indent>[ \t]*)(?P<router>[A-Za-z_]\w*)\.Run\((?P<addr>[^()\n]*)\)[ \t]*$'),
297
+ # `http.ListenAndServe(":8080", r)` — chi
298
+ "chi": re.compile(
299
+ r'(?m)^(?P<indent>[ \t]*)http\.ListenAndServe\((?P<addr>[^,()\n]+),\s*(?P<router>[A-Za-z_]\w*)\)[ \t]*$'
300
+ ),
301
+ }
302
+
303
+
304
+ def _go_router_var(source: str, framework: str) -> Optional[str]:
305
+ _, _, anchor_a, anchor_b, _ = _GO_ADAPTERS[framework]
306
+ for anchor in (anchor_a, anchor_b):
307
+ if not anchor:
308
+ continue
309
+ idx = source.find(anchor)
310
+ if idx == -1:
311
+ continue
312
+ line_start = source.rfind("\n", 0, idx) + 1
313
+ line_end = source.find("\n", idx)
314
+ line = source[line_start : line_end if line_end != -1 else len(source)]
315
+ match = re.search(r"([A-Za-z_]\w*)\s*:?=\s*" + re.escape(anchor), line)
316
+ if match:
317
+ return match.group(1)
318
+ return None
319
+
320
+
321
+ def _wrap_go_serve(source: str, framework: str) -> Optional[Tuple[str, str]]:
322
+ """Rewrites a simple serve call to the discovery-announcing wrapper.
323
+
324
+ `r.Run(":8080")` → `oumvgin.AutoMountAndServe(r, ":8080")`, so the §9.2
325
+ descriptor carries the port the kernel actually assigned. Only a one-line call
326
+ with no nested parentheses is rewritten; anything else falls back to a bare
327
+ AutoMount (the user can swap the serve call manually).
328
+ """
329
+ pattern = _GO_SERVE_PATTERNS.get(framework)
330
+ if pattern is None:
331
+ return None
332
+ router_var = _go_router_var(source, framework)
333
+ for match in pattern.finditer(source):
334
+ if router_var and match.group("router") != router_var:
335
+ continue
336
+ alias = _GO_ADAPTERS[framework][0]
337
+ router = match.group("router")
338
+ addr = match.group("addr").strip()
339
+ indent = match.group("indent")
340
+ block = (
341
+ f"{indent}{_MARK_BEGIN}\n"
342
+ f"{indent}if err := {alias}.AutoMountAndServe({router}, {addr}); err != nil {{\n"
343
+ f"{indent}\tlog.Fatal(err)\n"
344
+ f"{indent}}}\n"
345
+ f"{indent}{_MARK_END}\n"
346
+ )
347
+ return source[: match.start()] + block + source[match.end() :], block.strip()
348
+ return None
349
+
350
+
351
+ def _ensure_std_import(source: str, package: str) -> str:
352
+ if re.search(r'^\s*(?:\w+\s+)?"%s"\s*$' % re.escape(package), source, re.M):
353
+ return source
354
+ idx = source.find("import (")
355
+ if idx == -1:
356
+ return source
357
+ line_end = source.find("\n", idx)
358
+ if line_end == -1:
359
+ return source
360
+ return source[: line_end + 1] + f'\t"{package}"\n' + source[line_end + 1 :]
361
+
362
+
294
363
  def apply_go_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
295
364
  """Ensures the module dependency, inserts the AutoMount call, validates with `go build`.
296
365
 
@@ -312,15 +381,21 @@ def apply_go_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
312
381
  return {"status": "already-patched", "entrypoint": path, "framework": framework}
313
382
 
314
383
  anchor = _go_anchor(original, framework)
315
- if anchor is None:
384
+ alias, import_path, _, _, call = _GO_ADAPTERS[framework]
385
+ wrapped = _wrap_go_serve(original, framework)
386
+ if wrapped is None and anchor is None:
316
387
  return {
317
388
  "status": "skipped",
318
389
  "reason": f"could not find router construction ({framework}) in {os.path.relpath(path, workspace)}",
319
390
  }
320
391
 
321
- alias, import_path, _, _, call = _GO_ADAPTERS[framework]
322
- insert = f"\t{_MARK_BEGIN}\n{call}\t{_MARK_END}\n"
323
- patched = original[:anchor] + insert + original[anchor:]
392
+ if wrapped is not None:
393
+ patched, preview = wrapped
394
+ patched = _ensure_std_import(patched, "log")
395
+ else:
396
+ insert = f"\t{_MARK_BEGIN}\n{call}\t{_MARK_END}\n"
397
+ patched = original[:anchor] + insert + original[anchor:]
398
+ preview = insert.strip()
324
399
 
325
400
  import_line = f'\t{alias} "{import_path}"\n'
326
401
  if import_path not in patched:
@@ -335,7 +410,8 @@ def apply_go_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
335
410
  "status": "would-patch",
336
411
  "entrypoint": os.path.relpath(path, workspace),
337
412
  "framework": framework,
338
- "preview": insert.strip(),
413
+ "mode": "serve" if wrapped is not None else "mount",
414
+ "preview": preview,
339
415
  }
340
416
 
341
417
  backup_dir = _inject_dir(workspace)
@@ -369,14 +445,24 @@ def apply_go_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
369
445
  }
370
446
 
371
447
  with open(os.path.join(backup_dir, "manifest.json"), "w", encoding="utf-8") as f:
372
- json.dump({"entrypoint": path, "backup": backup_path, "framework": framework}, f, indent=2)
448
+ json.dump(
449
+ {
450
+ "entrypoint": path,
451
+ "backup": backup_path,
452
+ "framework": framework,
453
+ "mode": "serve" if wrapped is not None else "mount",
454
+ },
455
+ f,
456
+ indent=2,
457
+ )
373
458
 
374
459
  return {
375
460
  "status": "patched",
376
461
  "entrypoint": os.path.relpath(path, workspace),
377
462
  "framework": framework,
463
+ "mode": "serve" if wrapped is not None else "mount",
378
464
  "backup": backup_path,
379
- "line": call.strip(),
465
+ "line": (preview.splitlines()[1].strip() if wrapped is not None else call.strip()),
380
466
  }
381
467
 
382
468
 
@@ -23,6 +23,7 @@ Key capabilities:
23
23
  import os
24
24
  import re
25
25
  import stat
26
+ import sys
26
27
  import difflib
27
28
  import shlex
28
29
  import subprocess
@@ -309,7 +310,17 @@ def _apply_hunk_to_text(
309
310
  return None, f"Target not found in lines {s_idx+1}..{e_idx}: {hint}"
310
311
  count = sub_text.count(match_target)
311
312
  if count > 1 and not replace_all:
312
- return None, f"Target occurs {count} times within lines {s_idx+1}..{e_idx}. Specify replace_all=True or narrow the range."
313
+ # Report where: the caller just narrowed to a window and needs the exact
314
+ # sub-range (or a longer unique snippet) to finish the edit in one retry.
315
+ occ, scan = [], 0
316
+ while len(occ) < 5:
317
+ pos = sub_text.find(match_target, scan)
318
+ if pos < 0:
319
+ break
320
+ occ.append(str(s_idx + sub_text.count("\n", 0, pos) + 1))
321
+ scan = pos + 1
322
+ locs = f" (near lines {', '.join(occ)})" if occ else ""
323
+ return None, f"Target occurs {count} times within lines {s_idx+1}..{e_idx}{locs}. Specify replace_all=True or narrow the range."
313
324
  prepared_replacement = _normalize_eol(replacement, nl)
314
325
  new_sub = sub_text.replace(match_target, prepared_replacement) if replace_all else sub_text.replace(match_target, prepared_replacement, 1)
315
326
  new_lines = lines[:s_idx] + [new_sub] + lines[e_idx:]
@@ -335,6 +346,60 @@ def _apply_hunk_to_text(
335
346
  return new_content, None
336
347
 
337
348
 
349
+ def detect_verify_command(base_dir: str, files: Optional[List[str]] = None) -> Optional[List[str]]:
350
+ """The project's own test command, for `apply_edits(verify="auto")`.
351
+
352
+ Only commands the project already declares are used — never a guess about which
353
+ files are tests — and only runner/flag shapes that `validate_verify_command`
354
+ accepts, so a resolved command can never come back blocked. Returning None is a normal
355
+ outcome: the caller then says "applied unverified" instead of inventing a verdict.
356
+
357
+ `files` (the paths being edited) narrows the run to the edited packages: an
358
+ unscoped `go test ./...` in a real module outlives the MCP tool timeout and can be
359
+ red on unrelated pre-existing failures, which would roll back a good edit.
360
+ """
361
+ def has(name: str) -> bool:
362
+ return os.path.exists(os.path.join(base_dir, name))
363
+
364
+ if has("go.mod"):
365
+ pkgs: List[str] = []
366
+ for f in files or []:
367
+ abs_f = os.path.abspath(os.path.join(base_dir, f))
368
+ rel = os.path.relpath(abs_f, base_dir).replace("\\", "/")
369
+ if rel.startswith(".."):
370
+ continue
371
+ pkg = os.path.dirname(rel) or "."
372
+ pkg = "." if pkg == "." else "./" + pkg
373
+ if pkg not in pkgs:
374
+ pkgs.append(pkg)
375
+ return ["go", "test"] + (pkgs or ["./..."])
376
+ if has("Cargo.toml"):
377
+ return ["cargo", "test", "--quiet"]
378
+ pkg = os.path.join(base_dir, "package.json")
379
+ if os.path.exists(pkg):
380
+ try:
381
+ import json as _json
382
+ with open(pkg, "r", encoding="utf-8") as f:
383
+ scripts = (_json.load(f) or {}).get("scripts") or {}
384
+ if isinstance(scripts, dict) and scripts.get("test"):
385
+ return ["npm", "test", "--silent"]
386
+ except (OSError, ValueError):
387
+ pass
388
+ py_files = []
389
+ for f in files or []:
390
+ if not str(f).endswith(".py"):
391
+ continue
392
+ rel = os.path.relpath(os.path.abspath(os.path.join(base_dir, f)), base_dir).replace("\\", "/")
393
+ if not rel.startswith(".."):
394
+ py_files.append(rel)
395
+ for marker in ("pytest.ini", "tox.ini", "pyproject.toml", "setup.cfg", "conftest.py"):
396
+ if has(marker):
397
+ return ["python3", "-m", "pytest", "-q"] + py_files
398
+ if os.path.isdir(os.path.join(base_dir, "tests")):
399
+ return ["python3", "-m", "pytest", "-q"] + py_files
400
+ return None
401
+
402
+
338
403
  def execute_batch_edits(
339
404
  edits: List[Dict[str, Any]],
340
405
  best_effort: bool = False,
@@ -374,20 +439,36 @@ def execute_batch_edits(
374
439
  }
375
440
 
376
441
  verified_argv: Optional[List[str]] = None
442
+ auto_verify_note = ""
377
443
  if verify:
378
- verified_argv, verify_err, verify_check = validate_verify_command(str(verify), base_dir=real_base)
379
- if verify_err or not verified_argv:
380
- return {
381
- "success": False,
382
- "blocked": True,
383
- "check_name": verify_check or "VERIFY_COMMAND_BLOCKED",
384
- "error": verify_err or "Verification command blocked.",
385
- "applied_count": 0,
386
- "applied_files": [],
387
- "failed_count": 0,
388
- "failed_files": [],
389
- "dry_run": dry_run,
390
- }
444
+ # verify="auto" -> run the project's own declared test command. This is the
445
+ # tool's strongest convergence lever (edit + verdict in one call) and it was
446
+ # never used because agents had to type the command from the task text.
447
+ if str(verify).strip().lower() == "auto":
448
+ requested = [str(e.get("path") or "") for e in edits if isinstance(e, dict) and e.get("path")]
449
+ verified_argv = detect_verify_command(real_base, files=requested)
450
+ if verified_argv:
451
+ verify = " ".join(verified_argv)
452
+ else:
453
+ auto_verify_note = (
454
+ "no declared test command found (go.mod / package.json scripts.test / "
455
+ "pytest config / a tests/ directory)"
456
+ )
457
+ verify = ""
458
+ if verify:
459
+ verified_argv, verify_err, verify_check = validate_verify_command(str(verify), base_dir=real_base)
460
+ if verify_err or not verified_argv:
461
+ return {
462
+ "success": False,
463
+ "blocked": True,
464
+ "check_name": verify_check or "VERIFY_COMMAND_BLOCKED",
465
+ "error": verify_err or "Verification command blocked.",
466
+ "applied_count": 0,
467
+ "applied_files": [],
468
+ "failed_count": 0,
469
+ "failed_files": [],
470
+ "dry_run": dry_run,
471
+ }
391
472
 
392
473
  # Pre-validation & secret check
393
474
  prepared_files: Dict[str, Dict[str, Any]] = {}
@@ -404,7 +485,13 @@ def execute_batch_edits(
404
485
  continue
405
486
 
406
487
  if os.path.isabs(rel_path):
407
- failed_files.append({"path": rel_path, "error": "Absolute paths and traversal outside workspace root are disallowed."})
488
+ failed_files.append({
489
+ "path": rel_path,
490
+ "error": (
491
+ "Absolute paths are disallowed: edit paths are resolved inside one working directory. "
492
+ "Pass 'cwd' (the repo root, absolute) with repo-relative 'path' values instead."
493
+ ),
494
+ })
408
495
  continue
409
496
 
410
497
  abs_path = os.path.normpath(os.path.join(base_dir, rel_path))
@@ -747,6 +834,10 @@ def execute_batch_edits(
747
834
  result["success"] = False
748
835
  _rollback_after_verify_failure()
749
836
 
837
+ if auto_verify_note and applied_files_info and not dry_run:
838
+ # Asked to verify, could not: say so plainly instead of reporting success as a pass.
839
+ result["verify"] = {"command": "auto", "passed": None, "note": auto_verify_note}
840
+
750
841
  if best_effort and applied_files_info:
751
842
  result.setdefault("edits_kept", True)
752
843
 
@@ -77,7 +77,9 @@ class Usage:
77
77
 
78
78
 
79
79
  class BudgetExceeded(RuntimeError):
80
- pass
80
+ def __init__(self, message: str, usage: Optional[Dict[str, Any]] = None):
81
+ super().__init__(message)
82
+ self.usage = usage or {}
81
83
 
82
84
 
83
85
  class DeepSeekClient:
@@ -129,6 +131,7 @@ ToolFn = Callable[..., Any]
129
131
  class StepRecord:
130
132
  index: int
131
133
  tool_calls: List[str] = field(default_factory=list)
134
+ result_chars: List[int] = field(default_factory=list)
132
135
  duration_ms: float = 0.0
133
136
  oracle_passed: Optional[int] = None
134
137
  oracle_failed: List[str] = field(default_factory=list)
@@ -149,6 +152,8 @@ def run_agent(
149
152
  """Runs one tool loop. Returns messages-independent accounting + step log."""
150
153
  usage = Usage()
151
154
  steps: List[StepRecord] = []
155
+ tool_counts: Dict[str, int] = {}
156
+ tool_chars: Dict[str, int] = {}
152
157
  messages: List[Dict[str, Any]] = [
153
158
  {"role": "system", "content": system_prompt},
154
159
  {"role": "user", "content": task_prompt},
@@ -179,10 +184,14 @@ def run_agent(
179
184
  result = fn(**args) if fn else {"error": f"unknown tool {name}"}
180
185
  except Exception as exc: # tool errors are observations, not crashes
181
186
  result = {"error": f"{type(exc).__name__}: {exc}"}
187
+ content = json.dumps(result, ensure_ascii=False)[:6000]
188
+ tool_counts[name] = tool_counts.get(name, 0) + 1
189
+ tool_chars[name] = tool_chars.get(name, 0) + len(content)
190
+ record.result_chars.append(len(content))
182
191
  messages.append({
183
192
  "role": "tool",
184
193
  "tool_call_id": call.get("id", ""),
185
- "content": json.dumps(result, ensure_ascii=False)[:6000],
194
+ "content": content,
186
195
  })
187
196
 
188
197
  if after_step:
@@ -195,7 +204,10 @@ def run_agent(
195
204
  break
196
205
 
197
206
  if usage.usd(client.model) > budget_usd:
198
- raise BudgetExceeded(f"budget ${budget_usd} exceeded at step {index} (${usage.usd(client.model)})")
207
+ raise BudgetExceeded(
208
+ f"budget ${budget_usd} exceeded at step {index} (${usage.usd(client.model)})",
209
+ usage.as_dict(client.model),
210
+ )
199
211
  else:
200
212
  stop_reason = "max_steps"
201
213
 
@@ -206,10 +218,13 @@ def run_agent(
206
218
  "prices_usd_per_mtok": PRICES.get(client.model),
207
219
  "stop_reason": stop_reason,
208
220
  "usage": usage.as_dict(client.model),
221
+ "tool_calls": tool_counts,
222
+ "tool_result_chars": tool_chars,
209
223
  "steps": [
210
224
  {
211
225
  "index": s.index,
212
226
  "tools": s.tool_calls,
227
+ "result_chars": s.result_chars,
213
228
  "oracle_passed": s.oracle_passed,
214
229
  "oracle_failed": s.oracle_failed,
215
230
  "note": s.note,