File size: 46,170 Bytes
44ad484
 
 
 
c0072b1
 
44ad484
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a71b331
44ad484
 
0bfffbc
c0072b1
 
 
 
5f00812
c0072b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43d613a
c0072b1
 
 
 
 
 
 
 
 
 
0bfffbc
 
 
c0072b1
 
 
9d361f6
 
5f00812
9d361f6
 
 
 
 
 
 
43d613a
9d361f6
 
 
 
 
 
 
 
 
6aa62ca
 
 
 
 
5f00812
6aa62ca
 
 
7dec693
 
6aa62ca
 
 
 
 
 
43d613a
6aa62ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c0072b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f00812
 
 
c0072b1
 
 
 
 
 
 
 
 
 
 
 
43d613a
c0072b1
 
 
 
 
 
 
 
 
 
 
 
 
 
0bfffbc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f00812
 
 
0bfffbc
 
 
 
 
 
 
 
 
 
 
 
 
43d613a
0bfffbc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c0072b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dfba75c
c0072b1
5f00812
 
 
c0072b1
 
 
dfba75c
c0072b1
 
 
 
 
 
 
 
 
 
43d613a
dfba75c
c0072b1
 
 
 
 
 
 
 
 
 
dfba75c
c0072b1
 
 
862063b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f00812
 
 
862063b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43d613a
862063b
 
 
 
 
 
 
 
 
 
 
 
 
 
0bfffbc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f00812
 
 
0bfffbc
 
 
dfba75c
 
 
 
0bfffbc
 
 
 
 
 
 
 
 
 
43d613a
dfba75c
0bfffbc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dfba75c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f00812
 
 
dfba75c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43d613a
dfba75c
 
 
 
 
 
 
 
 
 
 
 
 
 
bad5fbe
acc2ffa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f00812
 
 
acc2ffa
 
 
 
 
 
bad5fbe
acc2ffa
 
 
bad5fbe
acc2ffa
 
 
 
 
 
 
 
 
 
43d613a
acc2ffa
 
 
 
 
 
 
bad5fbe
acc2ffa
 
bad5fbe
 
acc2ffa
 
 
5f00812
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bad5fbe
f09a362
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f00812
 
 
f09a362
 
 
 
 
 
bad5fbe
f09a362
 
 
 
 
bad5fbe
f09a362
 
 
 
 
bad5fbe
43d613a
f09a362
 
 
 
 
 
 
bad5fbe
f09a362
 
 
bad5fbe
 
 
f09a362
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f00812
 
 
f09a362
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43d613a
f09a362
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52d9109
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f00812
 
 
52d9109
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43d613a
52d9109
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f00812
 
 
52d9109
 
 
 
 
 
 
 
 
 
 
 
 
43d613a
52d9109
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f00812
 
 
52d9109
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43d613a
52d9109
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f09a362
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c0072b1
 
 
 
 
 
 
7dec693
 
 
 
 
 
c0072b1
 
 
 
 
 
 
 
 
 
 
dfba75c
c0072b1
5f00812
 
 
c0072b1
 
 
dfba75c
c0072b1
 
 
 
 
 
 
 
 
 
43d613a
dfba75c
c0072b1
 
 
 
 
 
 
 
 
 
dfba75c
7dec693
c0072b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f00812
 
 
c0072b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43d613a
c0072b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43d613a
c0072b1
 
 
 
 
 
 
 
 
 
 
 
 
44ad484
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f09a362
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44ad484
 
 
 
 
 
 
 
 
 
d474cf2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44ad484
 
 
 
 
 
 
 
 
 
 
 
 
c338c4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169

from langchain_core.messages import AIMessage, HumanMessage, ToolMessage
from langchain_core.tools import tool as tool_decorator

from lilith_agent.app import _build_tool_node, _cooldown_limit_for, _route_after_model, build_react_agent
from lilith_agent.config import Config


@tool_decorator
def echo_tool(text: str) -> str:
    """Echoes back the text."""
    return f"echoed: {text}"


def _ai_with_calls(calls):
    return AIMessage(content="", tool_calls=calls)


def test_router_goes_to_tools_when_tool_calls_present():
    state = {"messages": [_ai_with_calls([{"id": "1", "name": "echo_tool", "args": {"text": "hi"}}])]}
    assert _route_after_model(state) == "tools"


def test_router_ends_when_no_tool_calls():
    state = {"messages": [AIMessage(content="done")]}
    assert _route_after_model(state) == "extract_memory"


def test_graph_returns_fail_safe_answer_when_hard_cap_hits_near_recursion_limit(monkeypatch, tmp_path, capsys):
    class FakeModel:
        def __init__(self):
            self.calls = 0

        def bind_tools(self, tools, **kwargs):
            return self

        def invoke(self, messages):
            if "SYSTEM EMERGENCY OVERRIDE" in str(messages[0].content):
                return AIMessage(content="Final Answer: best effort answer")
            self.calls += 1
            return _ai_with_calls([
                {
                    "id": f"call-{self.calls}",
                    "name": "echo_tool",
                    "args": {"text": str(self.calls)},
                }
            ])

    fake_model = FakeModel()
    cfg = Config.from_env()
    cfg.recursion_limit = 4
    cfg.budget_hard_cap = 2
    cfg.budget_warn_at = 99
    cfg.compact_summarize = False
    monkeypatch.setenv("LILITH_HOME", str(tmp_path / ".lilith"))
    monkeypatch.setattr("lilith_agent.app.get_strong_model", lambda cfg: fake_model)
    monkeypatch.setattr("lilith_agent.app.get_cheap_model", lambda cfg: fake_model)
    monkeypatch.setattr("lilith_agent.tools.build_tools", lambda cfg: [echo_tool])
    monkeypatch.setattr("lilith_agent.memory.extract_and_compress_facts", lambda messages, model: None)

    graph = build_react_agent(cfg)
    result = graph.invoke(
        {"messages": [HumanMessage(content="answer this")], "iterations": 0, "todos": []},
        {"configurable": {"thread_id": "hard-cap-test"}},
    )

    captured = capsys.readouterr().out
    assert "[route] recursion threshold reached" in captured
    assert "[fail_safe] emergency override" in captured
    assert result["messages"][-1].content == "Final Answer: best effort answer"


