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,541 @@
1
+ """React sandbox target for the measured benchmark.
2
+
3
+ Workspace: a throwaway copy of `agent-dom/packages/benchmark` placed *inside* the
4
+ repo (`agent-dom/.bench-tmp-*`) so Node resolves react/tsx from the monorepo's
5
+ node_modules. The agent edits the real React sandbox sources; correctness is the
6
+ 12-assertion TaskManagerOracle executed by `src/bin/oracle-runner.ts` after every
7
+ step.
8
+
9
+ The OUMV arm for this target needs the Vite bridge (`tokensafe dev`), so the first
10
+ React pilot measures the `baseline` arm only — the Go pilot already compares both.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import os
17
+ import shutil
18
+ import subprocess
19
+ import tempfile
20
+ import time
21
+ from pathlib import Path
22
+ from typing import Any, Dict, List, Optional, Tuple
23
+
24
+ from src.bench import tokensafe_mcp
25
+
26
+ REPO_ROOT = Path(__file__).resolve().parents[3]
27
+ AGENT_DOM = REPO_ROOT / "agent-dom"
28
+ PACKAGE = AGENT_DOM / "packages" / "benchmark"
29
+ WRITE_PREFIX = "sandboxes/react-task-manager/src/"
30
+ STORE = f"{WRITE_PREFIX}store.ts"
31
+
32
+ TASKS: Dict[str, Dict[str, Any]] = {
33
+ "search-filter": {
34
+ "symptom": "typing in the search box no longer filters the task list (the query is ignored).",
35
+ "repro": "set the search query to 'milk': the list still shows every task instead of only matching titles/tags.",
36
+ "breaks": [(
37
+ STORE,
38
+ " if (state.searchQuery.trim()) {\n const q = state.searchQuery.toLowerCase();\n const inTitle = task.title.toLowerCase().includes(q);\n const inTags = task.tags?.some((tag) => tag.toLowerCase().includes(q)) ?? false;\n if (!inTitle && !inTags) return false;\n }\n",
39
+ "",
40
+ )],
41
+ },
42
+ "optimistic-rollback": {
43
+ "symptom": "when the background sync fails, the toggled task keeps the optimistic status instead of rolling back.",
44
+ "repro": "toggle a task while the mock backend rejects the sync: the task must return to its previous status and show an error.",
45
+ "breaks": [(
46
+ STORE,
47
+ """ } catch (err: any) {
48
+ this.set({
49
+ tasks: this.state.tasks.map((t) => (t.id === id ? { ...t, status: prior.status } : t)),
50
+ errorMessage: err?.message || 'Optimistic sync failed',
51
+ });
52
+ throw err;
53
+ }""",
54
+ """ } catch (err: any) {
55
+ this.set({ errorMessage: err?.message || 'Optimistic sync failed' });
56
+ throw err;
57
+ }""",
58
+ )],
59
+ },
60
+ "saving-indicator": {
61
+ "symptom": "the save button is never disabled while the request is in flight, so users double-submit.",
62
+ "repro": "click Save once: isSaving must become true for the duration of the request; it stays false.",
63
+ "breaks": [(
64
+ STORE,
65
+ " this.set({ isSaving: true, errorMessage: null, successMessage: null });",
66
+ " this.set({ errorMessage: null, successMessage: null });",
67
+ )],
68
+ },
69
+ }
70
+
71
+
72
+ OUMV_STDIO = AGENT_DOM / "packages" / "vite" / "scripts" / "oumv-stdio.mjs"
73
+
74
+
75
+ class OumvStdio:
76
+ """Newline-delimited JSON-RPC client for the shipped React stdio adapter.
77
+
78
+ The adapter serves the same controller `tokensafe dev` uses; in headless mode
79
+ L0-L3 come from the static AST, which is exactly what an agent gets before a
80
+ browser tab connects. One process per workspace, closed with the workspace.
81
+ """
82
+
83
+ def __init__(self, root: Path):
84
+ self.proc = subprocess.Popen(
85
+ ["node", str(OUMV_STDIO), "--root", str(root)],
86
+ stdin=subprocess.PIPE,
87
+ stdout=subprocess.PIPE,
88
+ stderr=subprocess.PIPE,
89
+ text=True,
90
+ cwd=str(AGENT_DOM),
91
+ )
92
+ self._id = 0
93
+
94
+ def request(self, method: str, params: Dict[str, Any]) -> Any:
95
+ self._id += 1
96
+ payload = {"jsonrpc": "2.0", "id": self._id, "method": method, "params": params}
97
+ try:
98
+ self.proc.stdin.write(json.dumps(payload) + "\n")
99
+ self.proc.stdin.flush()
100
+ line = self.proc.stdout.readline()
101
+ except (BrokenPipeError, ValueError) as exc:
102
+ return {"error": f"OUMV adapter is not running: {exc}"}
103
+ if not line:
104
+ stderr = (self.proc.stderr.read() or "")[-300:] if self.proc.stderr else ""
105
+ return {"error": f"OUMV adapter produced no output: {stderr}"}
106
+ try:
107
+ body = json.loads(line)
108
+ except json.JSONDecodeError:
109
+ return {"error": f"invalid JSON from adapter: {line[:200]}"}
110
+ if body.get("error"):
111
+ return {"error": body["error"]}
112
+ return body.get("result")
113
+
114
+ def close(self) -> None:
115
+ try:
116
+ self.proc.stdin.close()
117
+ except Exception:
118
+ pass
119
+ try:
120
+ self.proc.terminate()
121
+ self.proc.wait(timeout=5)
122
+ except Exception:
123
+ try:
124
+ self.proc.kill()
125
+ except Exception:
126
+ pass
127
+
128
+
129
+ class ReactWorkspace:
130
+ def __init__(self, task_id: str):
131
+ if task_id not in TASKS:
132
+ raise ValueError(f"unknown task {task_id}; valid: {', '.join(TASKS)}")
133
+ self.task_id = task_id
134
+ self._rpc: Optional[OumvStdio] = None
135
+ self._mcp = None
136
+ base = AGENT_DOM / f".bench-tmp-{next(tempfile._get_candidate_names())}"
137
+ self.dir = base / "benchmark"
138
+ base.mkdir(parents=True)
139
+ shutil.copytree(
140
+ PACKAGE,
141
+ self.dir,
142
+ ignore=shutil.ignore_patterns("node_modules", "dist", ".turbo", "*.log"),
143
+ )
144
+ # Reuse the package's installed deps (react, happy-dom, tsx) instead of
145
+ # copying them: the temp dir lives inside the repo, so a symlink is enough.
146
+ if (PACKAGE / "node_modules").is_dir():
147
+ os.symlink(PACKAGE / "node_modules", self.dir / "node_modules")
148
+ for rel, old, new in TASKS[task_id]["breaks"]:
149
+ path = self.dir / rel
150
+ text = path.read_text(encoding="utf-8")
151
+ if old not in text:
152
+ raise RuntimeError(f"break target not found in {rel}")
153
+ path.write_text(text.replace(old, new, 1), encoding="utf-8")
154
+
155
+ # ---- oracle -----------------------------------------------------------
156
+ def oracle(self) -> Tuple[int, List[str], str]:
157
+ proc = subprocess.run(
158
+ ["npx", "tsx", "src/bin/oracle-runner.ts"],
159
+ cwd=str(self.dir),
160
+ capture_output=True,
161
+ text=True,
162
+ timeout=300,
163
+ )
164
+ out = (proc.stdout or "").strip().splitlines()
165
+ for line in reversed(out):
166
+ try:
167
+ payload = json.loads(line)
168
+ except json.JSONDecodeError:
169
+ continue
170
+ return int(payload.get("passed", 0)), list(payload.get("failed", [])), "PASS" if payload.get("passed") == 12 else "FAIL"
171
+ tail = ((proc.stderr or "") + (proc.stdout or "")).strip().splitlines()
172
+ detail = " | ".join(tail[-3:])[:400] if tail else "no output"
173
+ return 0, [], f"RUNNER ERROR: {detail}"
174
+
175
+ # ---- tools ------------------------------------------------------------
176
+ def _resolve(self, rel: str) -> Path:
177
+ candidate = (self.dir / rel).resolve()
178
+ root = self.dir.resolve()
179
+ if candidate != root and root not in candidate.parents:
180
+ raise ValueError(f"path escapes the workspace: {rel}")
181
+ return candidate
182
+
183
+ def list_files(self, path: str = "sandboxes", depth: int = 3) -> Any:
184
+ base = self._resolve(path)
185
+ if not base.exists():
186
+ return {"error": f"no such path: {path}"}
187
+ lines: List[str] = []
188
+ for entry in sorted(base.rglob("*")):
189
+ rel = entry.relative_to(base)
190
+ if len(rel.parts) > max(0, min(int(depth), 4)):
191
+ continue
192
+ lines.append(f"{rel}{'/' if entry.is_dir() else ''}")
193
+ if len(lines) >= 120:
194
+ lines.append("… truncated")
195
+ break
196
+ return {"path": path, "entries": lines}
197
+
198
+ def read_file(self, path: str, start: int = 1, end: int = 180) -> Any:
199
+ target = self._resolve(path)
200
+ if not target.is_file():
201
+ return {"error": f"not a file: {path}"}
202
+ lines = target.read_text(encoding="utf-8", errors="replace").splitlines()
203
+ start = max(1, int(start))
204
+ end = min(len(lines), max(start, int(end)))
205
+ return {
206
+ "path": path,
207
+ "total_lines": len(lines),
208
+ "content": "\n".join(f"{i:>4}: {lines[i-1]}" for i in range(start, end + 1)),
209
+ }
210
+
211
+ def write_file(self, path: str, content: str) -> Any:
212
+ if not path.startswith(WRITE_PREFIX) or not path.endswith((".ts", ".tsx")):
213
+ return {"error": f"writes are limited to {WRITE_PREFIX}**/*.ts(x)"}
214
+ if path.endswith("adapter.ts"):
215
+ return {"error": "the adapter is read-only; edit the component/store"}
216
+ target = self._resolve(path)
217
+ target.parent.mkdir(parents=True, exist_ok=True)
218
+ target.write_text(content, encoding="utf-8")
219
+ return {"ok": True, "path": path, "bytes": len(content.encode())}
220
+
221
+ def run_command(self, cmd: str) -> Any:
222
+ if not cmd.strip().startswith("npx tsx src/bin/oracle-runner.ts"):
223
+ return {"error": "only `npx tsx src/bin/oracle-runner.ts` is allowed"}
224
+ proc = subprocess.run(cmd.split(), cwd=str(self.dir), capture_output=True, text=True, timeout=300)
225
+ return {"exit_code": proc.returncode, "output": ((proc.stdout or "") + (proc.stderr or "")).strip()[-2000:]}
226
+
227
+ def search_files(self, query: str, path: str = "sandboxes", max_hits: int = 40) -> Any:
228
+ """Case-insensitive substring search — the grep a normal agent would have."""
229
+ base = self._resolve(path)
230
+ needle = query.strip().lower()
231
+ if not needle:
232
+ return {"error": "query is required"}
233
+ max_hits = max(1, min(int(max_hits), 100))
234
+ hits: List[str] = []
235
+ for entry in sorted(base.rglob("*")):
236
+ if not entry.is_file() or entry.suffix not in {".ts", ".tsx", ".js", ".jsx", ".json"}:
237
+ continue
238
+ try:
239
+ text = entry.read_text(encoding="utf-8", errors="replace")
240
+ except OSError:
241
+ continue
242
+ for number, line in enumerate(text.splitlines(), 1):
243
+ if needle in line.lower():
244
+ hits.append(f"{entry.relative_to(base)}:{number}: {line.strip()[:160]}")
245
+ if len(hits) >= max_hits:
246
+ return {"query": query, "hits": hits, "truncated": True}
247
+ return {"query": query, "hits": hits, "truncated": False}
248
+
249
+ # ---- OUMV -------------------------------------------------------------
250
+ def oumv(self, method: str, params: Dict[str, Any]) -> Any:
251
+ if self._rpc is None:
252
+ self._rpc = OumvStdio(self.dir)
253
+ return self._rpc.request(method, params)
254
+
255
+ def tokensafe(self, name: str, arguments: Dict[str, Any]) -> Any:
256
+ if self._mcp is None:
257
+ self._mcp = tokensafe_mcp.open_client(self.dir)
258
+ if self._mcp is None:
259
+ return {"error": "TokenSafe MCP is unavailable"}
260
+ return self._mcp.call(name, arguments)
261
+
262
+ def cleanup(self) -> None:
263
+ if self._mcp is not None:
264
+ self._mcp.close()
265
+ self._mcp = None
266
+ if self._rpc is not None:
267
+ self._rpc.close()
268
+ self._rpc = None
269
+ shutil.rmtree(self.dir.parent, ignore_errors=True)
270
+
271
+
272
+ TOOLS: List[Dict[str, Any]] = [
273
+ {
274
+ "type": "function",
275
+ "function": {
276
+ "name": "list_files",
277
+ "description": "List sandbox files (start from 'sandboxes').",
278
+ "parameters": {"type": "object", "properties": {"path": {"type": "string"}, "depth": {"type": "integer"}}},
279
+ },
280
+ },
281
+ {
282
+ "type": "function",
283
+ "function": {
284
+ "name": "read_file",
285
+ "description": "Read a line range of a sandbox file.",
286
+ "parameters": {
287
+ "type": "object",
288
+ "properties": {"path": {"type": "string"}, "start": {"type": "integer"}, "end": {"type": "integer"}},
289
+ "required": ["path"],
290
+ },
291
+ },
292
+ },
293
+ {
294
+ "type": "function",
295
+ "function": {
296
+ "name": "write_file",
297
+ "description": "Replace a sandbox source file (sandboxes/react-task-manager/src/**, not adapter.ts).",
298
+ "parameters": {
299
+ "type": "object",
300
+ "properties": {"path": {"type": "string"}, "content": {"type": "string"}},
301
+ "required": ["path", "content"],
302
+ },
303
+ },
304
+ },
305
+ {
306
+ "type": "function",
307
+ "function": {
308
+ "name": "search_files",
309
+ "description": "Case-insensitive substring search across sandbox sources, returns path:line hits.",
310
+ "parameters": {
311
+ "type": "object",
312
+ "properties": {
313
+ "query": {"type": "string"},
314
+ "path": {"type": "string", "description": "Relative directory, default 'sandboxes'"},
315
+ "max_hits": {"type": "integer", "description": "Default 40, max 100"},
316
+ },
317
+ "required": ["query"],
318
+ },
319
+ },
320
+ },
321
+ {
322
+ "type": "function",
323
+ "function": {
324
+ "name": "run_command",
325
+ "description": "Run the 12-assertion oracle (`npx tsx src/bin/oracle-runner.ts`).",
326
+ "parameters": {"type": "object", "properties": {"cmd": {"type": "string"}}, "required": ["cmd"]},
327
+ },
328
+ },
329
+ ]
330
+
331
+
332
+ def registry(ws: ReactWorkspace, arm: str = "baseline") -> Dict[str, Any]:
333
+ tools: Dict[str, Any] = {
334
+ "list_files": ws.list_files,
335
+ "read_file": ws.read_file,
336
+ "write_file": ws.write_file,
337
+ "search_files": ws.search_files,
338
+ "run_command": ws.run_command,
339
+ }
340
+ if arm == "tokensafe":
341
+ tools.update({
342
+ "ts_smart_read_file": lambda path, symbol="": ws.tokensafe(
343
+ "smart_read_file", {"path": path, **({"symbol": symbol} if symbol else {})}
344
+ ),
345
+ "ts_scoped_search": lambda query, path="sandboxes": ws.tokensafe(
346
+ "scoped_search", {"query": query, "path": path, "max_results": 20}
347
+ ),
348
+ "ts_repo_map": lambda view="graph": ws.tokensafe("repo_map", {"view": view, "project_path": "."}),
349
+ "ts_apply_edits": lambda path, edits, verify="": ws.tokensafe(
350
+ "apply_edits",
351
+ {
352
+ "edits": [{"path": path, "hunks": edits}],
353
+ **({"verify": verify} if verify else {}),
354
+ },
355
+ ),
356
+ })
357
+ if arm == "oumv":
358
+ tools.update({
359
+ "oumv_observe": lambda level, target="": ws.oumv("oumv/observe", {"level": level, "target": target}),
360
+ "oumv_getSource": lambda path, symbol="": ws.oumv("oumv/getSource", {"path": path, "symbol": symbol}),
361
+ "oumv_applyEdit": lambda path, replacement, expectedVersion: ws.oumv(
362
+ "oumv/applyEdit", {"path": path, "replacement": replacement, "expectedVersion": expectedVersion}
363
+ ),
364
+ "oumv_understand": lambda query, target: ws.oumv("oumv/understand", {"query": query, "target": target}),
365
+ })
366
+ return tools
367
+
368
+
369
+ TOKENSAFE_TOOLS: List[Dict[str, Any]] = TOOLS + [
370
+ {
371
+ "type": "function",
372
+ "function": {
373
+ "name": "ts_smart_read_file",
374
+ "description": "TokenSafe AST-skeleton reader: a compact symbol view of one 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 sandbox.",
387
+ "parameters": {
388
+ "type": "object",
389
+ "properties": {"query": {"type": "string"}, "path": {"type": "string"}},
390
+ "required": ["query"],
391
+ },
392
+ },
393
+ },
394
+ {
395
+ "type": "function",
396
+ "function": {
397
+ "name": "ts_repo_map",
398
+ "description": "TokenSafe architecture map: high-dependency files and API surface.",
399
+ "parameters": {
400
+ "type": "object",
401
+ "properties": {"view": {"type": "string", "enum": ["graph", "api", "tree"]}},
402
+ "required": ["view"],
403
+ },
404
+ },
405
+ },
406
+ {
407
+ "type": "function",
408
+ "function": {
409
+ "name": "ts_apply_edits",
410
+ "description": (
411
+ "TokenSafe surgical editor: replaces exact snippets (hunks of {target, replacement}) "
412
+ "and runs `verify` after the edit, returning a one-line pass/fail."
413
+ ),
414
+ "parameters": {
415
+ "type": "object",
416
+ "properties": {
417
+ "path": {"type": "string"},
418
+ "edits": {
419
+ "type": "array",
420
+ "items": {
421
+ "type": "object",
422
+ "properties": {
423
+ "target": {"type": "string", "description": "Exact snippet to replace"},
424
+ "replacement": {"type": "string", "description": "Replacement snippet"},
425
+ },
426
+ "required": ["target", "replacement"],
427
+ },
428
+ },
429
+ "verify": {"type": "string", "description": "Shell command to run after the edit"},
430
+ },
431
+ "required": ["path", "edits"],
432
+ },
433
+ },
434
+ },
435
+ ]
436
+
437
+ OUMV_TOOLS: List[Dict[str, Any]] = TOOLS + [
438
+ {
439
+ "type": "function",
440
+ "function": {
441
+ "name": "oumv_observe",
442
+ "description": "OUMV observe: L0 pulse, L1 component surface, L2 component contract, L3 source.",
443
+ "parameters": {
444
+ "type": "object",
445
+ "properties": {
446
+ "level": {"type": "string", "enum": ["L0", "L1", "L2", "L3"]},
447
+ "target": {"type": "string", "description": "e.g. 'sandboxes/react-task-manager/src/store.ts'"},
448
+ },
449
+ "required": ["level"],
450
+ },
451
+ },
452
+ },
453
+ {
454
+ "type": "function",
455
+ "function": {
456
+ "name": "oumv_getSource",
457
+ "description": "OUMV source read with the sha256 OCC version token; pass `symbol` to get just that function, method or class.",
458
+ "parameters": {
459
+ "type": "object",
460
+ "properties": {
461
+ "path": {"type": "string"},
462
+ "symbol": {"type": "string"},
463
+ },
464
+ "required": ["path"],
465
+ },
466
+ },
467
+ },
468
+ {
469
+ "type": "function",
470
+ "function": {
471
+ "name": "oumv_applyEdit",
472
+ "description": "OUMV guarded edit: writes the replacement only if `expectedVersion` from getSource matches the file on disk.",
473
+ "parameters": {
474
+ "type": "object",
475
+ "properties": {
476
+ "path": {"type": "string"},
477
+ "replacement": {"type": "string"},
478
+ "expectedVersion": {"type": "string", "description": "sha256 version from getSource"},
479
+ },
480
+ "required": ["path", "replacement", "expectedVersion"],
481
+ },
482
+ },
483
+ },
484
+ {
485
+ "type": "function",
486
+ "function": {
487
+ "name": "oumv_understand",
488
+ "description": "OUMV understand: impact analysis (importers and components affected by a file or symbol).",
489
+ "parameters": {
490
+ "type": "object",
491
+ "properties": {
492
+ "query": {"type": "string", "enum": ["impact", "causality"]},
493
+ "target": {"type": "string"},
494
+ },
495
+ "required": ["query", "target"],
496
+ },
497
+ },
498
+ },
499
+ ]
500
+
501
+
502
+ SYSTEM = (
503
+ "You are a senior React engineer working in a small sandbox. Use search_files to locate code, "
504
+ "read_file to inspect it, write_file to fix the bug, and run_command to run the 12-assertion oracle. "
505
+ "The oracle output is JSON with `passed` and `failed` assertion ids. Tests and adapter.ts are read-only. "
506
+ "Make the smallest correct change and stop as soon as the oracle reports 12."
507
+ )
508
+
509
+ SYSTEM_TOKENSAFE = (
510
+ "You are a senior React engineer working in a small sandbox. The workspace has TokenSafe tools. "
511
+ "Use this loop and stop as soon as the oracle reports 12: (1) ts_scoped_search for the behaviour named "
512
+ "in the repro to get file:line hits; (2) ts_smart_read_file with that path and the identifier from the hit "
513
+ "as `symbol` — it returns the enclosing component/handler body (or a window around the hit) with line numbers; "
514
+ "(3) ts_apply_edits with one hunk {target: the exact snippet, replacement: the fix} plus "
515
+ 'verify="auto" (the declared test command) — it edits and verifies in one call; (4) if verify fails, read the '
516
+ "reported line and repeat (2)-(3). ts_repo_map is for an unfamiliar repository; skip it when the repro "
517
+ "already names the component. Prefer these tools over list_files/read_file. Tests and adapter.ts are "
518
+ "read-only. Do not rewrite whole files."
519
+ )
520
+
521
+ SYSTEM_OUMV = (
522
+ "You are a senior React engineer working in a small sandbox that exposes the OUMV runtime. "
523
+ "Use this loop and stop as soon as the oracle reports 12: (1) search_files ONCE for the behaviour named in "
524
+ "the repro; only call oumv_observe L1 if that finds nothing; (2) oumv_getSource ONCE on the file, WITHOUT "
525
+ "`symbol` — it returns the full bytes and the sha256 OCC version (`symbol` is only for inspecting a single "
526
+ "function or method after you already have the file); (3) oumv_applyEdit with the full fixed file and that "
527
+ "version (it rejects a stale version); (4) run_command to run the oracle. Do not re-read a file you already "
528
+ "have in context, and do not use write_file unless an OUMV tool returns an error. Tests and adapter.ts are "
529
+ "read-only."
530
+ )
531
+
532
+
533
+ def task_prompt(task_id: str) -> str:
534
+ task = TASKS[task_id]
535
+ return (
536
+ f"The task manager has a regression: {task['symptom']}\n"
537
+ f"Repro: {task['repro']}\n"
538
+ "Find the cause and fix the sandbox source. "
539
+ "Verification: `npx tsx src/bin/oracle-runner.ts` must print {\"passed\":12,\"failed\":[]}. "
540
+ "Do not modify the oracle, adapter.ts, or the test harness."
541
+ )