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
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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
from __future__ import annotations

import json

import httpx
import pytest

from replicalab.agents.scientist_policy import (
    RetryMetadata,
    ScientistCallResult,
    ScientistOutputParseError,
    build_anthropic_scientist_policy,
    build_baseline_scientist_action,
    build_ollama_scientist_policy,
    build_scientist_system_prompt,
    call_scientist_with_retry,
    format_scientist_observation,
    parse_scientist_output,
)
from replicalab.models import (
    ConversationEntry,
    Protocol,
    ScientistActionType,
    ScientistObservation,
)
from replicalab.scenarios import generate_scenario


# ---------------------------------------------------------------------------
# Shared valid JSON payloads for retry tests
# ---------------------------------------------------------------------------

_VALID_REQUEST_INFO_JSON = """{
  "action_type": "request_info",
  "sample_size": 0,
  "controls": [],
  "technique": "",
  "duration_days": 0,
  "required_equipment": [],
  "required_reagents": [],
  "questions": ["What compute budget is available?"],
  "rationale": ""
}"""


def test_parse_scientist_output_accepts_plain_json() -> None:
    raw_text = """
    {
      "action_type": "request_info",
      "sample_size": 0,
      "controls": [],
      "technique": "",
      "duration_days": 0,
      "required_equipment": [],
      "required_reagents": [],
      "questions": ["What compute budget is available?"],
      "rationale": ""
    }
    """

    action = parse_scientist_output(raw_text)

    assert action.action_type is ScientistActionType.REQUEST_INFO
    assert action.questions == ["What compute budget is available?"]


def test_parse_scientist_output_accepts_fenced_json_with_prose() -> None:
    raw_text = """
    I would revise the plan as follows:

    ```json
    {
      "action_type": "revise_protocol",
      "sample_size": 24,
      "controls": ["baseline", "ablation"],
      "technique": "small_scale_backtest",
      "duration_days": 3,
      "required_equipment": ["gpu_node"],
      "required_reagents": [],
      "questions": [],
      "rationale": "Shrink the trial to fit the available compute window."
    }
    ```
    """

    action = parse_scientist_output(raw_text)

    assert action.action_type is ScientistActionType.REVISE_PROTOCOL
    assert action.technique == "small_scale_backtest"


def test_parse_scientist_output_raises_explicit_error_when_json_is_missing() -> None:
    with pytest.raises(ScientistOutputParseError) as exc_info:
        parse_scientist_output("I need more context before I can answer.")

    assert exc_info.value.code == "no_json"
    assert "does not contain a JSON object" in exc_info.value.message


def test_parse_scientist_output_raises_explicit_error_when_json_is_invalid() -> None:
    raw_text = """
    ```json
    {
      "action_type": "request_info",
      "questions": ["What budget do we have?"],
    }
    ```
    """

    with pytest.raises(ScientistOutputParseError) as exc_info:
        parse_scientist_output(raw_text)

    assert exc_info.value.code == "invalid_json"
    assert "could not be decoded" in exc_info.value.message


def test_parse_scientist_output_raises_explicit_error_when_schema_is_invalid() -> None:
    raw_text = """
    {
      "action_type": "request_info",
      "sample_size": 0,
      "controls": [],
      "technique": "",
      "duration_days": 0,
      "required_equipment": [],
      "required_reagents": [],
      "questions": [],
      "rationale": ""
    }
    """

    with pytest.raises(ScientistOutputParseError) as exc_info:
        parse_scientist_output(raw_text)

    assert exc_info.value.code == "invalid_action"
    assert "ScientistAction validation" in exc_info.value.message


def test_build_scientist_system_prompt_uses_normalized_scenario_data() -> None:
    scenario = generate_scenario(seed=202, template="ml_benchmark", difficulty="medium")

    prompt = build_scientist_system_prompt(scenario)

    assert "You are the Scientist agent in ReplicaLab." in prompt
    assert scenario.task_summary in prompt
    assert scenario.success_criteria[0] in prompt
    assert scenario.resources[0].label in prompt
    assert "action_type values" in prompt
    assert "propose_protocol" in prompt
    assert "request_info" in prompt


# ---------------------------------------------------------------------------
# AGT 02 — format_scientist_observation
# ---------------------------------------------------------------------------