def test_build_react_agent_prints_effective_recursion_limit(monkeypatch, tmp_path, capsys):
    class FakeModel:
        def bind_tools(self, tools, **kwargs):
            return self

    cfg = Config.from_env()
    cfg.recursion_limit = 50
    cfg.budget_hard_cap = 25
    cfg.compact_summarize = False
    monkeypatch.setenv("LILITH_HOME", str(tmp_path / ".lilith"))
    monkeypatch.setattr("lilith_agent.app.get_strong_model", lambda cfg: FakeModel())
    monkeypatch.setattr("lilith_agent.app.get_cheap_model", lambda cfg: FakeModel())
    monkeypatch.setattr("lilith_agent.tools.build_tools", lambda cfg: [echo_tool])

    build_react_agent(cfg)

    captured = capsys.readouterr().out
    assert "[graph] effective_recursion_limit=79 logical_recursion_limit=50 budget_hard_cap=25 headroom=4" in captured


def test_model_prompt_includes_youtube_fallback_strategy(monkeypatch, tmp_path):
    class FakeModel:
        def __init__(self):
            self.system_prompt = ""

        def bind_tools(self, tools, **kwargs):
            return self

        def invoke(self, messages):
            if not self.system_prompt:
                self.system_prompt = str(messages[0].content)
            return AIMessage(content="Final Answer: inspected")

    fake_model = FakeModel()
    cfg = Config.from_env()
    cfg.compact_summarize = False
    monkeypatch.setenv("LILITH_HOME", str(tmp_path / ".lilith"))
    monkeypatch.setattr("lilith_agent.app.get_strong_model", lambda cfg: fake_model)
    monkeypatch.setattr("lilith_agent.app.get_cheap_model", lambda cfg: fake_model)
    monkeypatch.setattr("lilith_agent.tools.build_tools", lambda cfg: [echo_tool])
    monkeypatch.setattr("lilith_agent.memory.extract_and_compress_facts", lambda messages, model: None)

    graph = build_react_agent(cfg)
    graph.invoke(
        {"messages": [HumanMessage(content="What happens in https://www.youtube.com/watch?v=abcdefghijk?")], "iterations": 0, "todos": []},
        {"configurable": {"thread_id": "youtube-fallback-prompt-test"}},
    )

    prompt = fake_model.system_prompt.lower()
    assert "youtube fallback strategy" in prompt
    assert "video id" in prompt
    assert "transcript" in prompt
    assert "do not repeatedly retry" in prompt


def test_fail_safe_uses_unbound_model_to_prevent_more_tool_calls(monkeypatch, tmp_path):
    class FakeBoundModel:
        def __init__(self):
            self.calls = 0

        def invoke(self, messages):
            self.calls += 1
            return _ai_with_calls([
                {
                    "id": f"bound-call-{self.calls}",
                    "name": "echo_tool",
                    "args": {"text": str(self.calls)},
                }
            ])

    class FakeModel:
        def __init__(self):
            self.bound = FakeBoundModel()

        def bind_tools(self, tools, **kwargs):
            if kwargs.get("tool_choice") == "none":
                return self
            return self.bound

        def invoke(self, messages):
            return AIMessage(content="Final Answer: unbound best effort")

    fake_model = FakeModel()
    cfg = Config.from_env()
    cfg.recursion_limit = 4
    cfg.budget_hard_cap = 1
    cfg.budget_warn_at = 99
    cfg.compact_summarize = False
    monkeypatch.setenv("LILITH_HOME", str(tmp_path / ".lilith"))
    monkeypatch.setattr("lilith_agent.app.get_strong_model", lambda cfg: fake_model)
    monkeypatch.setattr("lilith_agent.app.get_cheap_model", lambda cfg: fake_model)
    monkeypatch.setattr("lilith_agent.tools.build_tools", lambda cfg: [echo_tool])
    monkeypatch.setattr("lilith_agent.memory.extract_and_compress_facts", lambda messages, model: None)

    graph = build_react_agent(cfg)
    result = graph.invoke(
        {"messages": [HumanMessage(content="answer this")], "iterations": 0, "todos": []},
        {"configurable": {"thread_id": "unbound-fail-safe-test"}},
    )

    assert result["messages"][-1].content == "Final Answer: unbound best effort"
    assert not getattr(result["messages"][-1], "tool_calls", None)


def test_fail_safe_prompt_reinforces_original_question_contract(monkeypatch, tmp_path):
    class FakeBoundModel:
        def invoke(self, messages):
            return _ai_with_calls([
                {
                    "id": "bound-call",
                    "name": "echo_tool",
                    "args": {"text": "intermediate"},
                }
            ])

    class FakeModel:
        def __init__(self):
            self.bound = FakeBoundModel()
            self.fail_safe_prompt = ""

        def bind_tools(self, tools, **kwargs):
            if kwargs.get("tool_choice") == "none":
                return self
            return self.bound

        def invoke(self, messages):
            self.fail_safe_prompt = str(messages[0].content)
            return AIMessage(content="Final Answer: best effort")

    fake_model = FakeModel()
    cfg = Config.from_env()
    cfg.recursion_limit = 4
    cfg.budget_hard_cap = 1
    cfg.budget_warn_at = 99
    cfg.compact_summarize = False
    monkeypatch.setenv("LILITH_HOME", str(tmp_path / ".lilith"))
    monkeypatch.setattr("lilith_agent.app.get_strong_model", lambda cfg: fake_model)
    monkeypatch.setattr("lilith_agent.app.get_cheap_model", lambda cfg: fake_model)
    monkeypatch.setattr("lilith_agent.tools.build_tools", lambda cfg: [echo_tool])
    monkeypatch.setattr("lilith_agent.memory.extract_and_compress_facts", lambda messages, model: None)

    graph = build_react_agent(cfg)
    graph.invoke(
        {"messages": [HumanMessage(content="What country corresponds to this capital?")], "iterations": 0, "todos": []},
        {"configurable": {"thread_id": "fail-safe-contract-prompt-test"}},
    )

    prompt = fake_model.fail_safe_prompt.lower()
    assert "original question" in prompt
    assert "not an intermediate" in prompt
    assert "bare final answer" in prompt


