tokensafe 4.6.4 → 4.7.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.
Files changed (44) hide show
  1. package/.codex-plugin/plugin.json +2 -2
  2. package/LICENSE +202 -21
  3. package/README.md +30 -4
  4. package/hooks/claude_code_hook.py +17 -15
  5. package/hooks/kimi_hook.py +14 -12
  6. package/hooks/pre_invocation.py +7 -12
  7. package/hooks/session_start.py +8 -2
  8. package/kimi.plugin.json +2 -2
  9. package/package.json +2 -2
  10. package/plugin.json +2 -1
  11. package/rules/AGENTS.md +1 -1
  12. package/server.json +3 -3
  13. package/src/acp/__init__.py +15 -0
  14. package/src/acp/server.py +328 -0
  15. package/src/adapter_core.py +2 -1
  16. package/src/agent/__init__.py +11 -0
  17. package/src/agent/context.py +99 -0
  18. package/src/agent/loop.py +385 -0
  19. package/src/agent/pricing.py +77 -0
  20. package/src/agent/providers.py +486 -0
  21. package/src/agent/tools.py +98 -0
  22. package/src/agent_firewall.py +16 -1
  23. package/src/auto_inject.py +93 -7
  24. package/src/batch_editor.py +106 -15
  25. package/src/bench/__init__.py +1 -0
  26. package/src/bench/driver.py +234 -0
  27. package/src/bench/go_target.py +646 -0
  28. package/src/bench/mechanics.py +214 -0
  29. package/src/bench/react_target.py +541 -0
  30. package/src/bench/runner.py +331 -0
  31. package/src/bench/tokensafe_mcp.py +144 -0
  32. package/src/cli.py +156 -0
  33. package/src/history_compactor.py +200 -2
  34. package/src/installer.py +3 -3
  35. package/src/mcp_server.py +510 -237
  36. package/src/paths.py +41 -2
  37. package/src/retrofit.py +27 -5
  38. package/src/scaffold.py +8 -6
  39. package/src/scoped_search.py +67 -5
  40. package/src/session_brief.py +180 -15
  41. package/src/session_context.py +124 -0
  42. package/src/skeletonizer.py +9 -3
  43. package/src/telemetry_sync.py +1 -1
  44. package/src/version_checker.py +1 -1