def _base_observation(**overrides) -> ScientistObservation:
    defaults = {
        "paper_title": "Test Paper Title",
        "paper_hypothesis": "X improves Y.",
        "paper_method": "Run benchmark Z.",
        "paper_key_finding": "10% improvement.",
        "experiment_goal": "Replicate the 10% improvement.",
        "conversation_history": [],
        "current_protocol": None,
        "round_number": 0,
        "max_rounds": 6,
    }
    defaults.update(overrides)
    return ScientistObservation(**defaults)


def test_format_observation_empty_history_no_protocol() -> None:
    obs = _base_observation()
    result = format_scientist_observation(obs)

    assert "Round 0 of 6" in result
    assert "Test Paper Title" in result
    assert "X improves Y." in result
    assert "Run benchmark Z." in result
    assert "10% improvement." in result
    assert "Replicate the 10% improvement." in result
    assert "No conversation history yet" in result
    assert "No protocol has been proposed yet" in result
    assert "ScientistAction schema reminder:" in result
    assert (
        "allowed action_type values: propose_protocol, revise_protocol, "
        "request_info, accept"
    ) in result
    assert "include all ScientistAction fields in every response" in result
    assert "Respond with exactly one JSON object" in result


def test_format_observation_with_history_and_protocol() -> None:
    history = [
        ConversationEntry(
            role="scientist",
            message="I propose a grid search protocol.",
            round_number=1,
            action_type="propose_protocol",
        ),
        ConversationEntry(
            role="lab_manager",
            message="The compute cluster is booked. Consider a smaller run.",
            round_number=1,
            action_type="suggest_alternative",
        ),
    ]
    protocol = Protocol(
        sample_size=24,
        controls=["baseline", "ablation"],
        technique="grid_search",
        duration_days=3,
        required_equipment=["gpu_node"],
        required_reagents=["benchmark_dataset"],
        rationale="Standard hyperparameter sweep.",
    )
    obs = _base_observation(
        conversation_history=history,
        current_protocol=protocol,
        round_number=2,
    )
    result = format_scientist_observation(obs)

    assert "Round 2 of 6" in result
    assert "Conversation so far:" in result
    assert "[SCIENTIST r1 [propose_protocol]]" in result
    assert "I propose a grid search protocol." in result
    assert "[LAB_MANAGER r1 [suggest_alternative]]" in result
    assert "compute cluster is booked" in result
    assert "Current protocol:" in result
    assert "technique: grid_search" in result
    assert "sample_size: 24" in result
    assert "controls: baseline, ablation" in result
    assert "duration_days: 3" in result
    assert "gpu_node" in result
    assert "benchmark_dataset" in result
    assert "Standard hyperparameter sweep." in result


def test_format_observation_stable_section_order() -> None:
    obs = _base_observation(
        conversation_history=[
            ConversationEntry(
                role="scientist",
                message="First proposal.",
                round_number=1,
                action_type="propose_protocol",
            ),
        ],
        current_protocol=Protocol(
            sample_size=10,
            controls=["ctrl"],
            technique="method_a",
            duration_days=2,
            required_equipment=["tool_a"],
            required_reagents=["reagent_a"],
            rationale="Simple test.",
        ),
        round_number=1,
    )
    result = format_scientist_observation(obs)

    # Sections must appear in this fixed order
    round_pos = result.index("Round 1 of 6")
    paper_pos = result.index("Paper:")
    history_pos = result.index("Conversation so far:")
    protocol_pos = result.index("Current protocol:")
    action_pos = result.index("Respond with exactly one JSON")

    assert round_pos < paper_pos < history_pos < protocol_pos < action_pos


def test_format_observation_history_entry_without_action_type() -> None:
    obs = _base_observation(
        conversation_history=[
            ConversationEntry(
                role="system",
                message="Episode started.",
                round_number=0,
                action_type=None,
            ),
        ],
    )
    result = format_scientist_observation(obs)

    assert "[SYSTEM r0]:" in result
    assert "Episode started." in result


def test_format_observation_from_generated_scenario() -> None:
    scenario = generate_scenario(seed=77, template="finance_trading", difficulty="easy")
    obs = scenario.scientist_observation
    result = format_scientist_observation(obs)

    assert obs.paper_title in result
    assert obs.experiment_goal in result
    assert "Round 0" in result
    assert "No conversation history yet" in result
    assert "Respond with exactly one JSON" in result