def test_supervisor_nudges_agent_to_answer_when_evidence_is_enough(monkeypatch, tmp_path):
    class FakeBoundModel:
        def __init__(self):
            self.calls = 0

        def invoke(self, messages):
            self.calls += 1
            if any("SUPERVISOR" in str(getattr(m, "content", "")) for m in messages):
                return AIMessage(content="Final Answer: backtick")
            return _ai_with_calls([
                {
                    "id": f"call-{self.calls}",
                    "name": "echo_tool",
                    "args": {"text": "Add `: 'For penguins\\n'"},
                }
            ])

    class FakeStrongModel:
        def __init__(self):
            self.bound = FakeBoundModel()
            self.supervisor_calls = 0

        def bind_tools(self, tools, **kwargs):
            if kwargs.get("tool_choice") == "none":
                return self
            return self.bound

        def invoke(self, messages):
            self.supervisor_calls += 1
            return AIMessage(content='{"status":"nudge","best_answer":"backtick","guidance":"You have verified the answer. Stop and answer backtick."}')

    strong = FakeStrongModel()
    cfg = Config.from_env()
    cfg.recursion_limit = 10
    cfg.budget_hard_cap = 99
    cfg.budget_warn_at = 99
    cfg.compact_summarize = False
    monkeypatch.setenv("LILITH_HOME", str(tmp_path / ".lilith"))
    monkeypatch.setattr("lilith_agent.app._SUPERVISOR_MIN_TOOL_CALLS", 1, raising=False)
    monkeypatch.setattr("lilith_agent.app.get_strong_model", lambda cfg, thinking=True: strong)
    monkeypatch.setattr("lilith_agent.app.get_cheap_model", lambda cfg: object())
    monkeypatch.setattr("lilith_agent.tools.build_tools", lambda cfg: [echo_tool])
    monkeypatch.setattr("lilith_agent.memory.extract_and_compress_facts", lambda messages, model: None)

    graph = build_react_agent(cfg)
    result = graph.invoke(
        {"messages": [HumanMessage(content="Unlambda question")], "iterations": 0, "todos": []},
        {"configurable": {"thread_id": "supervisor-nudge-test"}},
    )

    assert result["messages"][-1].content == "Final Answer: backtick"
    assert strong.supervisor_calls == 1
    assert strong.bound.calls == 2


def test_supervisor_uses_extra_strong_model_not_cheap_model(monkeypatch, tmp_path):
    class FakeBoundModel:
        def __init__(self):
            self.calls = 0

        def invoke(self, messages):
            self.calls += 1
            if any("SUPERVISOR" in str(getattr(m, "content", "")) for m in messages):
                return AIMessage(content="Final Answer: backtick")
            return _ai_with_calls([
                {
                    "id": f"call-{self.calls}",
                    "name": "echo_tool",
                    "args": {"text": "evidence"},
                }
            ])

    class FakeExtraStrongModel:
        def __init__(self):
            self.bound = FakeBoundModel()
            self.supervisor_calls = 0

        def bind_tools(self, tools, **kwargs):
            if kwargs.get("tool_choice") == "none":
                return self
            return self.bound

        def invoke(self, messages):
            self.supervisor_calls += 1
            return AIMessage(content='{"status":"nudge","best_answer":"backtick","guidance":"Stop and answer backtick."}')

    strong = FakeExtraStrongModel()

    def cheap_should_not_be_used(cfg):
        raise AssertionError("supervisor should use extra strong model, not cheap model")

    cfg = Config.from_env()
    cfg.recursion_limit = 10
    cfg.budget_hard_cap = 99
    cfg.budget_warn_at = 99
    cfg.compact_summarize = False
    monkeypatch.setenv("LILITH_HOME", str(tmp_path / ".lilith"))
    monkeypatch.setattr("lilith_agent.app._SUPERVISOR_MIN_TOOL_CALLS", 1, raising=False)
    monkeypatch.setattr("lilith_agent.app.get_strong_model", lambda cfg, thinking=True: strong)
    monkeypatch.setattr("lilith_agent.app.get_cheap_model", cheap_should_not_be_used)
    monkeypatch.setattr("lilith_agent.tools.build_tools", lambda cfg: [echo_tool])
    monkeypatch.setattr("lilith_agent.memory.extract_and_compress_facts", lambda messages, model: None)

    graph = build_react_agent(cfg)
    result = graph.invoke(
        {"messages": [HumanMessage(content="Unlambda question")], "iterations": 0, "todos": []},
        {"configurable": {"thread_id": "supervisor-extra-strong-test"}},
    )

    assert result["messages"][-1].content == "Final Answer: backtick"
    assert strong.supervisor_calls == 1


def test_supervisor_finalizer_prompt_reinforces_original_question_contract(monkeypatch, tmp_path):
    class FakeBoundModel:
        def invoke(self, messages):
            return _ai_with_calls([
                {
                    "id": "call",
                    "name": "echo_tool",
                    "args": {"text": "evidence"},
                }
            ])

    class FakeStrongModel:
        def __init__(self):
            self.bound = FakeBoundModel()
            self.finalizer_prompt = ""

        def bind_tools(self, tools, **kwargs):
            if kwargs.get("tool_choice") == "none":
                return self
            return self.bound

        def invoke(self, messages):
            prompt = str(messages[0].content)
            if "SUPERVISOR FINALIZER" in prompt:
                self.finalizer_prompt = prompt
                return AIMessage(content="Final Answer: final")
            return AIMessage(content='{"status":"finalize","best_answer":"","guidance":"Existing evidence is enough."}')

    strong = FakeStrongModel()
    cfg = Config.from_env()
    cfg.recursion_limit = 10
    cfg.budget_hard_cap = 99
    cfg.budget_warn_at = 99
    cfg.compact_summarize = False
    monkeypatch.setenv("LILITH_HOME", str(tmp_path / ".lilith"))
    monkeypatch.setattr("lilith_agent.app._SUPERVISOR_MIN_TOOL_CALLS", 1, raising=False)
    monkeypatch.setattr("lilith_agent.app.get_strong_model", lambda cfg, thinking=True: strong)
    monkeypatch.setattr("lilith_agent.app.get_cheap_model", lambda cfg: object())
    monkeypatch.setattr("lilith_agent.tools.build_tools", lambda cfg: [echo_tool])
    monkeypatch.setattr("lilith_agent.memory.extract_and_compress_facts", lambda messages, model: None)

    graph = build_react_agent(cfg)
    graph.invoke(
        {"messages": [HumanMessage(content="What final entity answers the original question?")], "iterations": 0, "todos": []},
        {"configurable": {"thread_id": "supervisor-finalizer-contract-prompt-test"}},
    )

    prompt = strong.finalizer_prompt.lower()
    assert "original question" in prompt
    assert "not an intermediate" in prompt
    assert "bare final answer" in prompt


