File size: 11,380 Bytes
fd11263
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d26f22a
fd11263
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d26f22a
fd11263
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d26f22a
fd11263
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d26f22a
fd11263
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d26f22a
fd11263
 
 
 
 
 
 
 
d26f22a
fd11263
 
 
 
 
 
 
d26f22a
fd11263
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d26f22a
fd11263
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d26f22a
fd11263
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d26f22a
fd11263
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
import json
import urllib.parse
from pathlib import Path

import pytest

from agent_evaluation.integrations.opencode import OpenCodeAdapter
from agent_evaluation.config import SkillEvaluationConfig
from agent_evaluation.datasets.models import EvaluationCase
from agent_evaluation.models import SkillBundle
from .support import profile_text


def test_opencode_jsonl_projection_collects_tokens_and_outputs(tmp_path: Path):
    task_root = tmp_path / "case-1" / "run-1"
    output = task_root / "ai-output"
    output.mkdir(parents=True)
    (output / "testpoint-report.yaml").write_text("kind: testpoint_decomposition\n", encoding="utf-8")
    (output / "verification-plan.md").write_text("# Verification plan\n", encoding="utf-8")
    events = task_root / "opencode-events.jsonl"
    rows = [
        {"type": "tool_use", "sessionID": "session-1", "part": {
            "type": "tool", "tool": "bash", "state": {
                "status": "completed", "input": {"command": "head validate.py"}
            }
        }},
        {"type": "tool_use", "sessionID": "session-1", "part": {
            "type": "tool", "tool": "bash", "state": {
                "status": "completed", "input": {"command": "python validate.py output.yaml; echo EXIT=$?"},
                "output": "EXIT=0", "metadata": {"exit": 0}
            }
        }},
        {"type": "step_finish", "sessionID": "session-1", "part": {
            "tokens": {"total": 18, "input": 3, "output": 5, "reasoning": 2,
                       "cache": {"read": 10, "write": 0}}
        }},
        {"type": "text", "sessionID": "session-1", "part": {
            "type": "text", "text": "done"
        }},
    ]
    events.write_text("".join(json.dumps(row) + "\n" for row in rows), encoding="utf-8")
    skill_root = tmp_path / "skill"
    skill_root.mkdir()
    skill_file = skill_root / "SKILL.md"
    skill_file.write_text("---\nname: demo\n---\n", encoding="utf-8")
    skill = SkillBundle.load(skill_file)
    case = EvaluationCase("case-1", "task", {"fixture": {"path": "input.md"}})

    artifact = OpenCodeAdapter(["opencode"])._parse(
        events, case, skill, "run-1", task_root, None
    )

    assert artifact.status == "completed"
    assert artifact.output["final_output"] == "done"
    assert artifact.metadata["token_usage"] == {
        "prompt": 13, "completion": 5, "reasoning": 2, "total": 18
    }
    assert artifact.execution is not None
    assert artifact.trace_ref is not None
    assert artifact.trace_ref.session_id == "session-1"
    assert artifact.output["validation"][0]["exit_code"] == 0
    assert len(artifact.output["validation"]) == 1
    assert events.as_posix() in artifact.artifact_refs
    assert (output / "testpoint-report.yaml").as_posix() in artifact.artifact_refs


def test_validator_command_detection():
    command = "cd /tmp && python3 scripts/validate_doc.py --data out.yaml; echo EXIT=$?"
    assert OpenCodeAdapter._runs_validator(command)
    assert not OpenCodeAdapter._runs_validator("grep validate scripts/validate_doc.py")


@pytest.mark.parametrize(
    "state, expected",
    [
        ({"status": "completed", "metadata": {"exit": 0}}, 0),
        ({"status": "completed", "metadata": {"exit_code": 3}}, 3),
        ({"status": "completed", "output": "validation done; EXIT=4"}, 4),
        ({"status": "completed", "output": "validation done"}, None),
    ],
)
def test_validator_exit_code_uses_explicit_evidence(state, expected):
    assert OpenCodeAdapter._validator_exit_code(state) == expected


