File size: 9,643 Bytes
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
"""Regression checks for the flattened native runtime; no real agents run here."""

import html
import json
import os
from pathlib import Path
import subprocess
import pty
from urllib.parse import unquote
import re

import pytest

from agent_evaluation import cli
from agent_evaluation.backend.config import DEFAULT_DATABASE
from agent_evaluation.models import TaskArtifact, ScoreRecord, score_statistics
from agent_evaluation.reporting.models import ReportData
from agent_evaluation.backend.views import report_data_from_experiment
from agent_evaluation.reporting.render import render_evaluation_document
from .test_render import renderer_example_result


ROOT = Path(__file__).parents[1]


def test_default_database_is_project_local():
    assert DEFAULT_DATABASE == ROOT / "workspace/native/evaluation.sqlite"


@pytest.mark.parametrize("mode", ["headless", "interactive", "evaluate-export"])
def test_cli_modes_share_assembly_and_normalize_cases(mode, tmp_path, monkeypatch):
    captured = []
    monkeypatch.setattr(cli, "DEFAULT_ENV_FILE", tmp_path / "absent.env")
    monkeypatch.delenv("SKILL_EVAL_ENV_FILE", raising=False)
    monkeypatch.setattr(cli, "_profile_requires_trace", lambda args: False)
    monkeypatch.setattr(cli, "OpenCodeExportAdapter", lambda *args, **kwargs: object())
    monkeypatch.setattr(cli, "_make_opencode_adapter", lambda *args, **kwargs: object())
    monkeypatch.setattr(cli, "_run_loop", lambda args, parser, adapter: captured.append(args) or 0)
    args = ["--skill", "skill", "--dataset", "dataset", "--artifacts", "artifacts", "--case-id", "one"]
    if mode == "headless":
        args += ["--case-id", "two", "--limit", "1"]
    else:
        args = [mode, *args, "--case-id", "overridden"]
        if mode == "evaluate-export":
            args += ["--export-json", "export.json"]
    assert cli.main(args) == 0
    assert captured[0].case_ids == (["one", "two"] if mode == "headless" else ["overridden"])
    assert getattr(captured[0], "limit", None) == (1 if mode == "headless" else None)


@pytest.mark.parametrize("mode,option", [("interactive", "--limit"), ("evaluate-export", "--limit"),
                                        ("interactive", "--opencode-auto-approve")])
def test_cli_rejects_mode_inapplicable_options(mode, option, monkeypatch, tmp_path):
    monkeypatch.setattr(cli, "DEFAULT_ENV_FILE", tmp_path / "absent")
    monkeypatch.delenv("SKILL_EVAL_ENV_FILE", raising=False)
    args = [mode, "--skill", "s", "--dataset", "d", "--artifacts", "a", "--case-id", "c", option]
    if option == "--limit":
        args.append("1")
    if mode == "evaluate-export":
        args += ["--export-json", "e"]
    with pytest.raises(SystemExit) as exc:
        cli.main(args)
    assert exc.value.code == 2


def test_shell_credentials_do_not_require_dotenv_but_explicit_file_does(tmp_path, monkeypatch):
    missing = tmp_path / "absent.env"
    monkeypatch.setattr(cli, "DEFAULT_ENV_FILE", missing)
    monkeypatch.delenv("SKILL_EVAL_ENV_FILE", raising=False)
    monkeypatch.setenv("SKILL_EVAL_LLM_MODEL", "shell-model")
    assert cli._load_environment([]) == missing
    assert os.environ["SKILL_EVAL_LLM_MODEL"] == "shell-model"
    monkeypatch.setenv("SKILL_EVAL_ENV_FILE", str(missing))
    with pytest.raises(SystemExit):
        cli._load_environment([])


@pytest.mark.parametrize("script", sorted((ROOT / "scripts").iterdir()), ids=lambda p: p.name)
def test_scripts_cannot_replace_a_sourcing_shell(script):
    result = subprocess.run(["bash", "--noprofile", "--norc", "-c",
                             'source "$1"; status=$?; echo "survived:$status"', "check", str(script)],
                            text=True, capture_output=True)
    assert result.returncode == 0
    assert "survived:2" in result.stdout
    assert "do not source" in result.stderr


def test_example_scripts_forward_overrides_without_worktree_env_fallback():
    for script in (ROOT / "scripts").glob("run-*-example"):
        source = script.read_text()
        assert '"$@"' in source
        assert "git-common-dir" not in source
        assert 'if [[ ! -f "$ENV_FILE" ]]' not in source
        assert "export NO_PROXY=" not in source