def test_supervisor_finalizer_rejects_unknown_best_answer_and_forces_best_guess(monkeypatch, tmp_path):
    class FakeBoundModel:
        def invoke(self, messages):
            return _ai_with_calls([
                {
                    "id": "call",
                    "name": "echo_tool",
                    "args": {"text": "evidence"},
                }
            ])

    class FakeStrongModel:
        def __init__(self):
            self.bound = FakeBoundModel()
            self.finalizer_calls = 0

        def bind_tools(self, tools, **kwargs):
            if kwargs.get("tool_choice") == "none":
                return self
            return self.bound

        def invoke(self, messages):
            prompt = str(messages[0].content)
            if "SUPERVISOR FINALIZER" in prompt:
                self.finalizer_calls += 1
                return AIMessage(content="Final Answer: best guess")
            return AIMessage(content='{"status":"finalize","best_answer":"unknown","guidance":"Looping; make a best guess."}')

    strong = FakeStrongModel()
    cfg = Config.from_env()
    cfg.recursion_limit = 10
    cfg.budget_hard_cap = 99
    cfg.budget_warn_at = 99
    cfg.compact_summarize = False
    monkeypatch.setenv("LILITH_HOME", str(tmp_path / ".lilith"))
    monkeypatch.setattr("lilith_agent.app._SUPERVISOR_MIN_TOOL_CALLS", 1, raising=False)
    monkeypatch.setattr("lilith_agent.app.get_strong_model", lambda cfg, thinking=True: strong)
    monkeypatch.setattr("lilith_agent.app.get_cheap_model", lambda cfg: object())
    monkeypatch.setattr("lilith_agent.tools.build_tools", lambda cfg: [echo_tool])
    monkeypatch.setattr("lilith_agent.memory.extract_and_compress_facts", lambda messages, model: None)

    graph = build_react_agent(cfg)
    result = graph.invoke(
        {"messages": [HumanMessage(content="Unlambda question")], "iterations": 0, "todos": []},
        {"configurable": {"thread_id": "supervisor-unknown-best-answer-test"}},
    )

    assert result["messages"][-1].content == "Final Answer: best guess"
    assert strong.finalizer_calls == 1


def test_supervisor_finalizes_even_with_placeholder_if_requested(monkeypatch, tmp_path):
    class FakeBoundModel:
        def __init__(self):
            self.calls = 0

        def invoke(self, messages):
            self.calls += 1
            return _ai_with_calls([
                {
                    "id": f"call-{self.calls}",
                    "name": "echo_tool",
                    "args": {"text": "partial evidence"},
                }
            ])

    class FakeStrongModel:
        def __init__(self):
            self.bound = FakeBoundModel()
            self.supervisor_calls = 0
            self.finalizer_calls = 0

        def bind_tools(self, tools, **kwargs):
            if kwargs.get("tool_choice") == "none":
                return self
            return self.bound

        def invoke(self, messages):
            prompt = str(messages[0].content)
            if "SUPERVISOR FINALIZER" in prompt:
                self.finalizer_calls += 1
                return AIMessage(content="Final Answer: finalizer output")
            self.supervisor_calls += 1
            if self.supervisor_calls == 1:
                return AIMessage(content='{"status":"nudge","best_answer":"","guidance":"Use the evidence to make a best guess."}')
            # On second call, it asks to finalize but with a placeholder answer. The code should allow finalization.
            return AIMessage(content='{"status":"finalize","best_answer":"Unknown","guidance":"You were already nudged. Provide your final answer based on the best available information."}')

    strong = FakeStrongModel()
    cfg = Config.from_env()
    cfg.recursion_limit = 12
    cfg.budget_hard_cap = 99
    cfg.budget_warn_at = 99
    cfg.compact_summarize = False
    monkeypatch.setenv("LILITH_HOME", str(tmp_path / ".lilith"))
    monkeypatch.setattr("lilith_agent.app._SUPERVISOR_MIN_TOOL_CALLS", 1, raising=False)
    monkeypatch.setattr("lilith_agent.app.get_strong_model", lambda cfg, thinking=True: strong)
    monkeypatch.setattr("lilith_agent.app.get_cheap_model", lambda cfg: object())
    monkeypatch.setattr("lilith_agent.tools.build_tools", lambda cfg: [echo_tool])
    monkeypatch.setattr("lilith_agent.memory.extract_and_compress_facts", lambda messages, model: None)

    graph = build_react_agent(cfg)
    result = graph.invoke(
        {"messages": [HumanMessage(content="Question requiring a concrete answer")], "iterations": 0, "todos": []},
        {"configurable": {"thread_id": "supervisor-finalize-after-nudge-test"}},
    )

    assert result["messages"][-1].content == "Final Answer: finalizer output"
    assert strong.finalizer_calls == 1
    assert strong.supervisor_calls == 2


def test_supervisor_finalizer_forbids_tool_calls_to_prevent_markup_leak(monkeypatch, tmp_path):
    # DeepSeek thinking-off still emits raw tool-call markup when invoked unbound
    # against a tool-laden history. The finalizer must bind tools with
    # tool_choice="none" so the model is forced to answer in plain text.
    dsml_leak = '<||DSML||tool_calls><||DSML||invoke name="web_search"></||DSML||invoke>'

    class FakeBoundModel:
        def invoke(self, messages):
            return _ai_with_calls([
                {"id": "call", "name": "echo_tool", "args": {"text": "evidence"}}
            ])

    class FakeFinalizerBound:
        def invoke(self, messages):
            return AIMessage(content="Final Answer: synthesized report")

    class FakeStrongModel:
        def __init__(self):
            self.bound = FakeBoundModel()
            self.finalizer_tool_choice = None

        def bind_tools(self, tools, **kwargs):
            if kwargs.get("tool_choice") == "none":
                self.finalizer_tool_choice = "none"
                return FakeFinalizerBound()
            return self.bound

        def invoke(self, messages):
            prompt = str(messages[0].content)
            if "SUPERVISOR FINALIZER" in prompt:
                # Reached only if the finalizer wrongly invokes the unbound model.
                return AIMessage(content=dsml_leak)
            return AIMessage(content='{"status":"finalize","best_answer":"","guidance":"Evidence is enough."}')

    strong = FakeStrongModel()
    cfg = Config.from_env()
    cfg.recursion_limit = 10
    cfg.budget_hard_cap = 99
    cfg.budget_warn_at = 99
    cfg.compact_summarize = False
    monkeypatch.setenv("LILITH_HOME", str(tmp_path / ".lilith"))
    monkeypatch.setattr("lilith_agent.app._SUPERVISOR_MIN_TOOL_CALLS", 1, raising=False)
    monkeypatch.setattr("lilith_agent.app.get_strong_model", lambda cfg, thinking=True: strong)
    monkeypatch.setattr("lilith_agent.app.get_cheap_model", lambda cfg: object())
    monkeypatch.setattr("lilith_agent.tools.build_tools", lambda cfg: [echo_tool])
    monkeypatch.setattr("lilith_agent.memory.extract_and_compress_facts", lambda messages, model: None)

    graph = build_react_agent(cfg)
    result = graph.invoke(
        {"messages": [HumanMessage(content="Research the competitor landscape.")], "iterations": 0, "todos": []},
        {"configurable": {"thread_id": "supervisor-finalizer-markup-leak-test"}},
    )

    final = result["messages"][-1].content
    assert "DSML" not in final
    assert final == "Final Answer: synthesized report"
    assert strong.finalizer_tool_choice == "none"


