File size: 28,187 Bytes
966b234
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
from __future__ import annotations

import asyncio
import io
import json
from pathlib import Path
import subprocess
import sys
from types import SimpleNamespace

import pytest

from bench_builder import builder_progress_tools as progress_tools
from bench_builder import program_bench
from bench_builder.harness_plugins import HarnessRunResult, get_harness_plugin


class RecordingService:
    def __init__(self):
        self.calls = []

    def get_progress(self, **kwargs):
        self.calls.append(("get", kwargs))
        return {"snapshot_id": "s0012", "current_version": "v1", "checks": []}

    def update_progress(self, **kwargs):
        self.calls.append(("update", kwargs))
        return {"snapshot_id": "s0013", "progress": {"passed": 3, "total": 10}}


def test_compact_resume_preserves_all_check_states_versions_and_warnings():
    from copy import deepcopy

    payload = {
        "snapshot_id": "s1", "build_version": "old", "current_version": "new",
        "progress": {"passed": 0, "unreportedVersion": True, "warnings": ["stale evidence"]},
        "checks": [{"requirement_id": "r1", "status": "failed", "reason": "collision " * 1000,
                    "evidence": [{"path": "verification/collision.json"}]}],
        "requirements": [{"id": "r1", "description": "required behavior " * 1000}],
        "runtime_checks": [{"requirement_id": "startup", "status": "failed", "reason": "asset missing"}],
        "taxonomy_diagnostics": {"invalid_requirement_ids": ["r1"], "domains": {"agents": {}},
                                 "subdomains": {"agents.navigation": {}}},
        "captures": [{"id": "image"}], "pending_ids": [],
    }
    before = deepcopy(payload)
    service = SimpleNamespace(get_progress=lambda **_: payload)
    adapter = progress_tools.BuilderProgressTools(service)
    summary = adapter.get_progress()
    assert "checks" not in summary and summary["checks_by_status"] == {"failed": ["r1"]}
    assert summary["current_version"] == "new" and summary["build_version"] == "old"
    assert summary["progress"] == before["progress"]
    assert summary["runtime_checks"] == before["runtime_checks"]
    assert summary["taxonomy_diagnostics"]["invalid_requirement_ids"] == ["r1"]
    assert len(json.dumps(summary)) < len(json.dumps(payload)) / 10
    assert payload == before
    for detailed in (adapter.get_progress(detail="full"), adapter.get_progress(requirement_ids=["r1"])):
        assert {key: detailed[key] for key in payload} == before
    with pytest.raises(ValueError, match="detail must"):
        adapter.get_progress(detail="invalid")


def test_actual_mcp_schema_and_batch_calls():
    service = RecordingService()
    server = progress_tools.create_builder_progress_mcp_server(service)
    batch = {
        "request_id": "batch-1", "base_snapshot_id": "s0012", "summary": "Inspected HUD",
        "checks": [{"requirement_id": "r001", "status": "passed", "reason": "visible",
                    "evidence": [{"capture_id": "cap-1"}]}],
        "runtime_checks": [{"requirement_id": "startup", "status": "passed"}],
        "instance_checks": [{"requirement_id": "i001", "status": "partial"}],
        "captures": [{"id": "cap-1", "path": "verification/hud.png", "label": "HUD", "build_version": "v1"}],
        "preview": {"mode": "auto"},
    }

    async def exercise():
        listed = {tool.name: tool.input_schema for tool in await server.list_tools()}
        assert set(listed) == {"get_progress", "update_progress"}
        assert set(listed["get_progress"]["properties"]) == {"status", "requirement_ids", "detail"}
        assert listed["get_progress"]["properties"]["detail"]["default"] == "summary"
        schema = listed["update_progress"]
        assert set(schema["properties"]) == set(batch)
        assert schema["required"] == ["request_id"]
        assert schema["properties"]["base_snapshot_id"]["default"] == ""
        assert schema["properties"]["checks"]["default"] is None
        read = await server.call_tool("get_progress", {"status": "pending", "requirement_ids": ["r001"]})
        assert not read.is_error
        assert read.structured_content["snapshot_id"] == "s0012"
        updated = await server.call_tool("update_progress", batch)
        assert not updated.is_error
        assert updated.structured_content["progress"] == {"passed": 3, "total": 10}
        await server.call_tool("update_progress", {"request_id": "preview", "preview": {"mode": "auto"}})

    asyncio.run(exercise())
    assert service.calls[0] == ("get", {"status": "pending", "requirement_ids": ["r001"]})
    assert service.calls[1] == ("update", batch)
    assert service.calls[2][1] == {
        "request_id": "preview", "base_snapshot_id": "", "summary": "", "checks": None,
        "runtime_checks": None, "instance_checks": None, "captures": None, "preview": {"mode": "auto"},
    }


