File size: 5,880 Bytes
a642242
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
from __future__ import annotations

import json

from shiftedx_bench.agentic import run_agentic_cases
from shiftedx_bench.util import read_jsonl
from shiftedx_bench.harness import AgentHarness, bare_json_issue, normalize_bare_json, receipt_status


def _call(call_id, name, arguments):
    return {"id": call_id, "type": "function", "function": {"name": name, "arguments": json.dumps(arguments)}}


class ScriptedClient:
    def __init__(self):
        self.responses = [
            {"tool_calls": [
                _call("r1", "read_file", {"path": "/repo/path_utils.py"}),
                _call("r2", "read_file", {"path": "/repo/test_path_utils.py"}),
                _call("r3", "apply_patch", {"path": "/repo/path_utils.py", "patch": "if not path: return '.'"}),
            ]},
            {"tool_calls": [_call("r4", "run_tests", {})]},
            {"content": '```json\n{"status":"passed"}\n```', "tool_calls": []},
            {"content": '{"status":"passed"}', "tool_calls": []},
        ]
        self.index = 0

    def complete(self, payload):
        value = self.responses[self.index]
        self.index += 1
        return {
            "content": value.get("content", ""),
            "tool_calls": value.get("tool_calls", []),
            "prompt_tokens": 10,
            "completion_tokens": 5,
            "wall_s": 1.0,
            "ttft_s": 0.1,
            "end_to_end_tokens_per_second": 5.0,
            "prefill_tokens_per_second": 100.0,
            "decode_tokens_per_second": 50.0,
            "active_memory_bytes": 1024,
            "mtplx_stats": {},
        }


def test_receipt_status_uses_structure_not_error_substrings():
    assert receipt_status('{"status":"healthy","message":"No errors detected","error_budget":"99.9%"}') == "success"
    assert receipt_status('{"error":"index unavailable","retryable":false}') == "failure"
    assert receipt_status("11 passed, 1 failed: backoff") == "failure"
    assert receipt_status("Patch rejected: guard absent") == "failure"


def test_duplicate_is_scoped_to_state_epoch_and_mutation_requires_verification():
    state = AgentHarness("fix the bug", available_tools={"read_file", "apply_patch", "run_tests"})
    args = {"path": "/repo/a.py"}
    state.record("read_file", args, "source")
    prior = state.duplicate("read_file", args)
    assert prior is not None
    state.blocked_result(prior)
    assert state.force_finalize
    assert state.terminal_issue('{"status":"passed"}') is None
    state.record("apply_patch", {"path": "/repo/a.py", "patch": "x"}, "Patch applied.")
    assert state.pending_verification
    assert state.duplicate("read_file", args) is None
    assert "verification" in (state.terminal_issue('{"status":"passed"}') or "")
    assert "Run a verification tool now" in state.render()
    state.record("run_tests", {}, "2 passed")
    assert state.terminal_issue('{"status":"passed"}') is None


def test_failed_post_mutation_verification_returns_to_diagnosis_state():
    state = AgentHarness(
        "repair", available_tools={"read_file", "apply_patch", "run_tests"}
    )
    state.record("apply_patch", {"path": "/repo/a.py", "patch": "first"}, "Patch applied.")
    assert state.pending_verification
    state.record("run_tests", {}, "1 failed")
    assert not state.pending_verification
    assert "run_tests" in state.open_failures
    assert "Run a verification tool now" not in state.render()


def test_successful_receipts_can_project_declared_terminal_schema():
    tests = AgentHarness(
        "repair", required_json_keys=("status", "tests"),
        required_json_types={"status": "string", "tests": "integer"},
    )
    tests.record("run_tests", {}, "14 passed")
    assert tests.project_final("run_tests", "14 passed") == '{"status":"passed","tests":14}'
    health = AgentHarness(
        "health", required_json_keys=("status", "workers"),
        required_json_types={"status": "string", "workers": "integer"},
    )
    result = '{"status":"nominal","workers":8,"message":"ok"}'
    health.record("read_logs", {}, result)
    assert health.project_final("read_logs", result) == '{"status":"nominal","workers":8}'


def test_bare_json_contract_rejects_fences_and_non_objects():
    assert bare_json_issue('{"ok":true}') is None
    assert bare_json_issue('```json\n{"ok":true}\n```') is not None
    assert bare_json_issue("[]") is not None
    assert bare_json_issue('{"nested":{"ok":true}}', ("ok",)) is not None
    assert bare_json_issue('{"build":"1842"}', ("build",), {"build": "integer"}) is not None
    assert bare_json_issue('{"build":1842}', ("build",), {"build": "integer"}) is None
    assert normalize_bare_json('```json\n{"ok":true}\n```') == ('{"ok":true}', True)


def test_failed_verification_blocks_unbounded_investigation():
    state = AgentHarness(
        "repair", available_tools={"run_tests", "file_search", "read_file", "apply_patch"}
    )
    state.record("run_tests", {}, "1 failed")
    state.record("file_search", {"query": "bug"}, "/repo/a.py")
    state.record("read_file", {"path": "/repo/a.py"}, "source")
    state.record("read_file", {"path": "/repo/test_a.py"}, "tests")
    assert state.stalled_result("file_search") is not None
    assert "mutation tool" in state.render()


def test_shiftedx_harness_profile_repairs_format_without_hidden_oracle(tmp_path):
    output = tmp_path / "agentic.jsonl"
    run_agentic_cases(
        client=ScriptedClient(), model="test", output_path=output,
        variant_label="shiftedx-harness", limit=1, control_profile="shiftedx-harness-v1",
    )
    row = read_jsonl(output)[0]
    assert row["passed"]
    assert row["telemetry"]["terminal_correction_count"] == 0
    assert row["telemetry"]["format_normalization_count"] == 1
    assert row["telemetry"]["dispatched_tool_call_count"] == 4
    assert row["metadata"]["agentic_control_profile"] == "shiftedx-harness-v1"