def test_supervisor_forces_finalize_after_max_nudges(monkeypatch, tmp_path):
    class FakeBoundModel:
        def __init__(self):
            self.calls = 0

        def invoke(self, messages):
            self.calls += 1
            return _ai_with_calls([
                {
                    "id": f"call-{self.calls}",
                    "name": "echo_tool",
                    "args": {"text": "partial evidence"},
                }
            ])

    class FakeStrongModel:
        def __init__(self):
            self.bound = FakeBoundModel()
            self.supervisor_calls = 0
            self.finalizer_calls = 0

        def bind_tools(self, tools, **kwargs):
            if kwargs.get("tool_choice") == "none":
                return self
            return self.bound

        def invoke(self, messages):
            prompt = str(messages[0].content)
            if "SUPERVISOR FINALIZER" in prompt:
                self.finalizer_calls += 1
                return AIMessage(content="Final Answer: max nudges forced this")
            self.supervisor_calls += 1
            return AIMessage(content='{"status":"nudge","best_answer":"concrete candidate","guidance":"Check one more constraint before final answer."}')

    strong = FakeStrongModel()
    cfg = Config.from_env()
    cfg.recursion_limit = 20
    cfg.budget_hard_cap = 99
    cfg.budget_warn_at = 99
    cfg.compact_summarize = False
    monkeypatch.setenv("LILITH_HOME", str(tmp_path / ".lilith"))
    monkeypatch.setattr("lilith_agent.app._SUPERVISOR_MIN_TOOL_CALLS", 1, raising=False)
    monkeypatch.setattr("lilith_agent.app._SUPERVISOR_MAX_NUDGES", 5, raising=False)
    monkeypatch.setattr("lilith_agent.app.get_strong_model", lambda cfg, thinking=True: strong)
    monkeypatch.setattr("lilith_agent.app.get_cheap_model", lambda cfg: object())
    monkeypatch.setattr("lilith_agent.tools.build_tools", lambda cfg: [echo_tool])
    monkeypatch.setattr("lilith_agent.memory.extract_and_compress_facts", lambda messages, model: None)

    graph = build_react_agent(cfg)
    result = graph.invoke(
        {"messages": [HumanMessage(content="Question requiring more checking")], "iterations": 0, "todos": []},
        {"configurable": {"thread_id": "supervisor-max-nudges-test"}},
    )

    assert strong.finalizer_calls == 0
    assert result["messages"][-1].content == "Final Answer: concrete candidate"
    assert strong.supervisor_calls == 5
    assert result["supervisor_decision"] == "finalize"


def test_final_answer_gets_supervisor_review_and_can_be_returned_for_revision(monkeypatch, tmp_path):
    class FakeBoundModel:
        def __init__(self):
            self.calls = 0

        def invoke(self, messages):
            self.calls += 1
            if any("FINAL ANSWER REVIEW FAILED" in str(getattr(m, "content", "")) for m in messages):
                return AIMessage(content="Final Answer: corrected answer")
            return AIMessage(content="Final Answer: wrong answer")

    class FakeStrongModel:
        def __init__(self):
            self.bound = FakeBoundModel()
            self.review_calls = 0

        def bind_tools(self, tools, **kwargs):
            if kwargs.get("tool_choice") == "none":
                return self
            return self.bound

        def invoke(self, messages):
            prompt = str(messages[0].content)
            if "FINAL ANSWER REVIEW" in prompt:
                self.review_calls += 1
                if self.review_calls == 1:
                    return AIMessage(content='{"status":"nudge","best_answer":"","guidance":"The proposed answer violates a constraint; fix it."}')
                return AIMessage(content='{"status":"finalize","best_answer":"corrected answer","guidance":"Approved."}')
            return AIMessage(content='{"status":"continue","best_answer":"","guidance":""}')

    strong = FakeStrongModel()
    cfg = Config.from_env()
    cfg.recursion_limit = 10
    cfg.budget_hard_cap = 99
    cfg.budget_warn_at = 99
    cfg.compact_summarize = False
    monkeypatch.setenv("LILITH_HOME", str(tmp_path / ".lilith"))
    monkeypatch.setattr("lilith_agent.app.get_strong_model", lambda cfg, thinking=True: strong)
    monkeypatch.setattr("lilith_agent.app.get_cheap_model", lambda cfg: object())
    monkeypatch.setattr("lilith_agent.tools.build_tools", lambda cfg: [])
    monkeypatch.setattr("lilith_agent.memory.extract_and_compress_facts", lambda messages, model: None)

    graph = build_react_agent(cfg)
    result = graph.invoke(
        {"messages": [HumanMessage(content="Question with constraint")], "iterations": 0, "todos": []},
        {"configurable": {"thread_id": "final-answer-review-revision-test"}},
    )

    assert strong.review_calls == 2
    assert "Final Answer: corrected answer" in result["messages"][-1].content
    assert all("wrong answer" != getattr(m, "content", "") for m in result["messages"][-1:])