def test_mcp_reports_service_conflicts():
    from mcp.server.mcpserver.exceptions import ToolError

    class ConflictService:
        def update_progress(self, **kwargs):
            raise ValueError("base_snapshot_id conflict")

    server = progress_tools.create_builder_progress_mcp_server(ConflictService())
    with pytest.raises(ToolError, match="base_snapshot_id conflict"):
        asyncio.run(server.call_tool("update_progress", {"request_id": "stale"}))


@pytest.fixture
def cli_service(monkeypatch):
    service = RecordingService()
    roots = []

    def create(run_dir):
        roots.append(run_dir)
        return service

    monkeypatch.setattr(progress_tools, "_create_service", create)
    return service, roots


def test_cli_get_filters(tmp_path, capsys, cli_service):
    service, roots = cli_service
    assert progress_tools.main([
        "--run-dir", str(tmp_path), "get", "--status", "pending",
        "--requirement-id", "r001", "--requirement-id", "r002",
    ]) == 0
    assert roots == [tmp_path]
    assert service.calls == [("get", {"status": "pending", "requirement_ids": ["r001", "r002"]})]
    assert json.loads(capsys.readouterr().out)["snapshot_id"] == "s0012"


@pytest.mark.parametrize("stdin", [False, True])
def test_cli_update_uses_same_batch_adapter(tmp_path, monkeypatch, capsys, cli_service, stdin):
    service, _ = cli_service
    payload = {"request_id": "cli-1", "instance_checks": [{"requirement_id": "i001"}],
               "captures": [{"path": "verification/frame.png"}], "preview": {"mode": "auto"}}
    source = tmp_path / "batch with spaces.json"
    source.write_text(json.dumps(payload), encoding="utf-8-sig")
    monkeypatch.setattr(sys, "stdin", io.StringIO(json.dumps(payload)))
    assert progress_tools.main([
        "--run-dir", str(tmp_path), "update", "--request", "-" if stdin else str(source),
    ]) == 0
    assert json.loads(capsys.readouterr().out)["snapshot_id"] == "s0013"
    assert service.calls[0][0] == "update"
    assert all(service.calls[0][1][key] == value for key, value in payload.items())


@pytest.mark.parametrize("payload", ["{", "[]", "{}", '{"request_id":"x","passed":200}'])
def test_cli_rejects_invalid_requests_before_service(tmp_path, monkeypatch, capsys, cli_service, payload):
    monkeypatch.setattr(sys, "stdin", io.StringIO(payload))
    assert progress_tools.main(["--run-dir", str(tmp_path), "update", "--request", "-"]) == 1
    output = capsys.readouterr()
    assert output.out == ""
    assert json.loads(output.err)["error"]
    assert cli_service[1] == []


@pytest.mark.parametrize("entry", ["--stdio", "serve"])
def test_cli_stdio_aliases(tmp_path, monkeypatch, capsys, cli_service, entry):
    calls = []
    monkeypatch.setattr(progress_tools, "create_builder_progress_mcp_server", lambda service:
                        SimpleNamespace(run=lambda **kwargs: calls.append((service, kwargs))))
    assert progress_tools.main(["--run-dir", str(tmp_path), entry]) == 0
    assert calls == [(cli_service[0], {"transport": "stdio"})]
    assert capsys.readouterr().out == ""