# ---------------------------------------------------------------------------
# AGT 03 — call_scientist_with_retry
# ---------------------------------------------------------------------------


def _make_system_prompt() -> str:
    scenario = generate_scenario(seed=1, template="math_reasoning", difficulty="easy")
    return build_scientist_system_prompt(scenario)


def test_retry_success_on_first_try() -> None:
    def gen_fn(messages: list[dict[str, str]]) -> str:
        return _VALID_REQUEST_INFO_JSON

    obs = _base_observation()
    result = call_scientist_with_retry(gen_fn, _make_system_prompt(), obs)

    assert isinstance(result, ScientistCallResult)
    assert result.action.action_type is ScientistActionType.REQUEST_INFO
    assert result.metadata.attempt_count == 1
    assert result.metadata.retry_count == 0
    assert result.metadata.last_error_code is None
    assert result.metadata.last_error_message is None


def test_retry_malformed_json_then_valid() -> None:
    call_count = 0

    def gen_fn(messages: list[dict[str, str]]) -> str:
        nonlocal call_count
        call_count += 1
        if call_count == 1:
            return '{"action_type": "request_info", trailing garbage'
        return _VALID_REQUEST_INFO_JSON

    obs = _base_observation()
    result = call_scientist_with_retry(gen_fn, _make_system_prompt(), obs)

    assert result.action.action_type is ScientistActionType.REQUEST_INFO
    assert result.metadata.attempt_count == 2
    assert result.metadata.retry_count == 1
    assert result.metadata.last_error_code == "invalid_json"


def test_retry_invalid_action_then_valid() -> None:
    # First attempt: valid JSON but questions is empty for request_info
    invalid_json = """{
      "action_type": "request_info",
      "sample_size": 0,
      "controls": [],
      "technique": "",
      "duration_days": 0,
      "required_equipment": [],
      "required_reagents": [],
      "questions": [],
      "rationale": ""
    }"""
    call_count = 0

    def gen_fn(messages: list[dict[str, str]]) -> str:
        nonlocal call_count
        call_count += 1
        if call_count == 1:
            return invalid_json
        return _VALID_REQUEST_INFO_JSON

    obs = _base_observation()
    result = call_scientist_with_retry(gen_fn, _make_system_prompt(), obs)

    assert result.action.action_type is ScientistActionType.REQUEST_INFO
    assert result.metadata.attempt_count == 2
    assert result.metadata.retry_count == 1
    assert result.metadata.last_error_code == "invalid_action"
    assert "ScientistAction validation" in result.metadata.last_error_message


def test_retry_exhausted_raises_last_error() -> None:
    def gen_fn(messages: list[dict[str, str]]) -> str:
        return "I cannot produce JSON right now."

    obs = _base_observation()
    with pytest.raises(ScientistOutputParseError) as exc_info:
        call_scientist_with_retry(gen_fn, _make_system_prompt(), obs, max_retries=2)

    assert exc_info.value.code == "no_json"


def test_retry_correction_message_includes_parser_error() -> None:
    """The correction prompt sent to the model must include the specific error."""
    captured_messages: list[list[dict[str, str]]] = []

    call_count = 0

    def gen_fn(messages: list[dict[str, str]]) -> str:
        nonlocal call_count
        call_count += 1
        captured_messages.append(list(messages))
        if call_count == 1:
            return "Just some prose, no JSON here."
        return _VALID_REQUEST_INFO_JSON

    obs = _base_observation()
    call_scientist_with_retry(gen_fn, _make_system_prompt(), obs)

    # Second call should have 4 messages: system, user, assistant (bad), user (correction)
    assert len(captured_messages) == 2
    retry_messages = captured_messages[1]
    assert len(retry_messages) == 4
    assert retry_messages[2]["role"] == "assistant"
    assert retry_messages[2]["content"] == "Just some prose, no JSON here."
    assert retry_messages[3]["role"] == "user"
    correction = retry_messages[3]["content"]
    assert "did not contain a JSON object" in correction
    assert "No markdown fences, no prose" in correction