@@ -0,0 +1,646 @@
1
+ """Go sandbox target for the OUMV benchmark.
2
+
3
+ The workstation copy is a throwaway module containing only what is needed to build
4
+ and evaluate the AUB sandbox. Two arms edit the *same* file:
5
+
6
+ * baseline — the agent gets file/command tools only;
7
+ * oumv — the same tools plus observe/getSource/verify/impact, served by a
8
+ helper binary that mounts the OUMV runtime over the same handler.
9
+
10
+ The 12-assertion oracle (`go test ./benchmark -run TestGroundTruthOracleVanilla`)
11
+ is the single source of truth for correctness; it runs after every agent step.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import os
18
+ import re
19
+ import shutil
20
+ import subprocess
21
+ import tempfile
22
+ import time
23
+ from pathlib import Path
24
+ from typing import Any, Dict, List, Optional, Tuple
25
+
26
+ from src.bench import tokensafe_mcp
27
+
28
+ REPO_ROOT = Path(__file__).resolve().parents[3]
29
+ GO_ROOT = REPO_ROOT / "tokensafe-backend" / "go"
30
+ COPY_ITEMS = ("go.mod", "go.sum", "tokensafe.go", "pkg", "benchmark", "cmd")
31
+ SANDBOX_FILE = "benchmark/sandboxes/vanilla_gin/app.go"
32
+ ALLOWED_WRITE_PREFIX = "benchmark/sandboxes/"
33
+ MAX_TOOL_OUTPUT = 4000
34
+
35
+ TASKS: Dict[str, Dict[str, Any]] = {
36
+ "product-create-status": {
37
+ "symptom": "creating a product returns HTTP 200 instead of 201, so the contract test fails.",
38
+ "repro": (
39
+ "POST /api/products with {\"title\":\"USB-C Hub\",\"price\":39.99,\"stock\":15,\"category\":\"electronics\"} "
40
+ "must answer 201; it answers 200. Stateless: one request is enough."
41
+ ),
42
+ "breaks": [(f"{SANDBOX_FILE}", "c.JSON(http.StatusCreated, p)", "c.JSON(http.StatusOK, p)")],
43
+ },
44
+ "order-conflict-status": {
45
+ "symptom": "a duplicate idempotency key returns HTTP 400 instead of 409, so clients retry blindly.",
46
+ "repro": (
47
+ "POST /api/orders with {\"idempotencyKey\":\"order_key_001\",\"customerId\":\"cust_100\","
48
+ "\"items\":[{\"productId\":2,\"quantity\":1}]} twice in the same process: the second call must answer 409 "
49
+ "and answers 400. Stateful: the first call creates the key, so the second call is the one that fails."
50
+ ),
51
+ "breaks": [(
52
+ SANDBOX_FILE,
53
+ 'c.JSON(http.StatusConflict, gin.H{"error": errMsg})',
54
+ 'c.JSON(http.StatusBadRequest, gin.H{"error": errMsg})',
55
+ )],
56
+ },
57
+ "product-validation-status": {
58
+ "symptom": "an invalid product payload is accepted with HTTP 200 instead of being rejected with 422.",
59
+ "repro": (
60
+ "POST /api/products with {\"title\":\"Bad Product\",\"price\":-10,\"stock\":5} must answer 422 (or 400); "
61
+ "it answers 200. Stateless: one request is enough."
62
+ ),
63
+ "breaks": [(
64
+ SANDBOX_FILE,
65
+ # the CreateProduct validation branch (the binding branch alone is not
66
+ # exercised by TC03, which sends a well-formed but invalid payload)
67
+ 'p, err := db.CreateProduct(req)\n\t\tif err != nil {\n\t\t\tc.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()})',
68
+ 'p, err := db.CreateProduct(req)\n\t\tif err != nil {\n\t\t\tc.JSON(http.StatusOK, gin.H{"error": err.Error()})',
69
+ )],
70
+ },
71
+ }
72
+
73
+
74
+ def _run(cmd: List[str], cwd: Path, timeout: float = 240.0, env: Optional[Dict[str, str]] = None) -> subprocess.CompletedProcess:
75
+ return subprocess.run(cmd, cwd=str(cwd), capture_output=True, text=True, timeout=timeout, env=env)
76
+
77
+
78
+ class GoWorkspace:
79
+ def __init__(self, task_id: str):
80
+ if task_id not in TASKS:
81
+ raise ValueError(f"unknown task {task_id}; valid: {', '.join(TASKS)}")
82
+ self.task_id = task_id
83
+ self.dir = Path(tempfile.mkdtemp(prefix=f"oumv-bench-{task_id}-")) / "go"
84
+ self.dir.mkdir(parents=True)
85
+ for item in COPY_ITEMS:
86
+ src = GO_ROOT / item
87
+ dst = self.dir / item
88
+ if src.is_dir():
89
+ shutil.copytree(src, dst)
90
+ else:
91
+ shutil.copy2(src, dst)
92
+ # The runtime must serve the *workspace* code: build the helper inside the
93
+ # copied module and rebuild it when an edit changes the sources, otherwise
94
+ # oumv/verify would keep reporting the pristine app's behaviour.
95
+ self.helper = self.dir.parent / "benchoumv"
96
+ self._helper_built_at = 0.0
97
+ self._mcp = None
98
+ self.break_build()
99
+
100
+ # ---- task setup -------------------------------------------------------
101
+ def break_build(self) -> None:
102
+ for rel, old, new in TASKS[self.task_id]["breaks"]:
103
+ path = self.dir / rel
104
+ text = path.read_text(encoding="utf-8")
105
+ if old not in text:
106
+ raise RuntimeError(f"break target not found in {rel}: {old[:60]}")
107
+ path.write_text(text.replace(old, new, 1), encoding="utf-8")
108
+
109
+ # ---- oracle -----------------------------------------------------------
110
+ def oracle(self) -> Tuple[int, List[str], str]:
111
+ proc = _run(
112
+ ["go", "test", "./benchmark", "-run", "TestGroundTruthOracleVanilla", "-count=1", "-v"],
113
+ cwd=self.dir,
114
+ env={**os.environ, "APP_ENV": "development"},
115
+ )
116
+ output = (proc.stdout or "") + (proc.stderr or "")
117
+ failed = sorted(set(re.findall(r"Assertion (TC\d+_\w+) failed", output)))
118
+ if proc.returncode == 0:
119
+ return 12, [], "PASS"
120
+ if not failed:
121
+ return 0, [], f"BUILD/TEST ERROR: {output.strip().splitlines()[-1][:200] if output.strip() else 'no output'}"
122
+ return 12 - len(failed), failed, "FAIL"
123
+
124
+ # ---- tools ------------------------------------------------------------
125
+ def _resolve(self, rel: str) -> Path:
126
+ candidate = (self.dir / rel).resolve()
127
+ root = self.dir.resolve()
128
+ if candidate != root and root not in candidate.parents:
129
+ raise ValueError(f"path escapes the workspace: {rel}")
130
+ return candidate
131
+
132
+ def list_files(self, path: str = ".", depth: int = 2) -> Any:
133
+ base = self._resolve(path)
134
+ if not base.exists():
135
+ return {"error": f"no such path: {path}"}
136
+ depth = max(0, min(int(depth), 4))
137
+ lines: List[str] = []
138
+ for entry in sorted(base.rglob("*")):
139
+ rel = entry.relative_to(base)
140
+ if len(rel.parts) > depth:
141
+ continue
142
+ if any(part in {".git", "node_modules"} for part in rel.parts):
143
+ continue
144
+ suffix = "/" if entry.is_dir() else ""
145
+ lines.append(f"{rel}{suffix}")
146
+ if len(lines) >= 120:
147
+ lines.append("… truncated")
148
+ break
149
+ return {"path": path, "entries": lines}
150
+
151
+ def read_file(self, path: str, start: int = 1, end: int = 160) -> Any:
152
+ target = self._resolve(path)
153
+ if not target.is_file():
154
+ return {"error": f"not a file: {path}"}
155
+ lines = target.read_text(encoding="utf-8", errors="replace").splitlines()
156
+ start = max(1, int(start))
157
+ end = min(len(lines), max(start, int(end)))
158
+ return {
159
+ "path": path,
160
+ "total_lines": len(lines),
161
+ "start": start,
162
+ "end": end,
163
+ "content": "\n".join(f"{i:>4}: {lines[i - 1]}" for i in range(start, end + 1)),
164
+ }
165
+
166
+ def write_file(self, path: str, content: str) -> Any:
167
+ if not path.startswith(ALLOWED_WRITE_PREFIX) or not path.endswith(".go"):
168
+ return {"error": f"writes are limited to {ALLOWED_WRITE_PREFIX}**/*.go"}
169
+ if path.endswith("_test.go"):
170
+ return {"error": "the oracle tests are read-only"}
171
+ target = self._resolve(path)
172
+ target.parent.mkdir(parents=True, exist_ok=True)
173
+ target.write_text(content, encoding="utf-8")
174
+ return {"ok": True, "path": path, "bytes": len(content.encode())}
175
+
176
+ def run_command(self, cmd: str) -> Any:
177
+ allowed_prefixes = ("go test ./benchmark", "go build ./", "go vet ./benchmark", "go test ./benchmark/")
178
+ if not cmd.strip().startswith(allowed_prefixes):
179
+ return {"error": "only `go test ./benchmark…`, `go build ./…` and `go vet ./benchmark…` are allowed"}
180
+ proc = _run(cmd.split(), cwd=self.dir, env={**os.environ, "APP_ENV": "development"})
181
+ out = ((proc.stdout or "") + (proc.stderr or "")).strip()
182
+ return {"exit_code": proc.returncode, "output": out[-MAX_TOOL_OUTPUT:]}
183
+
184
+ def search_files(self, query: str, path: str = ".", max_hits: int = 40) -> Any:
185
+ """Case-insensitive substring search — the grep a normal agent would have."""
186
+ base = self._resolve(path)
187
+ needle = query.strip().lower()
188
+ if not needle:
189
+ return {"error": "query is required"}
190
+ max_hits = max(1, min(int(max_hits), 100))
191
+ hits: List[str] = []
192
+ for entry in sorted(base.rglob("*")):
193
+ if not entry.is_file() or entry.suffix not in {".go", ".mod", ".sum"}:
194
+ continue
195
+ if any(part in {".git", "vendor"} for part in entry.relative_to(base).parts):
196
+ continue
197
+ try:
198
+ text = entry.read_text(encoding="utf-8", errors="replace")
199
+ except OSError:
200
+ continue
201
+ for number, line in enumerate(text.splitlines(), 1):
202
+ if needle in line.lower():
203
+ hits.append(f"{entry.relative_to(base)}:{number}: {line.strip()[:160]}")
204
+ if len(hits) >= max_hits:
205
+ return {"query": query, "hits": hits, "truncated": True}
206
+ return {"query": query, "hits": hits, "truncated": False}
207
+
208
+ # ---- OUMV -------------------------------------------------------------
209
+ def _newest_source_mtime(self) -> float:
210
+ newest = 0.0
211
+ for path in self.dir.rglob("*.go"):
212
+ try:
213
+ newest = max(newest, path.stat().st_mtime)
214
+ except OSError:
215
+ continue
216
+ return newest
217
+
218
+ def _ensure_helper(self, rebuild: bool) -> Optional[Dict[str, Any]]:
219
+ """Builds the workspace helper; rebuilds only when live code is requested."""
220
+ if self.helper.exists() and (not rebuild or self._helper_built_at >= self._newest_source_mtime()):
221
+ return None
222
+ proc = _run(["go", "build", "-o", str(self.helper), "./cmd/benchoumv"], cwd=self.dir)
223
+ if proc.returncode != 0:
224
+ lines = ((proc.stderr or "") + (proc.stdout or "")).strip().splitlines()
225
+ return {"error": {"code": -32002, "message": "BUILD_ERROR: " + (lines[-1] if lines else "build failed")[:300]}}
226
+ self._helper_built_at = time.time()
227
+ return None
228
+
229
+ def oumv(self, method: str, params: Dict[str, Any]) -> Any:
230
+ # verify/observe/understand must see the edited sources; getSource and L3
231
+ # read files directly, so they can reuse the last good binary.
232
+ live = method in ("oumv/verify", "oumv/understand") or (
233
+ method == "oumv/observe" and str(params.get("level") or "") != "L3"
234
+ )
235
+ failure = self._ensure_helper(rebuild=live)
236
+ if failure:
237
+ return failure
238
+ request = {"jsonrpc": "2.0", "id": 1, "method": method, "params": params}
239
+ proc = subprocess.run(
240
+ [str(self.helper)],
241
+ input=json.dumps(request) + "\n",
242
+ capture_output=True,
243
+ text=True,
244
+ timeout=120,
245
+ cwd=str(self.dir),
246
+ env={**os.environ, "APP_ENV": "development"},
247
+ )
248
+ line = (proc.stdout or "").strip().splitlines()
249
+ if not line:
250
+ return {"error": f"oumv helper produced no output: {(proc.stderr or '')[:200]}"}
251
+ try:
252
+ payload = json.loads(line[-1])
253
+ except json.JSONDecodeError:
254
+ return {"error": f"invalid JSON from helper: {line[-1][:200]}"}
255
+ if payload.get("error"):
256
+ return {"error": payload["error"]}
257
+ return payload.get("result")
258
+
259
+ def tokensafe_tool_schemas(self) -> Optional[List[Dict[str, Any]]]:
260
+ """The product's own `tools/list`, renamed to the arm's stable aliases.
261
+
262
+ `oumv` is excluded: it is a different product surface and would let this arm
263
+ call the protocol runtime the third arm is measuring.
264
+ """
265
+ if self._mcp is None:
266
+ self._mcp = tokensafe_mcp.open_client(self.dir)
267
+ if self._mcp is None:
268
+ return None
269
+ live = self._mcp.tool_schemas(exclude={"oumv"})
270
+ if not live:
271
+ return None
272
+ renamed = []
273
+ for tool in live:
274
+ clone = json.loads(json.dumps(tool))
275
+ real = clone["function"]["name"]
276
+ clone["function"]["name"] = TOKENSAFE_ALIASES.get(real, real)
277
+ renamed.append(clone)
278
+ return renamed
279
+
280
+ def tokensafe(self, name: str, arguments: Dict[str, Any]) -> Any:
281
+ if self._mcp is None:
282
+ self._mcp = tokensafe_mcp.open_client(self.dir)
283
+ if self._mcp is None:
284
+ return {"error": "TokenSafe MCP is unavailable"}
285
+ return self._mcp.call(name, arguments)
286
+
287
+ def cleanup(self) -> None:
288
+ if self._mcp is not None:
289
+ self._mcp.close()
290
+ self._mcp = None
291
+ shutil.rmtree(self.dir.parent, ignore_errors=True)
292
+
293
+
294
+ # ---- tool schemas ---------------------------------------------------------
295
+
296
+ BASE_TOOLS: List[Dict[str, Any]] = [
297
+ {
298
+ "type": "function",
299
+ "function": {
300
+ "name": "list_files",
301
+ "description": "List files under a workspace-relative path.",
302
+ "parameters": {
303
+ "type": "object",
304
+ "properties": {
305
+ "path": {"type": "string", "description": "Relative directory, default '.'"},
306
+ "depth": {"type": "integer", "description": "Max depth 0-4"},
307
+ },
308
+ },
309
+ },
310
+ },
311
+ {
312
+ "type": "function",
313
+ "function": {
314
+ "name": "read_file",
315
+ "description": "Read a line range of a workspace file.",
316
+ "parameters": {
317
+ "type": "object",
318
+ "properties": {
319
+ "path": {"type": "string"},
320
+ "start": {"type": "integer"},
321
+ "end": {"type": "integer"},
322
+ },
323
+ "required": ["path"],
324
+ },
325
+ },
326
+ },
327
+ {
328
+ "type": "function",
329
+ "function": {
330
+ "name": "write_file",
331
+ "description": "Replace a sandbox Go file (benchmark/sandboxes/**/*.go only).",
332
+ "parameters": {
333
+ "type": "object",
334
+ "properties": {"path": {"type": "string"}, "content": {"type": "string"}},
335
+ "required": ["path", "content"],
336
+ },
337
+ },
338
+ },
339
+ {
340
+ "type": "function",
341
+ "function": {
342
+ "name": "search_files",
343
+ "description": "Case-insensitive substring search across workspace .go files, returns path:line hits.",
344
+ "parameters": {
345
+ "type": "object",
346
+ "properties": {
347
+ "query": {"type": "string"},
348
+ "path": {"type": "string", "description": "Relative directory, default '.'"},
349
+ "max_hits": {"type": "integer", "description": "Default 40, max 100"},
350
+ },
351
+ "required": ["query"],
352
+ },
353
+ },
354
+ },
355
+ {
356
+ "type": "function",
357
+ "function": {
358
+ "name": "run_command",
359
+ "description": "Run an allowlisted Go command (go test ./benchmark…, go build ./…, go vet ./benchmark…).",
360
+ "parameters": {
361
+ "type": "object",
362
+ "properties": {"cmd": {"type": "string"}},
363
+ "required": ["cmd"],
364
+ },
365
+ },
366
+ },
367
+ ]
368
+
369
+ TOKENSAFE_TOOLS: List[Dict[str, Any]] = BASE_TOOLS + [
370
+ {
371
+ "type": "function",
372
+ "function": {
373
+ "name": "ts_smart_read_file",
374
+ "description": "TokenSafe AST-skeleton reader: a compact symbol view (~90% fewer tokens than the file).",
375
+ "parameters": {
376
+ "type": "object",
377
+ "properties": {"path": {"type": "string"}, "symbol": {"type": "string"}},
378
+ "required": ["path"],
379
+ },
380
+ },
381
+ },
382
+ {
383
+ "type": "function",
384
+ "function": {
385
+ "name": "ts_scoped_search",
386
+ "description": "TokenSafe scoped search returning file:line hits inside the workspace.",
387
+ "parameters": {
388
+ "type": "object",
389
+ "properties": {
390
+ "query": {"type": "string"},
391
+ "path": {"type": "string", "description": "Relative directory, default '.'"},
392
+ },
393
+ "required": ["query"],
394
+ },
395
+ },
396
+ },
397
+ {
398
+ "type": "function",
399
+ "function": {
400
+ "name": "ts_apply_edits",
401
+ "description": (
402
+ "TokenSafe surgical editor: replaces exact snippets (hunks of {target, replacement}) "
403
+ "and runs `verify` after the edit, returning a one-line pass/fail."
404
+ ),
405
+ "parameters": {
406
+ "type": "object",
407
+ "properties": {
408
+ "path": {"type": "string"},
409
+ "edits": {
410
+ "type": "array",
411
+ "items": {
412
+ "type": "object",
413
+ "properties": {
414
+ "target": {"type": "string", "description": "Exact snippet to replace"},
415
+ "replacement": {"type": "string", "description": "Replacement snippet"},
416
+ },
417
+ "required": ["target", "replacement"],
418
+ },
419
+ },
420
+ "verify": {"type": "string", "description": "Shell command to run after the edit"},
421
+ },
422
+ "required": ["path", "edits"],
423
+ },
424
+ },
425
+ },
426
+ {
427
+ "type": "function",
428
+ "function": {
429
+ "name": "ts_repo_map",
430
+ "description": "TokenSafe architecture map: god nodes / high-dependency files, or an API surface.",
431
+ "parameters": {
432
+ "type": "object",
433
+ "properties": {"view": {"type": "string", "enum": ["graph", "api", "tree"]}},
434
+ "required": ["view"],
435
+ },
436
+ },
437
+ },
438
+ ]
439
+
440
+ OUMV_TOOLS: List[Dict[str, Any]] = BASE_TOOLS + [
441
+ {
442
+ "type": "function",
443
+ "function": {
444
+ "name": "oumv_observe",
445
+ "description": "OUMV observe: L0 pulse, L1 endpoint surface, L2 endpoint contract, L3 source, L4 traces.",
446
+ "parameters": {
447
+ "type": "object",
448
+ "properties": {
449
+ "level": {"type": "string", "enum": ["L0", "L1", "L2", "L3", "L4"]},
450
+ "target": {"type": "string", "description": "e.g. 'GET /api/products' or 'path#symbol'"},
451
+ },
452
+ "required": ["level"],
453
+ },
454
+ },
455
+ },
456
+ {
457
+ "type": "function",
458
+ "function": {
459
+ "name": "oumv_getSource",
460
+ "description": "OUMV source read with the sha256 OCC version token.",
461
+ "parameters": {
462
+ "type": "object",
463
+ "properties": {"path": {"type": "string"}, "symbol": {"type": "string"}},
464
+ "required": ["path"],
465
+ },
466
+ },
467
+ },
468
+ {
469
+ "type": "function",
470
+ "function": {
471
+ "name": "oumv_applyEdit",
472
+ "description": (
473
+ "OUMV guarded edit: applies only if `expectedVersion` matches the file on disk. "
474
+ "mode='symbol' replaces one declaration (cheaper than the whole file)."
475
+ ),
476
+ "parameters": {
477
+ "type": "object",
478
+ "properties": {
479
+ "path": {"type": "string"},
480
+ "replacement": {"type": "string", "description": "New file content, or the new declaration body for mode='symbol'"},
481
+ "expectedVersion": {"type": "string", "description": "sha256 version from oumv_getSource"},
482
+ "mode": {"type": "string", "enum": ["replace", "symbol"]},
483
+ "symbol": {"type": "string", "description": "Declaration to replace when mode='symbol'"},
484
+ },
485
+ "required": ["path", "replacement", "expectedVersion"],
486
+ },
487
+ },
488
+ },
489
+ {
490
+ "type": "function",
491
+ "function": {
492
+ "name": "oumv_verify",
493
+ "description": "OUMV verify: dispatch a request (optionally with a JSON body) in-process and see status/body without starting a server.",
494
+ "parameters": {
495
+ "type": "object",
496
+ "properties": {
497
+ "target": {"type": "string", "description": "e.g. 'GET /api/products' or 'POST /api/orders'"},
498
+ "payload": {"type": "object", "description": "JSON body for POST/PUT targets"},
499
+ },
500
+ "required": ["target"],
501
+ },
502
+ },
503
+ },
504
+ {
505
+ "type": "function",
506
+ "function": {
507
+ "name": "oumv_understand",
508
+ "description": "OUMV understand: impact analysis for an endpoint target.",
509
+ "parameters": {
510
+ "type": "object",
511
+ "properties": {
512
+ "query": {"type": "string", "enum": ["impact", "causality"]},
513
+ "target": {"type": "string"},
514
+ },
515
+ "required": ["query", "target"],
516
+ },
517
+ },
518
+ },
519
+ ]
520
+
521
+
522
+ # The product's tool names -> the arm's stable aliases (the prompts use these).
523
+ TOKENSAFE_ALIASES = {
524
+ "smart_read_file": "ts_smart_read_file",
525
+ "scoped_search": "ts_scoped_search",
526
+ "apply_edits": "ts_apply_edits",
527
+ "repo_map": "ts_repo_map",
528
+ "session_context": "ts_session_context",
529
+ "run_helper": "ts_run_helper",
530
+ }
531
+
532
+
533
+ def build_arm(ws: GoWorkspace, arm: str) -> Tuple[str, List[Dict[str, Any]], Dict[str, Any]]:
534
+ """What one arm sees: prompt, tool schemas and dispatcher, decided in one place.
535
+
536
+ For the `tokensafe` arm the schemas come from the server's own `tools/list` (falling
537
+ back to the hand-written aliases only when the CLI is missing), so the measured arm
538
+ pays the schema cost a real session pays.
539
+ """
540
+ if arm == "tokensafe":
541
+ live = ws.tokensafe_tool_schemas()
542
+ tools = BASE_TOOLS + (live if live else TOKENSAFE_TOOLS[len(BASE_TOOLS):])
543
+ dispatcher: Dict[str, Any] = {
544
+ "list_files": ws.list_files,
545
+ "read_file": ws.read_file,
546
+ "write_file": ws.write_file,
547
+ "search_files": ws.search_files,
548
+ "run_command": ws.run_command,
549
+ }
550
+ reverse = {alias: real for real, alias in TOKENSAFE_ALIASES.items()}
551
+ for tool in tools[len(BASE_TOOLS):]:
552
+ alias = tool["function"]["name"]
553
+ real = reverse.get(alias, alias)
554
+ dispatcher[alias] = (lambda r: lambda **kwargs: ws.tokensafe(r, kwargs))(real)
555
+ return SYSTEM_TOKENSAFE, tools, dispatcher
556
+ if arm == "oumv":
557
+ return SYSTEM_OUMV, OUMV_TOOLS, registry(ws, arm)
558
+ return SYSTEM_BASELINE, BASE_TOOLS, registry(ws, arm)
559
+
560
+
561
+ def registry(ws: GoWorkspace, arm: str) -> Dict[str, Any]:
562
+ tools: Dict[str, Any] = {
563
+ "list_files": ws.list_files,
564
+ "read_file": ws.read_file,
565
+ "write_file": ws.write_file,
566
+ "search_files": ws.search_files,
567
+ "run_command": ws.run_command,
568
+ }
569
+ if arm == "tokensafe":
570
+ tools.update({
571
+ "ts_smart_read_file": lambda path, symbol="": ws.tokensafe(
572
+ "smart_read_file", {"path": path, **({"symbol": symbol} if symbol else {})}
573
+ ),
574
+ "ts_scoped_search": lambda query, path=".": ws.tokensafe(
575
+ "scoped_search", {"query": query, "path": path, "max_results": 20}
576
+ ),
577
+ "ts_apply_edits": lambda path, edits, verify="": ws.tokensafe(
578
+ "apply_edits",
579
+ {
580
+ "edits": [{"path": path, "hunks": edits}],
581
+ **({"verify": verify} if verify else {}),
582
+ },
583
+ ),
584
+ "ts_repo_map": lambda view="graph": ws.tokensafe("repo_map", {"view": view, "project_path": "."}),
585
+ })
586
+ if arm == "oumv":
587
+ tools.update({
588
+ "oumv_observe": lambda level, target="": ws.oumv("oumv/observe", {"level": level, "target": target}),
589
+ "oumv_getSource": lambda path, symbol="": ws.oumv("oumv/getSource", {"path": path, "symbol": symbol}),
590
+ "oumv_applyEdit": lambda path, replacement, expectedVersion, mode="", symbol="": ws.oumv(
591
+ "oumv/applyEdit",
592
+ {
593
+ "path": path,
594
+ "replacement": replacement,
595
+ "expectedVersion": expectedVersion,
596
+ **({"mode": mode} if mode else {}),
597
+ **({"symbol": symbol} if symbol else {}),
598
+ },
599
+ ),
600
+ "oumv_verify": lambda target, payload=None: ws.oumv(
601
+ "oumv/verify", {"target": target, "action": "probe", "payload": payload}
602
+ ),
603
+ "oumv_understand": lambda query, target: ws.oumv("oumv/understand", {"query": query, "target": target}),
604
+ })
605
+ return tools
606
+
607
+
608
+ SYSTEM_BASELINE = (
609
+ "You are a senior Go engineer working in a small Go module. Use search_files to locate code, "
610
+ "read_file to inspect it, write_file to fix it, and run_command to verify. Tests and the oracle are "
611
+ "read-only. Make the smallest correct change; stop as soon as the oracle passes."
612
+ )
613
+ SYSTEM_TOKENSAFE = (
614
+ "You are a senior Go engineer working in a small Go module. The bug report has a repro; "
615
+ "stop as soon as the oracle passes. Loop: (1) ts_scoped_search on the status code or error "
616
+ "text from the repro → file:line hits; (2) ts_smart_read_file(path, symbol=<identifier or "
617
+ "endpoint from the hit>) → the enclosing body or a window, with line numbers; "
618
+ "(3) ts_apply_edits with edits=[{path, hunks:[{target: exact snippet, replacement: fix, "
619
+ 'start_line: the L from (2)}]}] plus verify="auto" → edit and verdict in one call; '
620
+ "(4) if verify fails, fix the reported line and repeat (2)-(3). "
621
+ "Skip ts_repo_map when the repro names the endpoint. Prefer these over list_files/read_file; "
622
+ "never rewrite a whole file."
623
+ )
624
+
625
+ SYSTEM_OUMV = (
626
+ "You are a senior Go engineer working in a small Go module that exposes the OUMV runtime. "
627
+ "The bug report includes a repro; use it to go straight to the right handler instead of guessing payloads. "
628
+ "Use this loop and stop as soon as the oracle passes: (1) oumv_observe L3 with the failing endpoint target "
629
+ "(e.g. \"POST /api/products\") — it returns the handler body, its workspace path and the sha256 OCC version; "
630
+ "(2) oumv_getSource for that path once to get the full file bytes; (3) oumv_applyEdit with the fixed file and "
631
+ "the version from step 1 or 2 (it rejects a stale version); (4) confirm with oumv_verify when the repro is a "
632
+ "single request. When the failure needs state created by earlier requests, run the oracle with run_command "
633
+ "instead — oumv_verify intentionally starts a fresh app per call. Do not call list_files/read_file unless an "
634
+ "OUMV tool returns an error. Tests are read-only."
635
+ )
636
+
637
+
638
+ def task_prompt(task_id: str) -> str:
639
+ task = TASKS[task_id]
640
+ return (
641
+ f"The order API has a regression: {task['symptom']}\n"
642
+ f"Repro: {task['repro']}\n"
643
+ "Find the cause and fix the handler code. "
644
+ "Verification: `go test ./benchmark -run TestGroundTruthOracleVanilla -count=1` must pass all 12 assertions. "
645
+ "Do not modify tests, the oracle, or the database package."
646
+ )