def test_service_factory_binds_same_service_and_leaves_target_dynamic(tmp_path, monkeypatch):
    calls = []
    fake_module = SimpleNamespace(BuilderProgressService=lambda *args, **kwargs: calls.append((args, kwargs)))
    monkeypatch.setitem(sys.modules, "bench_builder.builder_progress", fake_module)
    progress_tools._create_service(tmp_path)
    assert calls == [((tmp_path.resolve(),), {})]


def test_absolute_entrypoint_starts_from_candidate_without_pythonpath(tmp_path):
    spec = progress_tools.builder_progress_mcp_servers(tmp_path)[0]
    assert spec["name"] == "builder_progress"
    assert spec["args"][-1] == "--stdio"
    completed = subprocess.run(
        [spec["command"], spec["args"][0], "--help"], cwd=tmp_path,
        capture_output=True, text=True, timeout=30,
    )
    assert completed.returncode == 0, completed.stderr
    assert "--run-dir" in completed.stdout
    assert "serve" in completed.stdout


def test_resume_includes_expanded_scope_without_changing_saved_tool_binding(tmp_path):
    import hashlib
    run = tmp_path / "run"
    candidate = run / "candidate"
    public = run / "public-inputs/video_agent/analysis"
    public.mkdir(parents=True)
    base = public / "game_design.json"
    base.write_text(json.dumps({"observable_requirements": [{"id": "original"}]}), encoding="utf-8")
    (run / "requirement_additions.json").write_text(json.dumps({
        "schema_version": 1, "base_contract_sha256": hashlib.sha256(base.read_bytes()).hexdigest(),
        "revisions": [{"id": "user-1", "authorization": "Add death and retry", "reason": "Expanded scope",
                       "requirements": [{"id": "death", "acceptance": "Death stops normal controls"},
                                        {"id": "retry", "acceptance": "Retry resets the encounter"}]}],
    }), encoding="utf-8")
    prompt, servers = progress_tools.prepare_builder_progress_prompt(
        "Continue the same session.", run_dir=run, candidate=candidate, public=public,
        plugin_id="own-agent", resume=True,
    )
    assert servers == ()  # A legacy session keeps its original CLI binding.
    assert "effective checklist now has 3 IDs" in prompt
    assert "older scope and does not satisfy this request" in prompt
    assert str((run / "requirement_additions.json").resolve()) in prompt
    assert str((candidate / "USER_REQUIREMENTS_UPDATE.md").resolve()) in prompt
    assert "create a new goal" in prompt
    assert "same session and candidate" in prompt
    assert json.loads(base.read_text())["observable_requirements"] == [{"id": "original"}]
    additions = run / "requirement_additions.json"
    assert hashlib.sha256(additions.read_bytes()).hexdigest() in prompt
    assert "missing at prompt preparation" in prompt
    assert "only after actually reading them" in prompt
    assert "no read record exists, read it in full" in prompt
    assert "entire effective scope" in prompt

    # New or edited owner notes invalidate a previous read record without changing the contract.
    notes = candidate / "USER_REQUIREMENTS_UPDATE.md"
    notes.write_text("Retry must also reset health.", encoding="utf-8")
    updated, updated_servers = progress_tools.prepare_builder_progress_prompt(
        "Continue the same session.", run_dir=run, candidate=candidate, public=public,
        plugin_id="own-agent", resume=True,
    )
    first_digest = hashlib.sha256(notes.read_bytes()).hexdigest()
    assert first_digest in updated
    assert "missing at prompt preparation" not in updated
    notes.write_text("Retry must reset health and inventory.", encoding="utf-8")
    revised, _ = progress_tools.prepare_builder_progress_prompt(
        "Continue the same session.", run_dir=run, candidate=candidate, public=public,
        plugin_id="own-agent", resume=True,
    )
    assert first_digest not in revised
    assert hashlib.sha256(notes.read_bytes()).hexdigest() in revised
    assert "effective checklist now has 3 IDs" in revised
    assert updated_servers == servers
    assert json.loads(base.read_text())["observable_requirements"] == [{"id": "original"}]