def test_retry_correction_for_invalid_action_includes_validation_detail() -> None:
    """invalid_action correction must include the schema validation message."""
    captured_messages: list[list[dict[str, str]]] = []

    invalid_json = """{
      "action_type": "request_info",
      "sample_size": 0,
      "controls": [],
      "technique": "",
      "duration_days": 0,
      "required_equipment": [],
      "required_reagents": [],
      "questions": [],
      "rationale": ""
    }"""
    call_count = 0

    def gen_fn(messages: list[dict[str, str]]) -> str:
        nonlocal call_count
        call_count += 1
        captured_messages.append(list(messages))
        if call_count == 1:
            return invalid_json
        return _VALID_REQUEST_INFO_JSON

    obs = _base_observation()
    call_scientist_with_retry(gen_fn, _make_system_prompt(), obs)

    retry_messages = captured_messages[1]
    correction = retry_messages[3]["content"]
    assert "failed ScientistAction validation" in correction
    assert "Fix the validation error" in correction


def test_retry_metadata_serializable() -> None:
    def gen_fn(messages: list[dict[str, str]]) -> str:
        return _VALID_REQUEST_INFO_JSON

    obs = _base_observation()
    result = call_scientist_with_retry(gen_fn, _make_system_prompt(), obs)

    dumped = result.metadata.model_dump_json()
    restored = RetryMetadata.model_validate_json(dumped)
    assert restored.attempt_count == 1
    assert restored.retry_count == 0


# ---------------------------------------------------------------------------
# AGT 04 - build_baseline_scientist_action
# ---------------------------------------------------------------------------


def test_baseline_scientist_proposes_protocol_for_fresh_observation() -> None:
    action = build_baseline_scientist_action(_base_observation())

    assert action.action_type is ScientistActionType.PROPOSE_PROTOCOL
    assert action.sample_size >= 1
    assert action.duration_days >= 1
    assert action.questions == []
    assert action.rationale


def test_baseline_scientist_accepts_existing_protocol_without_blocker() -> None:
    obs = _base_observation(
        current_protocol=Protocol(
            sample_size=10,
            controls=["baseline_check"],
            technique="published_split_replication",
            duration_days=2,
            required_equipment=[],
            required_reagents=[],
            rationale="Initial protocol is already in place.",
        ),
        conversation_history=[
            ConversationEntry(
                role="lab_manager",
                message="The current plan remains feasible.",
                round_number=1,
                action_type="report_feasibility",
            )
        ],
        round_number=1,
    )

    action = build_baseline_scientist_action(obs)

    assert action.action_type is ScientistActionType.ACCEPT
    assert action.sample_size == 0
    assert action.controls == []


def test_baseline_scientist_revises_when_latest_feedback_has_blocker() -> None:
    obs = _base_observation(
        current_protocol=Protocol(
            sample_size=12,
            controls=["published_split_check", "heldout_evaluation"],
            technique="published_split_replication",
            duration_days=3,
            required_equipment=[],
            required_reagents=[],
            rationale="Original scope is full-size.",
        ),
        conversation_history=[
            ConversationEntry(
                role="lab_manager",
                message="The current GPU plan is booked, so the schedule is too tight.",
                round_number=1,
                action_type="suggest_alternative",
            )
        ],
        round_number=1,
    )

    action = build_baseline_scientist_action(obs)

    assert action.action_type is ScientistActionType.REVISE_PROTOCOL
    assert action.sample_size == 6
    assert action.duration_days == 2
    assert "latest Lab Manager concern" in action.rationale


def test_baseline_scientist_finishes_stub_episode_without_crashing() -> None:
    from server.app import _StubEnv

    env = _StubEnv()

    first_observation = env.reset(
        seed=14,
        scenario="ml_benchmark",
        difficulty="easy",
    ).scientist
    assert first_observation is not None

    first_action = build_baseline_scientist_action(first_observation)
    first_step = env.step(first_action)
    assert first_step.done is False
    assert first_step.observation is not None
    assert first_step.observation.scientist is not None

    second_action = build_baseline_scientist_action(first_step.observation.scientist)
    second_step = env.step(second_action)

    assert second_step.done is True
    assert second_step.info.agreement_reached is True


# ---------------------------------------------------------------------------
# AGT 08 — Extended prompt, parser, formatter, and baseline coverage
# ---------------------------------------------------------------------------


# --- Parser happy paths ---