def test_fail_safe_falls_back_to_supervisor_best_answer_when_empty(monkeypatch, tmp_path):
    """fail_safe model returning empty content must not propagate; supervisor_best_answer wins."""

    class FakeBoundModel:
        def __init__(self):
            self.calls = 0

        def invoke(self, messages):
            self.calls += 1
            return _ai_with_calls([
                {
                    "id": f"call-{self.calls}",
                    "name": "echo_tool",
                    "args": {"text": str(self.calls)},
                }
            ])

    class FakeStrongModel:
        def __init__(self):
            self.bound = FakeBoundModel()
            self.fail_safe_calls = 0
            self.supervisor_calls = 0

        def bind_tools(self, tools, **kwargs):
            if kwargs.get("tool_choice") == "none":
                return self
            return self.bound

        def invoke(self, messages):
            prompt = str(messages[0].content)
            if "EMERGENCY OVERRIDE" in prompt:
                self.fail_safe_calls += 1
                return AIMessage(content="")
            self.supervisor_calls += 1
            return AIMessage(content='{"status":"nudge","best_answer":"backtick","guidance":"Stop and answer backtick."}')

    strong = FakeStrongModel()
    cfg = Config.from_env()
    cfg.recursion_limit = 4
    cfg.budget_hard_cap = 2
    cfg.budget_warn_at = 99
    cfg.compact_summarize = False
    monkeypatch.setenv("LILITH_HOME", str(tmp_path / ".lilith"))
    monkeypatch.setattr("lilith_agent.app._SUPERVISOR_MIN_TOOL_CALLS", 1, raising=False)
    monkeypatch.setattr("lilith_agent.app.get_strong_model", lambda cfg, thinking=True: strong)
    monkeypatch.setattr("lilith_agent.app.get_cheap_model", lambda cfg: object())
    monkeypatch.setattr("lilith_agent.tools.build_tools", lambda cfg: [echo_tool])
    monkeypatch.setattr("lilith_agent.memory.extract_and_compress_facts", lambda messages, model: None)

    graph = build_react_agent(cfg)
    result = graph.invoke(
        {"messages": [HumanMessage(content="Question")], "iterations": 0, "todos": []},
        {"configurable": {"thread_id": "fail-safe-best-answer-test"}},
    )

    last = result["messages"][-1]
    assert last.content
    assert "Final Answer:" in last.content
    assert "backtick" in last.content


def test_fail_safe_never_returns_empty_answer_without_best_answer(monkeypatch, tmp_path):
    """No supervisor_best_answer, fail_safe model empty: still produce non-empty descriptive Final Answer."""

    class FakeBoundModel:
        def __init__(self):
            self.calls = 0

        def invoke(self, messages):
            self.calls += 1
            return _ai_with_calls([
                {
                    "id": f"call-{self.calls}",
                    "name": "echo_tool",
                    "args": {"text": str(self.calls)},
                }
            ])

    class FakeStrongModel:
        def __init__(self):
            self.bound = FakeBoundModel()

        def bind_tools(self, tools, **kwargs):
            if kwargs.get("tool_choice") == "none":
                return self
            return self.bound

        def invoke(self, messages):
            return AIMessage(content="")

    strong = FakeStrongModel()
    cfg = Config.from_env()
    cfg.recursion_limit = 4
    cfg.budget_hard_cap = 2
    cfg.budget_warn_at = 99
    cfg.compact_summarize = False
    monkeypatch.setenv("LILITH_HOME", str(tmp_path / ".lilith"))
    monkeypatch.setattr("lilith_agent.app._SUPERVISOR_MIN_TOOL_CALLS", 99, raising=False)
    monkeypatch.setattr("lilith_agent.app.get_strong_model", lambda cfg, thinking=True: strong)
    monkeypatch.setattr("lilith_agent.app.get_cheap_model", lambda cfg: object())
    monkeypatch.setattr("lilith_agent.tools.build_tools", lambda cfg: [echo_tool])
    monkeypatch.setattr("lilith_agent.memory.extract_and_compress_facts", lambda messages, model: None)

    graph = build_react_agent(cfg)
    result = graph.invoke(
        {"messages": [HumanMessage(content="Question")], "iterations": 0, "todos": []},
        {"configurable": {"thread_id": "fail-safe-default-answer-test"}},
    )

    last = result["messages"][-1]
    content = str(getattr(last, "content", ""))
    assert content.strip(), "fail_safe must never propagate an empty answer"
    assert "Final Answer:" in content


def test_supervisor_review_auto_approves_after_fail_safe(monkeypatch, tmp_path):
    """fail_safe -> supervisor_review must auto-approve (no infinite loop back to model)."""

    class FakeBoundModel:
        def __init__(self):
            self.calls = 0

        def invoke(self, messages):
            self.calls += 1
            return _ai_with_calls([
                {
                    "id": f"call-{self.calls}",
                    "name": "echo_tool",
                    "args": {"text": str(self.calls)},
                }
            ])

    class FakeStrongModel:
        def __init__(self):
            self.bound = FakeBoundModel()
            self.review_calls = 0

        def bind_tools(self, tools, **kwargs):
            if kwargs.get("tool_choice") == "none":
                return self
            return self.bound

        def invoke(self, messages):
            prompt = str(messages[0].content)
            if "EMERGENCY OVERRIDE" in prompt:
                return AIMessage(content="Final Answer: best effort")
            if "FINAL ANSWER REVIEW" in prompt:
                self.review_calls += 1
                return AIMessage(content='{"status":"nudge","best_answer":"","guidance":"reject"}')
            return AIMessage(content='{"status":"continue","best_answer":"","guidance":""}')

    strong = FakeStrongModel()
    cfg = Config.from_env()
    cfg.recursion_limit = 4
    cfg.budget_hard_cap = 2
    cfg.budget_warn_at = 99
    cfg.compact_summarize = False
    monkeypatch.setenv("LILITH_HOME", str(tmp_path / ".lilith"))
    monkeypatch.setattr("lilith_agent.app._SUPERVISOR_MIN_TOOL_CALLS", 99, raising=False)
    monkeypatch.setattr("lilith_agent.app.get_strong_model", lambda cfg, thinking=True: strong)
    monkeypatch.setattr("lilith_agent.app.get_cheap_model", lambda cfg: object())
    monkeypatch.setattr("lilith_agent.tools.build_tools", lambda cfg: [echo_tool])
    monkeypatch.setattr("lilith_agent.memory.extract_and_compress_facts", lambda messages, model: None)

    graph = build_react_agent(cfg)
    result = graph.invoke(
        {"messages": [HumanMessage(content="Question")], "iterations": 0, "todos": []},
        {"configurable": {"thread_id": "fail-safe-review-no-loop-test"}},
    )

    last = result["messages"][-1]
    assert "Final Answer: best effort" in str(getattr(last, "content", ""))
    assert strong.review_calls == 0