@pytest.mark.parametrize(("plugin_id", "legacy", "archive", "engine"), [
    *[("acpx", legacy, archive, "webgame") for legacy in (False, True) for archive in (False, True)],
    ("dsh", False, False, "webgame"),
    ("acpx", False, False, "godot"),
])
def test_actual_builder_request_injection_and_resume(
    tmp_path, monkeypatch, plugin_id, legacy, archive, engine,
):
    package = tmp_path / "package"
    for name in ("task", "task_gt", "evaluator"):
        (package / name).mkdir(parents=True)
    (package / "task/task_config.json").write_text(json.dumps({
        "name": "Progress fixture", "engine_type": engine, "instruction": "Build a coin game.",
        "metadata": {"github_repo": "https://example.test/coin-game.git"},
    }), encoding="utf-8")
    for name in ("task", "task_gt"):
        (package / name / "LICENSE").write_text("MIT", encoding="utf-8")
    task = program_bench.bootstrap_package(package)
    plugin = get_harness_plugin(plugin_id)
    spec = plugin.profile(runtime_engine=engine, model="fixture", options={})
    profile = program_bench.AgentProfile(
        profile_id=spec.profile_id, display_name=spec.display_name, image=spec.image,
        argv=spec.argv, enabled=True, runtime_engines=spec.runtime_engines,
    )
    requests, prompts = [], []
    from contextlib import nullcontext
    monkeypatch.setattr(program_bench, "_bound_screenshot_broker", lambda *args: nullcontext())

    def prepare(_task, *, candidate, **kwargs):
        public = candidate / "reference_screenshots"
        public.mkdir(exist_ok=True)
        return program_bench.ShellWorkspace(
            candidate=candidate, public=public, toolchain_sha256="a" * 64,
            tools_sha256="b" * 64, node_version="24.1.0", chromium_revision="1234", dependencies={},
        )

    def run(_plugin, request):
        requests.append(request)
        prompts.append(request.prompt_path.read_text(encoding="utf-8"))
        if engine == "godot":
            (request.candidate / "project.godot").write_text("config_version=5\n", encoding="utf-8")
        else:
            (request.candidate / "index.html").write_text("<main>Game</main>", encoding="utf-8")
        artifacts = {}
        if archive:
            name = "acpx-session.json"
            (request.evidence_dir / name).write_text("{}")
            artifacts["harness_session"] = name
        return HarnessRunResult(
            command=("fixture",), returncode=0, stdout="built", stderr="", duration_seconds=0.01,
            timed_out=False, evidence={"status": "verified"}, events_name=plugin.descriptor.events_name,
            status="complete", artifacts=artifacts,
        )

    monkeypatch.setattr(program_bench, "_prepare_shell_workspace", prepare)
    monkeypatch.setattr(type(plugin), "run", run)
    prepare_prompt = progress_tools.prepare_builder_progress_prompt
    if legacy:
        monkeypatch.setattr(progress_tools, "prepare_builder_progress_prompt", lambda prompt, **kw: (prompt, ()))
    first = program_bench.run_agent_build(
        task, profile=profile, mode="lite", root=tmp_path / "runs", harness_plugin_id=plugin_id,
        goal_mode=plugin_id == "dsh",
    )
    assert first.status == "agent_complete", first.result.get("diagnostics")
    monkeypatch.setattr(progress_tools, "prepare_builder_progress_prompt", prepare_prompt)
    # No snapshot or progress call has been made. Resume must use saved prompt evidence.
    assert not (first.run_dir / "agent/progress/snapshots.jsonl").exists()
    monkeypatch.setattr(progress_tools, "builder_progress_mcp_servers", lambda *_args:
                        pytest.fail("must not construct a new MCP binding during resume"))
    second = program_bench.run_agent_build(
        task, profile=profile, mode="lite", root=tmp_path / "runs", harness_plugin_id=plugin_id,
        previous_run=first, build_round=2, completion_threshold_percent=95,
        goal_mode=plugin_id == "dsh",
    )
    assert second.status == "agent_complete", second.result.get("diagnostics")
    assert requests[0].mcp_servers == requests[1].mcp_servers
    expects_mcp = engine == "webgame" and plugin_id == "acpx" and not legacy
    assert bool(requests[1].mcp_servers) is expects_mcp
    if expects_mcp:
        binding = requests[1].mcp_servers[0]
        assert binding["name"] == "builder_progress"
        assert binding["args"][binding["args"].index("--run-dir") + 1] == str(first.run_dir.resolve())
    assert requests[1].candidate == requests[0].candidate
    assert requests[1].resume_interrupted
    assert requests[1].conversation_id == requests[0].conversation_id
    assert requests[1].turn_index == 2
    assert "requirement pass target is 95%" in prompts[1]
    if engine != "webgame" or plugin_id == "dsh":
        for prompt in prompts:
            assert "Builder progress tools are not bound for this harness" in prompt
            assert "builder_checks.json directly in your working game directory" in prompt
            assert "replace the JSON atomically" in prompt
            assert "update_progress" not in prompt
            assert "get_progress" not in prompt
            assert "builder_progress_tools.py" not in prompt
            assert "never write the ledger JSON directly" not in prompt
            assert "builder-progress-mcp" not in prompt
        assert not (first.run_dir / "candidate/.agents/skills/builder-progress").exists()
        if engine != "webgame":
            # A caller's availability hint cannot enable unsupported-engine prompt rules.
            preview = program_bench.agent_harness_prompt_text(
                task, node_version="24.1.0", goal_mode=True, progress_tools_available=True,
            )
            assert "update_progress" not in preview
            assert "replace the JSON atomically" in preview
        return
    assert "never write the ledger JSON directly" in prompts[1]
    assert "without evidence gates or automatic version resets" in prompts[1]
    assert str((first.run_dir / "candidate/.agents/skills/builder-progress/SKILL.md").resolve()) in prompts[1]
    assert "get --status pending" in prompts[1]
    assert "update --request -" in prompts[1]
    assert "Build and play the game" in prompts[1]
    assert "Use get_progress on resume" in prompts[1]
    if legacy:
        assert "Use the following CLI through the existing native shell tool" in prompts[1]