def test_parse_scientist_output_accepts_propose_protocol() -> None:
    raw_text = """{
      "action_type": "propose_protocol",
      "sample_size": 48,
      "controls": ["vehicle_control", "positive_control"],
      "technique": "wst1_assay",
      "duration_days": 5,
      "required_equipment": ["plate_reader"],
      "required_reagents": ["wst1", "dmso"],
      "questions": [],
      "rationale": "Standard viability assay with two controls."
    }"""

    action = parse_scientist_output(raw_text)

    assert action.action_type is ScientistActionType.PROPOSE_PROTOCOL
    assert action.sample_size == 48
    assert action.technique == "wst1_assay"
    assert action.controls == ["vehicle_control", "positive_control"]
    assert action.questions == []


def test_parse_scientist_output_accepts_accept_action() -> None:
    raw_text = """{
      "action_type": "accept",
      "sample_size": 0,
      "controls": [],
      "technique": "",
      "duration_days": 0,
      "required_equipment": [],
      "required_reagents": [],
      "questions": [],
      "rationale": ""
    }"""

    action = parse_scientist_output(raw_text)

    assert action.action_type is ScientistActionType.ACCEPT
    assert action.sample_size == 0
    assert action.rationale == ""


def test_parse_scientist_output_accepts_prose_wrapped_json() -> None:
    raw_text = (
        "After reviewing the constraints I think a request is in order.\n\n"
        '{"action_type": "request_info", "sample_size": 0, '
        '"controls": [], "technique": "", "duration_days": 0, '
        '"required_equipment": [], "required_reagents": [], '
        '"questions": ["Is the GPU available?"], "rationale": ""}\n\n'
        "That should clarify the compute situation."
    )

    action = parse_scientist_output(raw_text)

    assert action.action_type is ScientistActionType.REQUEST_INFO
    assert action.questions == ["Is the GPU available?"]


# --- Parser edge cases ---


def test_parse_scientist_output_raises_on_empty_string() -> None:
    with pytest.raises(ScientistOutputParseError) as exc_info:
        parse_scientist_output("")

    assert exc_info.value.code == "no_json"


def test_parse_scientist_output_raises_on_whitespace_only() -> None:
    with pytest.raises(ScientistOutputParseError) as exc_info:
        parse_scientist_output("   \n\t  ")

    assert exc_info.value.code == "no_json"


def test_parse_scientist_output_raises_on_json_list() -> None:
    # The parser's brace extractor finds the inner object from the list,
    # so this surfaces as an invalid_action (missing required fields)
    # rather than an invalid_json error.
    with pytest.raises(ScientistOutputParseError) as exc_info:
        parse_scientist_output('[{"action_type": "accept"}]')

    assert exc_info.value.code == "invalid_action"


def test_parse_scientist_output_raises_on_extra_forbidden_keys() -> None:
    raw_text = """{
      "action_type": "accept",
      "sample_size": 0,
      "controls": [],
      "technique": "",
      "duration_days": 0,
      "required_equipment": [],
      "required_reagents": [],
      "questions": [],
      "rationale": "",
      "secret_field": "should not be here"
    }"""

    with pytest.raises(ScientistOutputParseError) as exc_info:
        parse_scientist_output(raw_text)

    assert exc_info.value.code == "invalid_action"
    assert exc_info.value.parsed_payload is not None
    assert "secret_field" in exc_info.value.parsed_payload


def test_parse_error_to_dict_serialization() -> None:
    try:
        parse_scientist_output("no json here")
    except ScientistOutputParseError as exc:
        result = exc.to_dict()
        assert result["code"] == "no_json"
        assert result["raw_text"] == "no json here"
        assert result["parsed_payload"] is None
        assert "message" in result
    else:
        pytest.fail("Expected ScientistOutputParseError")


def test_parse_error_to_dict_with_parsed_payload() -> None:
    raw_text = """{
      "action_type": "request_info",
      "sample_size": 0,
      "controls": [],
      "technique": "",
      "duration_days": 0,
      "required_equipment": [],
      "required_reagents": [],
      "questions": [],
      "rationale": ""
    }"""
    try:
        parse_scientist_output(raw_text)
    except ScientistOutputParseError as exc:
        result = exc.to_dict()
        assert result["code"] == "invalid_action"
        assert result["parsed_payload"] is not None
        assert result["parsed_payload"]["action_type"] == "request_info"
    else:
        pytest.fail("Expected ScientistOutputParseError")


# --- System prompt: domain coverage ---