def test_tool_node_invokes_tool_successfully():
    node = _build_tool_node([echo_tool])
    state = {"messages": [
        HumanMessage(content="say hi"),
        _ai_with_calls([{"id": "1", "name": "echo_tool", "args": {"text": "hi"}}]),
    ]}

    out = node(state)
    assert len(out["messages"]) == 1
    msg = out["messages"][0]
    assert isinstance(msg, ToolMessage)
    assert msg.tool_call_id == "1"
    assert "echoed: hi" in msg.content


def test_supervisor_finalizes_when_agent_ignores_prior_nudge(monkeypatch, tmp_path):
    class FakeBoundModel:
        def __init__(self):
            self.calls = 0

        def invoke(self, messages):
            self.calls += 1
            sup_count = sum(
                1 for m in messages
                if "SUPERVISOR:" in str(getattr(m, "content", ""))
            )
            if sup_count >= 2:
                return AIMessage(content="Final Answer: backtick")
            return _ai_with_calls([
                {
                    "id": f"call-{self.calls}",
                    "name": "echo_tool",
                    "args": {"text": str(self.calls)},
                }
            ])

    class FakeStrongModel:
        def __init__(self):
            self.bound = FakeBoundModel()
            self.supervisor_calls = 0

        def bind_tools(self, tools, **kwargs):
            if kwargs.get("tool_choice") == "none":
                return self
            return self.bound

        def invoke(self, messages):
            self.supervisor_calls += 1
            return AIMessage(content='{"status":"nudge","best_answer":"backtick","guidance":"Stop. Existing evidence supports backtick."}')

    strong = FakeStrongModel()
    cfg = Config.from_env()
    cfg.recursion_limit = 12
    cfg.budget_hard_cap = 99
    cfg.budget_warn_at = 99
    cfg.compact_summarize = False
    monkeypatch.setenv("LILITH_HOME", str(tmp_path / ".lilith"))
    monkeypatch.setattr("lilith_agent.app._SUPERVISOR_MIN_TOOL_CALLS", 1, raising=False)
    monkeypatch.setattr("lilith_agent.app.get_strong_model", lambda cfg, thinking=True: strong)
    monkeypatch.setattr("lilith_agent.app.get_cheap_model", lambda cfg: object())
    monkeypatch.setattr("lilith_agent.tools.build_tools", lambda cfg: [echo_tool])
    monkeypatch.setattr("lilith_agent.memory.extract_and_compress_facts", lambda messages, model: None)

    graph = build_react_agent(cfg)
    result = graph.invoke(
        {"messages": [HumanMessage(content="Unlambda question")], "iterations": 0, "todos": []},
        {"configurable": {"thread_id": "supervisor-finalize-test"}},
    )

    assert result["messages"][-1].content == "Final Answer: backtick"
    assert strong.supervisor_calls == 2
    assert strong.bound.calls == 3


def test_supervisor_overhead_leaves_room_for_hard_cap_fail_safe(monkeypatch, tmp_path):
    class FakeBoundModel:
        def __init__(self):
            self.calls = 0

        def invoke(self, messages):
            self.calls += 1
            return _ai_with_calls([
                {
                    "id": f"call-{self.calls}",
                    "name": "echo_tool",
                    "args": {"text": str(self.calls)},
                }
            ])

    class FakeStrongModel:
        def __init__(self):
            self.bound = FakeBoundModel()

        def bind_tools(self, tools, **kwargs):
            if kwargs.get("tool_choice") == "none":
                return self
            return self.bound

        def invoke(self, messages):
            return AIMessage(content="Final Answer: hard cap fallback")

    class FakeSupervisorModel:
        def invoke(self, messages):
            return AIMessage(content='{"status":"continue"}')

    strong = FakeStrongModel()
    cfg = Config.from_env()
    cfg.recursion_limit = 8
    cfg.budget_hard_cap = 5
    cfg.budget_warn_at = 99
    cfg.compact_summarize = False
    monkeypatch.setenv("LILITH_HOME", str(tmp_path / ".lilith"))
    monkeypatch.setattr("lilith_agent.app._SUPERVISOR_MIN_TOOL_CALLS", 1, raising=False)
    monkeypatch.setattr("lilith_agent.app.get_strong_model", lambda cfg, thinking=True: strong)
    monkeypatch.setattr("lilith_agent.app.get_cheap_model", lambda cfg: FakeSupervisorModel())
    monkeypatch.setattr("lilith_agent.tools.build_tools", lambda cfg: [echo_tool])
    monkeypatch.setattr("lilith_agent.memory.extract_and_compress_facts", lambda messages, model: None)

    graph = build_react_agent(cfg)
    result = graph.invoke(
        {"messages": [HumanMessage(content="force hard cap")], "iterations": 0, "todos": []},
        {"configurable": {"thread_id": "supervisor-hard-cap-headroom-test"}},
    )

    assert result["messages"][-1].content == "Final Answer: hard cap fallback"


def test_supervisor_overhead_leaves_room_for_iteration_fail_safe(monkeypatch, tmp_path):
    class FakeBoundModel:
        def invoke(self, messages):
            return _ai_with_calls([
                {
                    "id": "call",
                    "name": "echo_tool",
                    "args": {"text": "loop"},
                }
            ])

    class FakeStrongModel:
        def bind_tools(self, tools):
            return FakeBoundModel()

        def invoke(self, messages):
            return AIMessage(content="Final Answer: iteration fallback")

    class FakeSupervisorModel:
        def invoke(self, messages):
            return AIMessage(content='{"status":"continue"}')

    cfg = Config.from_env()
    cfg.recursion_limit = 5
    cfg.budget_hard_cap = 99
    cfg.budget_warn_at = 99
    cfg.compact_summarize = False
    monkeypatch.setenv("LILITH_HOME", str(tmp_path / ".lilith"))
    monkeypatch.setattr("lilith_agent.app._SUPERVISOR_MIN_TOOL_CALLS", 1, raising=False)
    monkeypatch.setattr("lilith_agent.app.get_strong_model", lambda cfg: FakeStrongModel())
    monkeypatch.setattr("lilith_agent.app.get_cheap_model", lambda cfg: FakeSupervisorModel())
    monkeypatch.setattr("lilith_agent.tools.build_tools", lambda cfg: [echo_tool])
    monkeypatch.setattr("lilith_agent.memory.extract_and_compress_facts", lambda messages, model: None)

    graph = build_react_agent(cfg)
    result = graph.invoke(
        {"messages": [HumanMessage(content="force iteration cap")], "iterations": 0, "todos": []},
        {"configurable": {"thread_id": "supervisor-iteration-headroom-test"}},
    )

    assert result["messages"][-1].content == "Final Answer: iteration fallback"