def test_acpx_resume_can_reuse_existing_mcp_config(tmp_path):
    bound = progress_tools.builder_progress_mcp_servers(tmp_path)[0]
    bound["command"] = "C:/Original Python/python.exe"
    (tmp_path / "agent").mkdir()
    (tmp_path / "agent/video-tools-mcp.json").write_text(json.dumps({
        "mcpServers": [{"name": "video_reference", "command": "python", "args": [], "env": []}, bound],
    }), encoding="utf-8")
    assert progress_tools._saved_progress_servers(tmp_path, "own-agent") == (bound,)






@pytest.mark.parametrize("plugin_id", ["cursor_cloud", "dsh", "custom_remote"])
@pytest.mark.parametrize("resume", [False, True])
def test_unsupported_harness_prompt_has_no_local_tools_or_skill(tmp_path, plugin_id, resume):
    prompt, servers = progress_tools.prepare_builder_progress_prompt(
        "Build using the legacy checklist.", run_dir=tmp_path, candidate=tmp_path / "candidate",
        public=tmp_path / "public", plugin_id=plugin_id, resume=resume,
    )
    assert prompt == "Build using the legacy checklist."
    assert servers == ()
    assert list(tmp_path.iterdir()) == []


@pytest.mark.parametrize("available", [False, True])
@pytest.mark.parametrize("goal", [False, True])
def test_completion_prompt_only_requires_tools_when_available(available, goal):
    prompt = (program_bench._shell_goal_prompt_text(
        "Build.", build_round=1, continuation=False, progress_tools_available=available,
    ) if goal else program_bench._build_completion_prompt(100, progress_tools_available=available))
    assert ("update_progress" in prompt) is available
    assert ("get_progress" in prompt) is available
    assert ("never write the ledger JSON directly" in prompt) is available
    assert ("replace the JSON atomically" in prompt) is not available
    assert ("without evidence gates or automatic version resets" in prompt) is available
    assert "runtime checks must pass regardless" in prompt