def test_system_prompt_math_domain() -> None:
    scenario = generate_scenario(seed=10, template="math_reasoning", difficulty="easy")
    prompt = build_scientist_system_prompt(scenario)

    assert "Domain: mathematics" in prompt
    assert scenario.task_summary in prompt
    assert "You are the Scientist agent" in prompt


def test_system_prompt_finance_domain() -> None:
    scenario = generate_scenario(seed=10, template="finance_trading", difficulty="easy")
    prompt = build_scientist_system_prompt(scenario)

    assert "Domain: finance_trading" in prompt
    assert scenario.task_summary in prompt


def test_system_prompt_ml_domain() -> None:
    scenario = generate_scenario(seed=10, template="ml_benchmark", difficulty="easy")
    prompt = build_scientist_system_prompt(scenario)

    assert "Domain: machine_learning" in prompt
    assert scenario.task_summary in prompt


def test_system_prompt_accepts_dict_input() -> None:
    scenario = generate_scenario(seed=5, template="math_reasoning", difficulty="easy")
    pack_dict = scenario.model_dump()

    prompt = build_scientist_system_prompt(pack_dict)

    assert "You are the Scientist agent" in prompt
    assert scenario.task_summary in prompt
    assert "Domain: mathematics" in prompt


# --- System prompt: bounded-tool policy assertions ---


def test_system_prompt_contains_bounded_tool_policy() -> None:
    scenario = generate_scenario(seed=1, template="math_reasoning", difficulty="easy")
    prompt = build_scientist_system_prompt(scenario)

    assert "search_evidence" in prompt
    assert "run_code_check" in prompt
    assert "inspect_image" in prompt


def test_system_prompt_bounded_tool_policy_rules() -> None:
    scenario = generate_scenario(seed=1, template="ml_benchmark", difficulty="medium")
    prompt = build_scientist_system_prompt(scenario)

    assert "No unrestricted web browsing" in prompt
    assert "No audio" in prompt
    assert "do not override constraints" in prompt or "Tools do not override constraints" in prompt


def test_system_prompt_bounded_tool_policy_present_in_all_domains() -> None:
    for template in ("math_reasoning", "ml_benchmark", "finance_trading"):
        scenario = generate_scenario(seed=42, template=template, difficulty="easy")
        prompt = build_scientist_system_prompt(scenario)

        assert "Bounded tool policy" in prompt, f"Missing in {template}"
        assert "search_evidence" in prompt, f"Missing search_evidence in {template}"
        assert "run_code_check" in prompt, f"Missing run_code_check in {template}"
        assert "inspect_image" in prompt, f"Missing inspect_image in {template}"


# --- System prompt: role-boundary assertions ---


def test_system_prompt_contains_role_boundaries() -> None:
    scenario = generate_scenario(seed=1, template="math_reasoning", difficulty="easy")
    prompt = build_scientist_system_prompt(scenario)

    assert "do not invent resources" in prompt
    assert "do not assume access to hidden ground truth" in prompt.lower() or \
           "hidden ground truth" in prompt


def test_system_prompt_contains_output_contract() -> None:
    scenario = generate_scenario(seed=1, template="math_reasoning", difficulty="easy")
    prompt = build_scientist_system_prompt(scenario)

    assert "Output contract" in prompt
    assert "exactly one JSON object" in prompt
    assert "no extra keys" in prompt


# --- Observation formatter edge cases ---


def test_format_observation_final_round() -> None:
    obs = _base_observation(round_number=5, max_rounds=6)
    result = format_scientist_observation(obs)

    assert "Round 5 of 6" in result
    assert "Respond with exactly one JSON" in result


def test_format_observation_protocol_with_empty_lists() -> None:
    protocol = Protocol(
        sample_size=1,
        controls=[],
        technique="minimal_check",
        duration_days=1,
        required_equipment=[],
        required_reagents=[],
        rationale="Minimal protocol.",
    )
    obs = _base_observation(current_protocol=protocol, round_number=1)
    result = format_scientist_observation(obs)

    assert "Current protocol:" in result
    assert "technique: minimal_check" in result
    assert "controls: (none)" in result
    assert "required_equipment: (none)" in result
    assert "required_reagents: (none)" in result


# --- Baseline: domain inference ---