def test_tool_node_invokes_tool_and_returns_tool_message():
    node = _build_tool_node([echo_tool])
    state = {"messages": [
        HumanMessage(content="say hi"),
        _ai_with_calls([{"id": "1", "name": "echo_tool", "args": {"text": "hi"}}]),
    ]}

    out = node(state)
    assert len(out["messages"]) == 1
    msg = out["messages"][0]
    assert isinstance(msg, ToolMessage)
    assert msg.tool_call_id == "1"
    assert "echoed: hi" in msg.content


def test_tool_node_dedups_repeat_tool_call_without_invoking():
    calls = 0

    @tool_decorator
    def counting_tool(x: str) -> str:
        """Counting tool."""
        nonlocal calls
        calls += 1
        return f"ran {calls}"

    node = _build_tool_node([counting_tool])

    # History: earlier AI message already called counting_tool(x="a")
    prior_call = {"id": "old", "name": "counting_tool", "args": {"x": "a"}}
    prior_ai = _ai_with_calls([prior_call])
    prior_result = ToolMessage(tool_call_id="old", name="counting_tool", content="ran 0")

    # Now a new AI message asks for the same tool with the same args.
    new_call = {"id": "new", "name": "counting_tool", "args": {"x": "a"}}
    state = {"messages": [
        HumanMessage(content="go"),
        prior_ai,
        prior_result,
        _ai_with_calls([new_call]),
    ]}

    out = node(state)

    assert calls == 0, "deduped call must not invoke the tool again"
    msg = out["messages"][0]
    assert isinstance(msg, ToolMessage)
    assert msg.tool_call_id == "new"
    assert "already called" in msg.content.lower()


def test_tool_node_prints_semantic_dedup_queries(capsys):
    node = _build_tool_node([echo_tool], semantic_dedup_threshold=0.5)
    prior_call = {"id": "old", "name": "web_search", "args": {"query": "apollo moon landing transcript"}}
    new_call = {"id": "new", "name": "web_search", "args": {"query": "moon landing apollo transcript"}}
    state = {"messages": [
        HumanMessage(content="go"),
        _ai_with_calls([prior_call]),
        ToolMessage(tool_call_id="old", name="web_search", content="done"),
        _ai_with_calls([new_call]),
    ]}

    out = node(state)

    printed = capsys.readouterr().out
    assert "[tools] semantic_dedup score=1.00 tool=web_search" in printed
    assert "query='moon landing apollo transcript'" in printed
    assert "prior_query='apollo moon landing transcript'" in printed
    assert "REDUNDANT SEARCH PATH" in out["messages"][0].content


def test_tool_node_handles_unknown_tool_name():
    node = _build_tool_node([echo_tool])
    state = {"messages": [_ai_with_calls([{"id": "1", "name": "ghost", "args": {}}])]}

    out = node(state)
    msg = out["messages"][0]
    assert isinstance(msg, ToolMessage)
    assert "unknown tool" in msg.content.lower()


def test_dedup_does_not_emit_warning_level_logs(caplog):
    """Routine dedup fires on many turns; WARNING floods stderr during normal runs.

    Regression guard: `[dedup]`, `[semantic_dedup]`, `[loop_breaker]` stay at INFO."""
    import logging

    node = _build_tool_node([echo_tool])
    prior_call = {"id": "old", "name": "echo_tool", "args": {"text": "x"}}
    state = {"messages": [
        HumanMessage(content="go"),
        _ai_with_calls([prior_call]),
        ToolMessage(tool_call_id="old", name="echo_tool", content="done"),
        _ai_with_calls([{"id": "new", "name": "echo_tool", "args": {"text": "x"}}]),
    ]}

    with caplog.at_level(logging.DEBUG, logger="lilith_agent.app"):
        node(state)

    for rec in caplog.records:
        if "[dedup]" in rec.getMessage() or "[semantic_dedup]" in rec.getMessage() or "[loop_breaker]" in rec.getMessage():
            assert rec.levelno < logging.WARNING, f"routine guard log at {rec.levelname}: {rec.message}"


def test_cooldown_limit_for_known_tool_is_positive_int():
    """Each tool must declare a positive cooldown limit. Regression guard
    against the `3 if name == 'web_search' else 3` no-op ternary."""
    limit = _cooldown_limit_for("web_search")
    assert isinstance(limit, int) and limit > 0
    assert _cooldown_limit_for("fetch_url") == _cooldown_limit_for("web_search")


def test_tool_node_catches_tool_exceptions_and_feeds_back():
    @tool_decorator
    def boom_tool(x: str) -> str:
        """Always raises."""
        raise RuntimeError("kaboom")

    node = _build_tool_node([boom_tool])
    state = {"messages": [_ai_with_calls([{"id": "1", "name": "boom_tool", "args": {"x": "y"}}])]}

    out = node(state)
    msg = out["messages"][0]
    assert isinstance(msg, ToolMessage)
    assert "kaboom" in msg.content


@tool_decorator
def todo_sentinel_tool(action: str) -> str:
    """Returns todo sentinel output."""
    if action == "write":
        return "SET_TODOS: ['first', 'second']"
    return "DONE_TODO: 0"


def test_tool_node_consumes_todo_sentinels_into_state():
    node = _build_tool_node([todo_sentinel_tool])

    write_out = node({
        "messages": [_ai_with_calls([{"id": "1", "name": "todo_sentinel_tool", "args": {"action": "write"}}])],
        "todos": [],
    })
    assert write_out["todos"] == ["first", "second"]

    done_out = node({
        "messages": [_ai_with_calls([{"id": "2", "name": "todo_sentinel_tool", "args": {"action": "done"}}])],
        "todos": write_out["todos"],
    })
    assert done_out["todos"] == ["second"]