@pytest.fixture
def real_run(tmp_path):
    from PIL import Image

    candidate = tmp_path / "candidate"
    (candidate / "dist").mkdir(parents=True)
    (candidate / "dist/index.html").write_text("<main>Game</main>", encoding="utf-8")
    (candidate / "game_design.json").write_text(json.dumps({
        "observable_requirements": [{"id": "r001", "acceptance": "Red player"},
                                    {"id": "r002", "acceptance": "Moves on click"}],
        "reference_instances": [{"instance_id": "player.1"}],
    }), encoding="utf-8")
    verification = candidate / "verification"
    verification.mkdir()
    Image.new("RGB", (64, 36), "red").save(verification / "hud.png")
    (verification / "results.json").write_text('{"inputs":["click"],"errors":[]}', encoding="utf-8")
    (tmp_path / "result.json").write_text('{"build":{"completion_threshold_percent":100}}', encoding="utf-8")
    return tmp_path


def test_real_service_over_bound_stdio_and_cli(real_run):
    from mcp import ClientSession
    from mcp.client.stdio import StdioServerParameters, stdio_client
    from PIL import Image

    spec = progress_tools.builder_progress_mcp_servers(real_run)[0]
    candidate = real_run / "candidate"
    original_image = (candidate / "verification/hud.png").read_bytes()

    async def exercise():
        params = StdioServerParameters(command=spec["command"], args=spec["args"], cwd=str(candidate))
        async with stdio_client(params) as (read, write):
            async with ClientSession(read, write, read_timeout_seconds=30) as session:
                initialized = await session.initialize()
                assert initialized.server_info.name == "builder_progress"
                assert {tool.name for tool in (await session.list_tools()).tools} == {"get_progress", "update_progress"}
                current = (await session.call_tool("get_progress", {})).structured_content
                assert current["snapshot_id"] == ""
                assert current["progress"]["targetPercent"] == 100
                version = current["current_version"]
                batch = {
                    "request_id": "mcp-first", "preview": {"mode": "none"},
                    "captures": [{"id": "hud", "path": "verification/hud.png", "label": "HUD", "build_version": version}],
                    "checks": [{"requirement_id": "r001", "status": "passed", "reason": "Inspected red player",
                                "evidence": [{"capture_id": "hud"}]}],
                    "runtime_checks": [{"requirement_id": "startup", "status": "passed", "reason": "No startup errors",
                                        "evidence": [{"path": "verification/results.json", "build_version": version}]}],
                    "instance_checks": [{"requirement_id": "player.1", "status": "partial", "reason": "Motion pending"}],
                }
                published = await session.call_tool("update_progress", batch)
                assert not published.is_error
                first = published.structured_content
                assert first["progress"]["passed"] == 1
                assert first["pending_count"] == 1 and "pending_ids" not in first
                assert first["instance_progress"] == {"partial": 1}
                retried = await session.call_tool("update_progress", batch)
                assert retried.structured_content["snapshot_id"] == first["snapshot_id"]
                conflict = await session.call_tool("update_progress", {**batch, "summary": "Different content"})
                assert conflict.is_error
                assert "request_id was already used" in conflict.content[0].text

                # The already-running service sees a new target without a different MCP binding.
                (real_run / "result.json").write_text('{"build":{"completion_threshold_percent":95}}', encoding="utf-8")
                current = (await session.call_tool("get_progress", {"status": "pending"})).structured_content
                assert current["progress"]["targetPercent"] == 95
                assert current["checks_by_status"] == {"pending": ["r002"]}
                assert progress_tools.builder_progress_mcp_servers(real_run)[0] == spec

                Image.new("RGB", (64, 36), "blue").save(candidate / "verification/hud.png")
                assert Path(first["captures"][0]["path"]).read_bytes() == original_image
                return first

    first = asyncio.run(exercise())
    # Launch the exact absolute CLI from outside the repository and read the MCP publication.
    cli = subprocess.run(
        [spec["command"], *spec["args"][:-1], "get", "--status", "passed"], cwd=candidate,
        capture_output=True, text=True, timeout=30,
    )
    assert cli.returncode == 0, cli.stderr
    data = json.loads(cli.stdout)
    assert data["snapshot_id"] == first["snapshot_id"]
    assert data["checks_by_status"] == {"passed": ["r001"]}


