from __future__ import annotations import json import uuid from dataclasses import dataclass, field from pathlib import Path from typing import Any, Callable from .api import OpenAIClient from .scoring import score_response from .tools import function_tool from .util import append_jsonl, read_jsonl, sha256_json from .harness import AgentHarness, HARNESS_PROFILE, HARNESS_SYSTEM_SUFFIX, normalize_bare_json READ = function_tool("read_file", {"path": {"type": "string"}}, ["path"]) SEARCH = function_tool("file_search", {"query": {"type": "string"}}, ["query"]) SESSION = function_tool("session_search", {"query": {"type": "string"}}, ["query"]) TESTS = function_tool("run_tests", {}, []) PATCH = function_tool( "apply_patch", { "path": {"type": "string"}, "patch": { "type": "string", "description": "Complete replacement contents for the target file, not a unified diff.", }, }, ["path", "patch"], ) PATCH["function"]["description"] = "Replace one file with complete supplied contents." LOGS = function_tool("read_logs", {"service": {"type": "string"}}, ["service"]) @dataclass class AgentScenario: case_id: str prompt: str tools: list[dict[str, Any]] required_calls: set[str] expected_final: dict[str, Any] dispatch: Callable[[str, dict[str, Any], dict[str, Any]], str] max_turns: int = 8 max_tool_calls: int = 8 final_keys: tuple[str, ...] | None = None final_types: dict[str, str] = field(default_factory=dict) forbidden_calls: set[str] = field(default_factory=set) require_receipt: bool = True family: str = "core" real_repo: bool = False def _bugfix(name: str, args: dict[str, Any], state: dict[str, Any]) -> str: if name == "file_search": return "/repo/path_utils.py\n/repo/test_path_utils.py" if name == "read_file": if str(args.get("path", "")).endswith("test_path_utils.py"): return "assert parent('') == '.'\nassert parent('a/b') == 'a'\n" if str(args.get("path", "")).endswith("path_utils.py"): return ( "def parent(path):\n" " parts = [item for item in path.split('/') if item]\n" " parts.pop()\n" " return '/'.join(parts) or '.'\n" ) return "FileNotFoundError" if name == "apply_patch": patch = str(args.get("patch", "")) state["patched"] = "if" in patch and "path" in patch return "Patch applied." if state["patched"] else "Patch rejected: empty-path guard absent." if name == "run_tests": return "2 passed" if state.get("patched") else "1 failed: IndexError" return "Unknown tool" def _recovery(name: str, args: dict[str, Any], state: dict[str, Any]) -> str: if name == "session_search": return '{"error":"index unavailable","retryable":false}' if name == "file_search": return "/configs/staging/deploy.yaml: endpoint: https://staging.example:7443" if name == "read_file": return "service: atlas\nendpoint: https://staging.example:7443\n" return "Unknown tool" def _false_error(name: str, args: dict[str, Any], state: dict[str, Any]) -> str: if name == "read_logs": return json.dumps({"status": "healthy", "message": "No errors detected", "error_budget": "99.9%"}) return "Unknown tool" def _repair(name: str, args: dict[str, Any], state: dict[str, Any]) -> str: if name == "run_tests": return "12 passed" if state.get("patched") else "11 passed, 1 failed: backoff" if name == "file_search": return "/repo/retry.py\n/repo/test_retry.py" if name == "read_file": path = str(args.get("path", "")) if path == "/repo/retry.py": return "def retry_delays(n): return list(range(1,n+1))" if path == "/repo/test_retry.py": return "assert retry_delays(3)==[1,2,4]" return "FileNotFoundError" if name == "apply_patch": patch = str(args.get("patch", "")) state["patched"] = "2 **" in patch or "2**" in patch or "1 <<" in patch return "Patch applied." if state["patched"] else "Patch does not implement exponential backoff." return "Unknown tool" def _parallel_config(name: str, args: dict[str, Any], state: dict[str, Any]) -> str: if name != "read_file": return "Unknown tool" path = str(args.get("path", "")) if path == "/configs/app.yaml": return "api_version: v3\ntimeout_seconds: 30" if path == "/configs/worker.yaml": return "api_version: v2\ntimeout_seconds: 30" return "FileNotFoundError" def _wrong_path(name: str, args: dict[str, Any], state: dict[str, Any]) -> str: if name == "read_file": path = str(args.get("path", "")) if path == "/repo/config/prod.toml": return "FileNotFoundError" if path == "/repo/configs/prod.toml": return 'database_host = "prod-db"\npool_size = 20' return "FileNotFoundError" if name == "file_search": return "/repo/configs/prod.toml" return "Unknown tool" def scenarios() -> list[AgentScenario]: final = "When complete, return bare JSON only." return [ AgentScenario( "inspect_patch_test", "Fix the empty-path bug in path_utils.parent. Inspect source and tests, patch it, and run tests. " "Finish with bare JSON containing exactly {\"status\":\"passed\"}. " + final, [SEARCH, READ, PATCH, TESTS], {"read_file", "apply_patch", "run_tests"}, {"status": "passed"}, _bugfix, final_keys=("status",), final_types={"status": "string"}, family="inspect_patch_test", ), AgentScenario( "failed_search_recovery", "Find the staging endpoint. Search prior sessions first, recover with repository tools if unavailable, " "and verify the file. Finish with bare JSON containing exactly one key named endpoint. " + final, [SESSION, SEARCH, READ], {"session_search", "file_search", "read_file"}, {"endpoint": "https://staging.example:7443"}, _recovery, max_tool_calls=4, final_keys=("endpoint",), final_types={"endpoint": "string"}, family="failed_search_recovery", ), AgentScenario( "false_error_payload", "Check payments health. Do not retry a successful result whose text merely contains the word error. " "Finish with bare JSON containing exactly the keys status and error_budget. " + final, [LOGS], {"read_logs"}, {"status": "healthy", "error_budget": "99.9%"}, _false_error, max_turns=4, max_tool_calls=1, final_keys=("status", "error_budget"), final_types={"status": "string", "error_budget": "string"}, family="structured_status", ), AgentScenario( "repair_loop", "Run tests, diagnose the backoff failure, make the smallest source fix, rerun tests, and stop only when green. " "Finish with bare JSON containing exactly the keys status and tests: status must be the string " "\"passed\" when green, and tests must be the integer count of passing tests. " + final, [TESTS, SEARCH, READ, PATCH], {"run_tests", "read_file", "apply_patch"}, {"status": "passed", "tests": 12}, _repair, max_tool_calls=7, final_keys=("status", "tests"), final_types={"status": "string", "tests": "integer"}, family="repair_loop", ), AgentScenario( "parallel_config_review", "Read /configs/app.yaml and /configs/worker.yaml, preferably in parallel. Report both API versions. " "Finish with bare JSON containing exactly the keys app_version and worker_version. " + final, [READ], {"read_file"}, {"app_version": "v3", "worker_version": "v2"}, _parallel_config, max_turns=5, max_tool_calls=2, final_keys=("app_version", "worker_version"), final_types={"app_version": "string", "worker_version": "string"}, family="parallel_review", ), AgentScenario( "wrong_path_recovery", "Read /repo/config/prod.toml and report database host and pool size. If missing, locate the real file. " "Finish with bare JSON containing exactly the keys database_host and pool_size. " + final, [READ, SEARCH], {"read_file", "file_search"}, {"database_host": "prod-db", "pool_size": 20}, _wrong_path, max_turns=6, max_tool_calls=3, final_keys=("database_host", "pool_size"), final_types={"database_host": "string", "pool_size": "integer"}, family="wrong_path_recovery", ), ] def scenario_set(name: str) -> list[AgentScenario]: if name == "core": return scenarios() if name == "expanded": from .agentic_expanded import expanded_scenarios return expanded_scenarios() if name == "repo": from .agentic_repo import repo_scenarios return repo_scenarios() raise ValueError(f"Unknown agentic scenario set: {name}") def _arguments(call: dict[str, Any]) -> dict[str, Any]: raw = (call.get("function") or {}).get("arguments", {}) return json.loads(raw) if isinstance(raw, str) else raw def run_agentic_cases( *, client: OpenAIClient, model: str, output_path: Path, request_overrides: dict[str, Any] | None = None, variant_label: str = "default", limit: int | None = None, run_id: str | None = None, control_profile: str = "baseline", agentic_set: str = "core", case_id: str | None = None, ) -> list[dict[str, Any]]: if control_profile not in {"baseline", HARNESS_PROFILE}: raise ValueError(f"Unknown agentic control profile: {control_profile}") rows = [] run_id = run_id or str(uuid.uuid4()) system = ( "You are an autonomous coding agent in a deterministic sandbox. Use supplied tools, never invent " "results, recover from failures, verify completion, and obey the requested final JSON format." ) if control_profile == HARNESS_PROFILE: system += HARNESS_SYSTEM_SUFFIX selected = scenario_set(agentic_set) if case_id is not None: selected = [item for item in selected if item.case_id == case_id] if not selected: raise ValueError(f"Unknown case identifier for {agentic_set}: {case_id}") if limit is not None: selected = selected[:limit] completed = { (row.get("case_id"), row.get("variant")) for row in read_jsonl(output_path) if row.get("schema_version") == "1.0" } for scenario in selected: if (scenario.case_id, variant_label) in completed: continue messages: list[dict[str, Any]] = [ {"role": "system", "content": system}, {"role": "user", "content": scenario.prompt}, ] state: dict[str, Any] = {} harness = ( AgentHarness( scenario.prompt, available_tools={str(tool["function"]["name"]) for tool in scenario.tools}, required_json_keys=scenario.final_keys, required_json_types=scenario.final_types, require_receipt=scenario.require_receipt, ) if control_profile == HARNESS_PROFILE else None ) call_names: list[str] = [] dispatched_call_names: list[str] = [] turn_telemetry: list[dict[str, Any]] = [] response: dict[str, Any] = {} error = None format_normalizations = 0 receipt_projections = 0 for turn_index in range(scenario.max_turns): payload = { "model": model, "messages": messages, "tools": scenario.tools, "tool_choice": "none" if harness is not None and harness.force_finalize else "auto", "temperature": 0, "max_tokens": 1024, } payload.update(request_overrides or {}) response = client.complete(payload) turn_telemetry.append({ "wall_s": response.get("wall_s"), "prompt_tokens": response.get("prompt_tokens"), "completion_tokens": response.get("completion_tokens"), "ttft_s": response.get("ttft_s"), "end_to_end_tokens_per_second": response.get("end_to_end_tokens_per_second"), "prefill_tokens_per_second": response.get("prefill_tokens_per_second"), "decode_tokens_per_second": response.get("decode_tokens_per_second"), "active_memory_bytes": response.get("active_memory_bytes"), "mtplx_stats": response.get("mtplx_stats") or {}, }) calls = response.get("tool_calls") or [] if not calls: if harness is not None: normalized, changed = normalize_bare_json(response.get("content") or "") if changed: response = {**response, "content": normalized} format_normalizations += 1 issue = harness.terminal_issue(response.get("content") or "") if issue and harness.terminal_corrections < 2 and turn_index + 1 < scenario.max_turns: messages.append({"role": "assistant", "content": response.get("content") or ""}) messages.append({"role": "user", "content": harness.correction(issue)}) continue break assistant = {"role": "assistant", "content": response.get("content") or "", "tool_calls": calls} messages.append(assistant) projected_final = None for index, call in enumerate(calls): name = str((call.get("function") or {}).get("name")) call_names.append(name) try: arguments = _arguments(call) except Exception as exc: arguments = {} result = json.dumps({"error": f"argument parsing failure: {exc}"}) else: stalled = harness.stalled_result(name) if harness is not None else None prior = harness.duplicate(name, arguments) if harness is not None and stalled is None else None if stalled is not None: result = stalled elif prior is not None: result = harness.blocked_result(prior) else: budget_count = len(dispatched_call_names) if harness is not None else len(call_names) - 1 if budget_count >= scenario.max_tool_calls: error = "tool-call budget exceeded" break try: result = scenario.dispatch(name, arguments, state) except Exception as exc: result = json.dumps({"error": f"dispatcher failure: {exc}"}) dispatched_call_names.append(name) if harness is not None: harness.record(name, arguments, result) projected_final = harness.project_final(name, result) or projected_final messages.append( { "role": "tool", "tool_call_id": call.get("id") or f"call-{index}", "content": result, } ) if error: break if projected_final is not None: receipt_projections += 1 response = {**response, "content": projected_final, "tool_calls": []} messages.append({"role": "assistant", "content": projected_final}) break if harness is not None: messages.append({"role": "user", "content": harness.render()}) score = score_response("strict_json_subset", scenario.expected_final, response) required_ok = scenario.required_calls.issubset(dispatched_call_names) forbidden_seen = sorted(scenario.forbidden_calls & set(call_names)) passed = score.passed and required_ok and not forbidden_seen and error is None if not required_ok: error = f"missing required calls: {sorted(scenario.required_calls - set(dispatched_call_names))}" elif forbidden_seen: error = f"forbidden calls emitted: {forbidden_seen}" elif error is not None: pass elif not score.passed: error = score.error row = { "schema_version": "1.0", "run_id": run_id, "suite_id": "shiftedx-agentic-v1", "case_id": scenario.case_id, "lane": "agentic", "variant": variant_label, "passed": passed, "score": float(passed), "score_max": 1.0, "error": error, "response": {**response, "transcript": messages}, "telemetry": { "tool_call_count": len(call_names), "tool_calls": call_names, "dispatched_tool_call_count": len(dispatched_call_names), "dispatched_tool_calls": dispatched_call_names, "blocked_duplicate_count": harness.blocked_duplicates if harness is not None else 0, "blocked_stall_count": harness.blocked_stalls if harness is not None else 0, "terminal_correction_count": harness.terminal_corrections if harness is not None else 0, "format_normalization_count": format_normalizations, "receipt_projection_count": receipt_projections, "harness_receipts": ( [item.to_dict() for item in harness.receipts] if harness is not None else [] ), "turns": turn_telemetry, "wall_s": sum(float(item.get("wall_s") or 0) for item in turn_telemetry), "prompt_tokens": sum(int(item.get("prompt_tokens") or 0) for item in turn_telemetry), "completion_tokens": sum(int(item.get("completion_tokens") or 0) for item in turn_telemetry), "ttft_s": next((item.get("ttft_s") for item in turn_telemetry if item.get("ttft_s") is not None), None), }, "metadata": { "max_turns": scenario.max_turns, "max_tool_calls": scenario.max_tool_calls, "agentic_control_profile": control_profile, "agentic_set": agentic_set, "agentic_family": scenario.family, "real_repo": scenario.real_repo, "forbidden_calls": sorted(scenario.forbidden_calls), }, "request_hash": sha256_json({ "messages": messages[:2], "tools": scenario.tools, "agentic_control_profile": control_profile, "agentic_set": agentic_set, }), } append_jsonl(output_path, [row]) rows.append(row) return rows