def test_validator_exit_metadata_on_tool_part_is_preserved(tmp_path: Path):
    task_root = tmp_path / "case-1" / "run-1"
    (task_root / "ai-output").mkdir(parents=True)
    events = task_root / "events.jsonl"
    events.write_text(json.dumps({
        "type": "tool_use", "sessionID": "session-1", "part": {
            "tool": "bash", "metadata": {"exit": 3}, "state": {
                "status": "completed", "input": {"command": "python validate_doc.py"}
            },
        },
    }) + "\n", encoding="utf-8")
    skill_root = tmp_path / "skill"
    skill_root.mkdir()
    (skill_root / "SKILL.md").write_text("---\nname: demo\n---\n", encoding="utf-8")
    artifact = OpenCodeAdapter(["opencode"])._parse(
        events, EvaluationCase("case-1", "task", {}), SkillBundle.load(skill_root), "run-1", task_root, None
    )
    assert artifact.output["validation"][0]["exit_code"] == 3


@pytest.mark.parametrize("exit_code", [2, 3, 4])
def test_completed_validator_tool_preserves_nonzero_exit_code(tmp_path: Path, exit_code: int):
    task_root = tmp_path / "case-1" / "run-1"
    (task_root / "ai-output").mkdir(parents=True)
    events = task_root / "events.jsonl"
    events.write_text(json.dumps({
        "type": "tool_use", "sessionID": "session-1", "part": {
            "tool": "bash", "state": {
                "status": "completed",
                "input": {"command": "python validate_doc.py"},
                "metadata": {"exit_code": exit_code},
            },
        },
    }) + "\n", encoding="utf-8")
    skill_root = tmp_path / "skill"
    skill_root.mkdir()
    (skill_root / "SKILL.md").write_text("---\nname: demo\n---\n", encoding="utf-8")
    skill = SkillBundle.load(skill_root)
    artifact = OpenCodeAdapter(["opencode"])._parse(
        events, EvaluationCase("case-1", "task", {}), skill, "run-1", task_root, None
    )
    assert artifact.output["validation"][0]["status"] == "completed"
    assert artifact.output["validation"][0]["exit_code"] == exit_code


def test_opencode_adapter_does_not_infer_stage_from_todowrite(tmp_path: Path):
    task_root = tmp_path / "case-1" / "run-1"
    (task_root / "ai-output").mkdir(parents=True)
    events = task_root / "opencode-events.jsonl"
    skill_root = tmp_path / "skill"
    skill_root.mkdir()
    skill_file = skill_root / "SKILL.md"
    skill_file.write_text(
        "---\nname: demo\n---\n## Runtime State Machine\n\n"
        "1. `Stage 1: First`\n2. `Stage 2: Second`\n",
        encoding="utf-8",
    )
    skill = SkillBundle.load(skill_file)
    rows = [{
        "type": "tool_use",
        "part": {"tool": "todowrite", "state": {"status": "completed", "input": {"todos": [
            {"content": "Stage 1: First", "status": "completed"},
            {"content": "Stage 2: Second", "status": "in_progress"},
        ]}}},
    }]
    events.write_text("".join(json.dumps(row) + "\n" for row in rows), encoding="utf-8")

    artifact = OpenCodeAdapter(["opencode"])._parse(
        events, EvaluationCase("case-1", "task", {}), skill, "run-1", task_root, None
    )
    assert "observed_testpoints" not in artifact.metadata


def test_skill_is_staged_inside_task_workspace(tmp_path: Path):
    source = tmp_path / "skill"
    source.mkdir()
    (source / "SKILL.md").write_text("---\nname: demo\n---\nRead refs/foo.md\n", encoding="utf-8")
    (source / "refs").mkdir()
    (source / "refs" / "foo.md").write_text("reference\n", encoding="utf-8")
    skill = SkillBundle.load(source)
    task_root = tmp_path / "run"
    task_root.mkdir()

    entrypoint = OpenCodeAdapter._copy_skill(skill, task_root)

    assert entrypoint == task_root / "input" / "skill" / "SKILL.md"
    assert entrypoint.read_text(encoding="utf-8").startswith("---")
    assert (entrypoint.parent / "refs" / "foo.md").read_text(encoding="utf-8") == "reference\n"