def test_legacy_cli_publication_never_mutates_session_fingerprint(real_run, monkeypatch, capsys):
    candidate = real_run / "candidate"
    agent = real_run / "agent"
    agent.mkdir()
    # An existing video-only acpx config must remain byte-for-byte intact.
    saved = {
        "video-tools-mcp.json": {"mcpServers": [{"name": "video_reference", "command": "python", "args": [], "env": []}]},
        "harness-mcp-session.json": {"mcp_sha256": ""},
    }
    for name, payload in saved.items():
        (agent / name).write_text(json.dumps(payload), encoding="utf-8")
    before = {name: (agent / name).read_bytes() for name in saved}
    for turn in (2, 3):
        prompt, servers = progress_tools.prepare_builder_progress_prompt(
            "Continue.", run_dir=real_run, candidate=candidate, public=candidate / "reference_screenshots",
            plugin_id="own-agent", resume=True,
        )
        assert servers == ()
        (real_run / "prompt.md").write_text(prompt, encoding="utf-8")
        if turn == 2:
            monkeypatch.setattr(sys, "stdin", io.StringIO(json.dumps({
                "request_id": "legacy-cli-first", "summary": "Checks still pending", "preview": {"mode": "none"},
            })))
            assert progress_tools.main(["--run-dir", str(real_run), "update", "--request", "-"]) == 0
            assert json.loads(capsys.readouterr().out)["snapshot_id"]
    assert {name: (agent / name).read_bytes() for name in saved} == before


def test_missing_canonical_contract_error_and_documented_fallback(tmp_path, capsys):
    from mcp.server.mcpserver.exceptions import ToolError

    service = progress_tools._create_service(tmp_path)
    server = progress_tools.create_builder_progress_mcp_server(service)
    with pytest.raises(ToolError, match="stable game_design.json requirement list"):
        asyncio.run(server.call_tool("get_progress", {}))
    assert progress_tools.main(["--run-dir", str(tmp_path), "get"]) == 1
    assert "stable game_design.json" in json.loads(capsys.readouterr().err)["error"]
    candidate = tmp_path / "candidate"
    candidate.mkdir()
    (candidate / "game_design.json").write_text(json.dumps({
        "observable_requirements": [{"id": "r001", "acceptance": "One concrete requirement"}],
    }), encoding="utf-8")
    recovered = asyncio.run(server.call_tool("get_progress", {})).structured_content
    assert recovered["progress"]["total"] == 1
    assert recovered["snapshot_id"] == ""
    assert not (candidate / "builder_checks.json").exists()
    prompt, _ = progress_tools.prepare_builder_progress_prompt(
        "Build.", run_dir=tmp_path, candidate=candidate, public=candidate / "reference_screenshots",
        plugin_id="own-agent", resume=False,
    )
    assert str((candidate / "game_design.json").resolve()) in prompt
    assert "Preserve the requested scope" in prompt
    assert "snapshot timeline for the UI" in prompt