def test_baseline_scientist_infers_ml_domain() -> None:
    obs = _base_observation(
        paper_title="Reproducing CIFAR-10 accuracy with ResNet",
        paper_method="Train on CIFAR dataset with GPU",
        experiment_goal="Match the published benchmark accuracy.",
    )
    action = build_baseline_scientist_action(obs)

    assert action.action_type is ScientistActionType.PROPOSE_PROTOCOL
    assert action.technique == "published_split_replication"


def test_baseline_scientist_infers_finance_domain() -> None:
    obs = _base_observation(
        paper_title="Offline backtest of SPY mean-reversion",
        paper_method="Daily bar backtest with slippage modeling",
        experiment_goal="Evaluate Sharpe ratio under drawdown limits.",
    )
    action = build_baseline_scientist_action(obs)

    assert action.action_type is ScientistActionType.PROPOSE_PROTOCOL
    assert action.technique == "offline_backtest_workflow"


def test_baseline_scientist_infers_math_domain() -> None:
    obs = _base_observation(
        paper_title="Planning a proof of AM-GM inequality",
        paper_method="Algebraic manipulation with induction.",
        experiment_goal="Verify the proof outline.",
    )
    action = build_baseline_scientist_action(obs)

    assert action.action_type is ScientistActionType.PROPOSE_PROTOCOL
    assert action.technique == "structured_proof_outline"


# --- Baseline: forced accept at final round ---


def test_baseline_scientist_accepts_at_final_round_even_with_blocker() -> None:
    obs = _base_observation(
        current_protocol=Protocol(
            sample_size=20,
            controls=["ctrl"],
            technique="method_a",
            duration_days=5,
            required_equipment=[],
            required_reagents=[],
            rationale="Full scope plan.",
        ),
        conversation_history=[
            ConversationEntry(
                role="lab_manager",
                message="Budget is tight and equipment is booked.",
                round_number=4,
                action_type="suggest_alternative",
            ),
        ],
        round_number=5,
        max_rounds=6,
    )

    action = build_baseline_scientist_action(obs)

    assert action.action_type is ScientistActionType.ACCEPT


def test_build_anthropic_scientist_policy_calls_messages_api() -> None:
    captured: dict[str, object] = {}

    def handler(request: httpx.Request) -> httpx.Response:
        captured["headers"] = dict(request.headers)
        captured["payload"] = json.loads(request.content.decode("utf-8"))
        return httpx.Response(
            200,
            json={
                "content": [
                    {
                        "type": "text",
                        "text": _VALID_REQUEST_INFO_JSON,
                    }
                ]
            },
        )

    client = httpx.Client(transport=httpx.MockTransport(handler))
    policy = build_anthropic_scientist_policy(
        api_key="test-key",
        model="claude-test",
        client=client,
        base_url="https://api.anthropic.com/v1/messages",
    )

    action = policy(
        _base_observation(),
        scenario="ml_benchmark",
        difficulty="medium",
    )

    assert action.action_type is ScientistActionType.REQUEST_INFO
    payload = captured["payload"]
    assert isinstance(payload, dict)
    assert payload["model"] == "claude-test"
    assert payload["temperature"] == 0.0
    assert payload["messages"][0]["role"] == "user"
    headers = captured["headers"]
    assert isinstance(headers, dict)
    assert headers["x-api-key"] == "test-key"


def test_build_ollama_scientist_policy_calls_local_chat_api() -> None:
    captured: dict[str, object] = {}

    def handler(request: httpx.Request) -> httpx.Response:
        captured["payload"] = json.loads(request.content.decode("utf-8"))
        return httpx.Response(
            200,
            json={
                "message": {
                    "role": "assistant",
                    "content": _VALID_REQUEST_INFO_JSON,
                }
            },
        )

    client = httpx.Client(transport=httpx.MockTransport(handler))
    policy = build_ollama_scientist_policy(
        model="glm-5:cloud",
        client=client,
        base_url="http://127.0.0.1:11434/api/chat",
    )

    action = policy(
        _base_observation(),
        scenario="finance_trading",
        difficulty="medium",
    )

    assert action.action_type is ScientistActionType.REQUEST_INFO
    payload = captured["payload"]
    assert isinstance(payload, dict)
    assert payload["model"] == "glm-5:cloud"
    assert payload["stream"] is False
    assert payload["format"] == "json"
    assert payload["messages"][0]["role"] == "system"