@pytest.mark.parametrize("name", ["run-interactive-example", "run-export-example"])
def test_example_forwarding_reaches_cli_process(name, tmp_path):
    capture = tmp_path / "argv"
    executable = tmp_path / "python"
    executable.write_text('#!/bin/bash\nprintf "%s\\n" "$@" > "$CAPTURE"\n')
    executable.chmod(0o700)
    curl = tmp_path / "curl"
    curl.write_text('#!/bin/bash\nprintf "%s\\n" "$@" > "$CURL_CAPTURE"\n')
    curl.chmod(0o700)
    env = {**os.environ, "SKILL_EVAL_PYTHON": str(executable), "EXPORT_JSON": "unused-export",
           "PATH": f"{tmp_path}:{os.environ.get('PATH', '')}", "CAPTURE": str(capture),
           "CURL_CAPTURE": str(tmp_path / "curl-argv"), "SKILL": "/missing/default-skill"}
    env.pop("ENV_FILE", None)
    env.pop("SKILL_EVAL_ENV_FILE", None)
    master, slave = pty.openpty()
    try:
        completed = subprocess.run([str(ROOT / "scripts" / name), "--skill", str(tmp_path),
                                    "--backend-endpoint=http://127.0.0.1:9999", "--llm-timeout", "17"],
                                   stdin=slave, stdout=slave, stderr=subprocess.PIPE, env=env, timeout=10)
        assert completed.returncode == 0, completed.stderr.decode()
    finally:
        os.close(slave)
        os.close(master)
    args = capture.read_text().splitlines()
    assert args[:3] == ["-m", "agent_evaluation.cli", "interactive" if "interactive" in name else "evaluate-export"]
    assert args[-5:] == ["--skill", str(tmp_path), "--backend-endpoint=http://127.0.0.1:9999", "--llm-timeout", "17"]
    assert "--env-file" not in args
    if "interactive" in name:
        curl_args = (tmp_path / "curl-argv").read_text().splitlines()
        assert curl_args[:2] == ["--noproxy", "*"]
        assert curl_args[-1] == "http://127.0.0.1:9999/api/health"


def test_typed_params_and_no_foreign_evaluator_facade_exports():
    from agent_evaluation import evaluators
    from agent_evaluation.evaluators import ExpectedFilesParams
    params = ExpectedFilesParams(("result.md",))
    assert params.expected_files == ("result.md",)
    assert params.to_dict() == {"expected_files": ["result.md"]}
    assert not hasattr(params, "get")
    with pytest.raises(TypeError):
        params["expected_files"]
    assert not hasattr(evaluators, "TraceStore")
    assert not hasattr(evaluators, "SkillEvaluationConfig")


def test_report_memory_and_persisted_score_parity():
    example = renderer_example_result()
    run = TaskArtifact("run", "synthetic-case", "completed", {"final_output": "<text>"})
    memory = ReportData(example.experiment_id, (run,), example.scores, example.inputs,
                        {"name": "native", "experiment_id": example.experiment_id,
                         "metadata": example.backend["metadata"]})
    persisted = report_data_from_experiment(json.loads(json.dumps({
        "id": example.experiment_id, "runs": [run.to_dict()],
        "scores": [s.to_dict() for s in example.scores], "inputs": {},
        "backend_metadata": dict(example.backend["metadata"]),
    })))
    assert score_statistics(memory.scores) == score_statistics(persisted.scores)
    assert [s.to_dict() for s in memory.scores] == [s.to_dict() for s in persisted.scores]
    assert memory.backend["metadata"] == persisted.backend["metadata"]
    assert render_evaluation_document(memory) == render_evaluation_document(persisted)
    document = render_evaluation_document(persisted)
    assert "task-artifact.json" not in document
    assert "synthetic-case" in document and "completed" in document
    assert "Synthetic publication warning" in html.unescape(document)


@pytest.mark.parametrize("score", renderer_example_result().scores)
def test_score_record_owns_flat_audit_roundtrip(score):
    document = json.loads(json.dumps(score.to_dict()))
    assert ScoreRecord.from_dict(document).to_dict() == document


def test_renderer_only_accepts_report_data_and_has_no_writing_interface():
    from agent_evaluation.reporting import render
    assert not hasattr(render, "render_evaluation_report")
    assert not hasattr(ReportData, "from_result")
    assert not hasattr(ReportData, "from_experiment")
    with pytest.raises(TypeError, match="ReportData"):
        render_evaluation_document({"id": "not-a-report"})


@pytest.mark.parametrize("url", ["javascript:alert(1)", "//host/path", "file:///etc/passwd", "/etc/passwd", "x\nfoo", "https://host", "\\\\host"])
def test_report_rejects_unsafe_task_links(url):
    example = renderer_example_result()
    report = ReportData(example.experiment_id, (TaskArtifact("run", "<case>", "completed", {}),),
                        example.scores, example.inputs, example.backend)
    document = render_evaluation_document(report, task_links={"run": url})
    assert "task-artifact.json</a>" not in document
    assert "&lt;case&gt;" in document


def test_static_task_links_resolve_to_written_artifacts(tmp_path):
    from .test_loop import _fixture, _loop
    from agent_evaluation.integrations.simulator import SimulatorAdapter
    skill, dataset = _fixture(tmp_path)
    result = _loop(SimulatorAdapter()).run(skill, dataset, tmp_path / "artifacts", evolve=False)
    index = tmp_path / "artifacts" / result.experiment_id / "report/index.html"
    links = re.findall(r'href="([^"]+task-artifact.json)"', index.read_text())
    assert len(links) == len(result.runs)
    assert all((index.parent / unquote(html.unescape(link))).is_file() for link in links)