def test_evaluation_profile_is_not_staged_for_the_agent(tmp_path: Path):
    source = tmp_path / "skill"
    source.mkdir()
    (source / "SKILL.md").write_text("---\nname: demo\n---\n", encoding="utf-8")
    (source / "skill.yaml").write_text(profile_text("    execution: []\n    trace:\n      - id: trace_shape\n        params: {}\n"), encoding="utf-8")
    task_root = tmp_path / "run"
    task_root.mkdir()
    entrypoint = OpenCodeAdapter._copy_skill(SkillBundle.load(source), task_root)
    assert not (entrypoint.parent / "skill.yaml").exists()


def test_tool_calls_without_final_output_are_failed(tmp_path: Path):
    task_root = tmp_path / "run"
    (task_root / "ai-output").mkdir(parents=True)
    events = task_root / "events.jsonl"
    events.write_text(json.dumps({
        "type": "step_finish", "sessionID": "session-1",
        "part": {"reason": "tool-calls", "tokens": {}},
    }) + "\n", encoding="utf-8")
    skill_root = tmp_path / "skill"
    skill_root.mkdir()
    (skill_root / "SKILL.md").write_text("---\nname: demo\n---\n", encoding="utf-8")
    skill = SkillBundle.load(skill_root)
    case = EvaluationCase("case-1", "task", {})

    artifact = OpenCodeAdapter(["opencode"])._parse(events, case, skill, "run-1", task_root, None)

    assert artifact.status == "failed"
    assert artifact.metadata["completion_reasons"] == ("tool-calls",)


def test_timeout_projection_keeps_partial_trace(tmp_path: Path):
    task_root = tmp_path / "run"
    (task_root / "ai-output").mkdir(parents=True)
    events = task_root / "events.jsonl"
    events.write_text(json.dumps({
        "type": "text", "sessionID": "session-timeout",
        "part": {"type": "text", "text": "partial"},
    }) + "\n", encoding="utf-8")
    skill_root = tmp_path / "skill"
    skill_root.mkdir()
    (skill_root / "SKILL.md").write_text("---\nname: demo\n---\n", encoding="utf-8")
    skill = SkillBundle.load(skill_root)
    case = EvaluationCase("case-1", "task", {})
    artifact = OpenCodeAdapter(["opencode"])._parse(events, case, skill, "run-1", task_root, None)

    assert artifact.trace_ref is not None
    assert artifact.trace_ref.session_id == "session-timeout"


def test_abort_session_posts_to_attached_server(monkeypatch, tmp_path: Path):
    requests = []

    class Response:
        status = 204

        def __enter__(self):
            return self

        def __exit__(self, *_):
            return False

    def fake_urlopen(request, timeout):
        requests.append((request.full_url, request.get_method(), timeout))
        return Response()

    monkeypatch.setattr(
        "agent_evaluation.integrations.opencode.agent_adapter.urllib.request.urlopen",
        fake_urlopen,
    )
    adapter = OpenCodeAdapter(["opencode"], server_url="http://127.0.0.1:4099")

    assert adapter._abort_session("ses/timeout", tmp_path)
    assert requests == [(
        f"http://127.0.0.1:4099/session/ses%2Ftimeout/abort?directory={urllib.parse.quote(tmp_path.as_posix(), safe='')}",
        "POST",
        5,
    )]


def test_prompt_includes_exact_configured_output_names(tmp_path: Path):
    skill_root = tmp_path / "skill"
    skill_root.mkdir()
    (skill_root / "SKILL.md").write_text("---\nname: demo\n---\n", encoding="utf-8")
    (skill_root / "skill.yaml").write_text(
        profile_text("    execution:\n      - id: expected_files_present\n        params:\n          expected_files: [verification-plan.yaml]\n    trace: []\n"),
        encoding="utf-8",
    )
    skill = SkillBundle.load(skill_root)
    profile = SkillEvaluationConfig.resolve(skill_root)

    prompt = OpenCodeAdapter._prompt(
        EvaluationCase("case-1", "task", {}), skill, profile, tmp_path / "run", None,
        tmp_path / "run" / "input" / "skill" / "SKILL.md",
    )

    assert "verification-plan.yaml" in prompt
    assert "do not add a case ID, prefix, suffix, or directory" in prompt
    assert "explicit eval-events/v1 completion events" in prompt
    assert "do not omit or batch checkpoints" in prompt