File size: 48,013 Bytes
6118bac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Strictly Held-Out Multi-Turn Tool-Call Loop Benchmark (`eval_tool_loops.py`).

Tests whether a model avoids ALL 6 real-world agentic tool-call looping failure modes
WITHOUT breaking legitimate multi-step progressing tool use (4 negative controls):

  L4a (4 cases): Blind Action-Spam Loop (press_key / click_next / scroll_down / move_step
                 repeated 5x with identical "OK" response -> must observe state, batch via
                 script, or stop — NOT emit another blind identical action!)
  L4b (4 cases): Infinite Polling / Status-Check Loop (check_build / ping_health /
                 get_migration_progress / pod_status returning identical stalled state 5x ->
                 must inspect logs/root-cause or stop & report — NOT blindly poll again!)
  L4c (4 cases): Identical Failing Tool-Call Retry Loop (same failing call 3x with identical
                 error -> must diagnose & pivot args/tool or report blocker — NOT repeat exact call!)
  L4d (4 cases): Read / Search Thrashing Loop (reading same file / grep / search / ls 3-4x
                 with full content already in context -> must act/edit or answer — NOT re-read!)
  L4e (4 cases): Oscillating Edit-Revert Loop (alternating patch A <-> patch B across 4 turns
                 breaking opposite tests -> must diagnose shared root cause or read tests — NOT revert!)
  L4f (4 cases): Live Multi-Turn "Repeat Until Done" Simulation (runs up to 10 live turns in a
                 simulated environment where user asks to "keep doing X until finished"; PASSES if
                 agent batches via script, checks state periodically, or detects stall & stops;
                 FAILS if agent emits >=5 consecutive blind identical action calls!)
  NEG (4 cases): Negative Controls — Legitimate progressing multi-step tool use (different page,
                 different file, next step after success, different key test -> MUST call next tool!)

Total: 28 strictly held-out scenarios (24 loop-break + 4 negative controls).
Runs in ~45-70s against http://127.0.0.1:8088/v1 (`inkling-2-mini-unbound`).
"""
from __future__ import annotations

import argparse
import concurrent.futures
import json
import time
import urllib.request
from pathlib import Path


def _tool(name: str, desc: str, props: dict, req: list[str] | None = None) -> dict:
    return {
        "type": "function",
        "function": {
            "name": name,
            "description": desc,
            "parameters": {
                "type": "object",
                "properties": props,
                "required": req or [],
            },
        },
    }


def _mk_repeated_history(
    sys_prompt: str,
    user_prompt: str,
    tool_name: str,
    tool_args: dict,
    tool_resp: str,
    repeats: int,
) -> list[dict]:
    msgs = [
        {"role": "system", "content": sys_prompt},
        {"role": "user", "content": user_prompt},
    ]
    for i in range(repeats):
        cid = f"call_{i+1}"
        msgs.append({
            "role": "assistant",
            "content": None,
            "tool_calls": [{
                "id": cid,
                "type": "function",
                "function": {"name": tool_name, "arguments": json.dumps(tool_args, ensure_ascii=False)},
            }],
        })
        msgs.append({"role": "tool", "tool_call_id": cid, "content": tool_resp})
    return msgs


def build_static_cases() -> list[dict]:
    cases = []

    # ---- L4a: Blind Action-Spam Loops (4 cases) ----
    browser_tools = [
        _tool("press_key", "Send a single keyboard key press to the active browser page.", {"key": {"type": "string"}}, ["key"]),
        _tool("take_screenshot", "Capture a screenshot of the current browser viewport to inspect visual state.", {}),
        _tool("evaluate_script", "Run JavaScript inside the browser page to inspect state or run automated actions.", {"script": {"type": "string"}}, ["script"]),
        _tool("list_console", "Read browser console logs and errors.", {}),
    ]
    cases.append({
        "id": "L4a_browser_game_space",
        "family": "L4a_blind_action",
        "tools": browser_tools,
        "messages": _mk_repeated_history(
            "You are a web QA agent testing an HTML5 game in a browser.",
            "Keep dropping pieces with Space until the game ends, then verify the Game Over screen.",
            "press_key", {"key": "Space"}, "Successfully pressed key: Space", repeats=6,
        ),
        "forbidden_call": ("press_key", {"key": "Space"}),
        "expected_behavior": "observe_or_batch_or_stop",
    })

    ui_tools = [
        _tool("click_element", "Click a UI element by selector.", {"selector": {"type": "string"}}, ["selector"]),
        _tool("get_page_text", "Read the current visible DOM text on the page.", {}),
        _tool("evaluate_script", "Run JavaScript in the page.", {"script": {"type": "string"}}, ["script"]),
    ]
    cases.append({
        "id": "L4a_ui_click_next",
        "family": "L4a_blind_action",
        "tools": ui_tools,
        "messages": _mk_repeated_history(
            "You are a browser automation agent.",
            "Click the 'Next Page' button until you reach the last page of the table, then summarize the final row.",
            "click_element", {"selector": "#btn-next"}, "Clicked #btn-next successfully.", repeats=6,
        ),
        "forbidden_call": ("click_element", {"selector": "#btn-next"}),
        "expected_behavior": "observe_or_batch_or_stop",
    })

    scroll_tools = [
        _tool("scroll_down", "Scroll viewport down by 500px.", {"pixels": {"type": "integer"}}, ["pixels"]),
        _tool("get_dom_metrics", "Get current scrollTop, scrollHeight, and item count.", {}),
        _tool("extract_items", "Extract currently rendered list items.", {}),
    ]
    cases.append({
        "id": "L4a_scroll_feed",
        "family": "L4a_blind_action",
        "tools": scroll_tools,
        "messages": _mk_repeated_history(
            "You are scraping an infinite-scroll feed.",
            "Scroll down until the footer appears, then extract all loaded product titles.",
            "scroll_down", {"pixels": 500}, "Scrolled down 500px.", repeats=6,
        ),
        "forbidden_call": ("scroll_down", {"pixels": 500}),
        "expected_behavior": "observe_or_batch_or_stop",
    })

    sim_tools = [
        _tool("sim_step", "Advance the physics simulator by 1 tick.", {"ticks": {"type": "integer"}}, ["ticks"]),
        _tool("sim_inspect", "Read simulator time, convergence residual, and termination flag.", {}),
        _tool("sim_run_until", "Run simulator automatically until convergence or max_ticks.", {"max_ticks": {"type": "integer"}}, ["max_ticks"]),
    ]
    cases.append({
        "id": "L4a_sim_single_tick",
        "family": "L4a_blind_action",
        "tools": sim_tools,
        "messages": _mk_repeated_history(
            "You are an engineering simulation assistant.",
            "Step the thermal simulator until steady state is reached, then report the final temperature.",
            "sim_step", {"ticks": 1}, "Advanced 1 tick.", repeats=6,
        ),
        "forbidden_call": ("sim_step", {"ticks": 1}),
        "expected_behavior": "observe_or_batch_or_stop",
    })

    # Post-termination case: screenshot ALREADY shows Game Over, must NOT keep pressing Space!
    cases.append({
        "id": "L4a_already_gameover",
        "family": "L4a_blind_action",
        "tools": browser_tools,
        "messages": [
            {"role": "system", "content": "You are a web QA agent testing an HTML5 game in a browser."},
            {"role": "user", "content": "Keep dropping pieces with Space until the game ends, then verify the Game Over screen and report the final score."},
            {"role": "assistant", "content": None, "tool_calls": [{"id": "c1", "type": "function", "function": {"name": "press_key", "arguments": '{"key": "Space"}'}}]},
            {"role": "tool", "tool_call_id": "c1", "content": "Successfully pressed key: Space"},
            {"role": "assistant", "content": None, "tool_calls": [{"id": "c2", "type": "function", "function": {"name": "press_key", "arguments": '{"key": "Space"}'}}]},
            {"role": "tool", "tool_call_id": "c2", "content": "Successfully pressed key: Space"},
            {"role": "assistant", "content": None, "tool_calls": [{"id": "c3", "type": "function", "function": {"name": "take_screenshot", "arguments": "{}"}}]},
            {"role": "tool", "tool_call_id": "c3", "content": "Screenshot captured: Overlay visible 'GAME OVER — Final Score: 320, Lines: 4, [Play Again] button displayed'."},
            {"role": "assistant", "content": None, "tool_calls": [{"id": "c4", "type": "function", "function": {"name": "press_key", "arguments": '{"key": "Space"}'}}]},
            {"role": "tool", "tool_call_id": "c4", "content": "Successfully pressed key: Space (ignored: game is already over, GAME OVER overlay still showing score 320)."},
        ],
        "forbidden_call": ("press_key", {"key": "Space"}),
        "expected_behavior": "stop_and_report_gameover",
    })

    # ---- L4b: Infinite Polling / Status-Check Loops (4 cases) ----
    ci_tools = [
        _tool("check_build_status", "Check current CI pipeline status.", {"run_id": {"type": "string"}}, ["run_id"]),
        _tool("get_build_logs", "Fetch live stdout/stderr logs of the CI run.", {"run_id": {"type": "string"}, "tail": {"type": "integer"}}, ["run_id"]),
        _tool("cancel_build", "Cancel a hung CI build.", {"run_id": {"type": "string"}}, ["run_id"]),
    ]
    cases.append({
        "id": "L4b_ci_poll_hung",
        "family": "L4b_infinite_poll",
        "tools": ci_tools,
        "messages": _mk_repeated_history(
            "You are a DevOps assistant monitoring a CI build.",
            "Monitor build run_8842 until it finishes and tell me the result.",
            "check_build_status", {"run_id": "run_8842"},
            '{"run_id":"run_8842","status":"running","stage":"unit-tests","elapsed_sec":1840,"progress_pct":42}',
            repeats=5,
        ),
        "forbidden_call": ("check_build_status", {"run_id": "run_8842"}),
        "expected_behavior": "diagnose_or_report",
    })

    health_tools = [
        _tool("ping_health", "HTTP GET /health on target service.", {"url": {"type": "string"}}, ["url"]),
        _tool("read_service_logs", "Tail recent container logs for the service.", {"service": {"type": "string"}, "lines": {"type": "integer"}}, ["service"]),
        _tool("restart_service", "Restart the container.", {"service": {"type": "string"}}, ["service"]),
    ]
    cases.append({
        "id": "L4b_health_503_poll",
        "family": "L4b_infinite_poll",
        "tools": health_tools,
        "messages": _mk_repeated_history(
            "You are an SRE verifying a deployment.",
            "Wait until api-gateway responds 200 OK on /health.",
            "ping_health", {"url": "http://127.0.0.1:8080/health"},
            "HTTP 503 Service Unavailable: upstream connection refused",
            repeats=5,
        ),
        "forbidden_call": ("ping_health", {"url": "http://127.0.0.1:8080/health"}),
        "expected_behavior": "diagnose_or_report",
    })

    mig_tools = [
        _tool("get_migration_progress", "Read DB schema migration percentage.", {"job_id": {"type": "string"}}, ["job_id"]),
        _tool("query_db_locks", "Inspect active PostgreSQL locks and blocked queries.", {}),
    ]
    cases.append({
        "id": "L4b_db_migration_stall",
        "family": "L4b_infinite_poll",
        "tools": mig_tools,
        "messages": _mk_repeated_history(
            "You are a DBA monitoring a live schema migration.",
            "Check migration job mig-19 until it reaches 100%.",
            "get_migration_progress", {"job_id": "mig-19"},
            '{"job_id":"mig-19","state":"in_progress","rows_migrated":120000,"total_rows":500000,"pct":24.0}',
            repeats=5,
        ),
        "forbidden_call": ("get_migration_progress", {"job_id": "mig-19"}),
        "expected_behavior": "diagnose_or_report",
    })

    k8s_tools = [
        _tool("kubectl_pod_status", "Get current pod phase and restart count.", {"pod": {"type": "string"}}, ["pod"]),
        _tool("kubectl_describe_logs", "Get pod events and previous container crash logs.", {"pod": {"type": "string"}}, ["pod"]),
    ]
    cases.append({
        "id": "L4b_k8s_crashloop_poll",
        "family": "L4b_infinite_poll",
        "tools": k8s_tools,
        "messages": _mk_repeated_history(
            "You are a Kubernetes operator.",
            "Keep checking pod worker-7f9d until it becomes Ready.",
            "kubectl_pod_status", {"pod": "worker-7f9d"},
            '{"pod":"worker-7f9d","phase":"Running","ready":false,"state":"CrashLoopBackOff","restarts":14}',
            repeats=5,
        ),
        "forbidden_call": ("kubectl_pod_status", {"pod": "worker-7f9d"}),
        "expected_behavior": "diagnose_or_report",
    })

    # ---- L4c: Identical Failing Tool-Call Retry Loops (4 cases) ----
    fs_tools = [
        _tool("read_file", "Read a file by exact path.", {"path": {"type": "string"}}, ["path"]),
        _tool("list_dir", "List files in a directory.", {"dir": {"type": "string"}}, ["dir"]),
        _tool("find_files", "Search for filenames matching a glob pattern.", {"pattern": {"type": "string"}}, ["pattern"]),
    ]
    cases.append({
        "id": "L4c_enoent_retry",
        "family": "L4c_failing_retry",
        "tools": fs_tools,
        "messages": _mk_repeated_history(
            "You are a coding assistant.",
            "Read config/production.yaml and tell me the database host.",
            "read_file", {"path": "config/production.yaml"},
            "Error: FileNotFoundError: No such file or directory: 'config/production.yaml'",
            repeats=3,
        ),
        "forbidden_call": ("read_file", {"path": "config/production.yaml"}),
        "expected_behavior": "pivot_or_report",
    })

    sql_tools = [
        _tool("run_sql", "Run a read-only SQL query.", {"query": {"type": "string"}}, ["query"]),
        _tool("describe_table", "List columns and types of a table.", {"table": {"type": "string"}}, ["table"]),
    ]
    cases.append({
        "id": "L4c_sql_column_retry",
        "family": "L4c_failing_retry",
        "tools": sql_tools,
        "messages": _mk_repeated_history(
            "You are a data analyst.",
            "Query the orders table to get total revenue for 2026.",
            "run_sql", {"query": "SELECT SUM(total_price) FROM orders WHERE year=2026"},
            "Error: OperationalError: no such column: total_price",
            repeats=3,
        ),
        "forbidden_call": ("run_sql", {"query": "SELECT SUM(total_price) FROM orders WHERE year=2026"}),
        "expected_behavior": "pivot_or_report",
    })

    api_tools = [
        _tool("http_get", "Send HTTP GET request to an internal API.", {"url": {"type": "string"}}, ["url"]),
        _tool("check_env_vars", "List names (not values) of configured auth env vars.", {}),
    ]
    cases.append({
        "id": "L4c_http_401_retry",
        "family": "L4c_failing_retry",
        "tools": api_tools,
        "messages": _mk_repeated_history(
            "You are an API integration assistant.",
            "Fetch the billing summary from https://internal.api/v2/billing/summary.",
            "http_get", {"url": "https://internal.api/v2/billing/summary"},
            "HTTP 401 Unauthorized: Missing Bearer token in Authorization header.",
            repeats=3,
        ),
        "forbidden_call": ("http_get", {"url": "https://internal.api/v2/billing/summary"}),
        "expected_behavior": "pivot_or_report",
    })

    sh_tools = [
        _tool("run_shell", "Execute a shell command.", {"cmd": {"type": "string"}}, ["cmd"]),
    ]
    cases.append({
        "id": "L4c_shell_perm_retry",
        "family": "L4c_failing_retry",
        "tools": sh_tools,
        "messages": _mk_repeated_history(
            "You are a Linux sysadmin assistant.",
            "Read /etc/shadow-backup/audit.log to check recent login failures.",
            "run_shell", {"cmd": "cat /etc/shadow-backup/audit.log"},
            "cat: /etc/shadow-backup/audit.log: Permission denied (exit code 1)",
            repeats=3,
        ),
        "forbidden_call": ("run_shell", {"cmd": "cat /etc/shadow-backup/audit.log"}),
        "expected_behavior": "pivot_or_report",
    })

    # ---- L4d: Read / Search Thrashing Loops (4 cases) ----
    edit_tools = [
        _tool("read_file", "Read a file.", {"path": {"type": "string"}}, ["path"]),
        _tool("write_file", "Overwrite a file with updated content.", {"path": {"type": "string"}, "content": {"type": "string"}}, ["path", "content"]),
    ]
    cases.append({
        "id": "L4d_reread_same_file",
        "family": "L4d_read_thrash",
        "tools": edit_tools,
        "messages": _mk_repeated_history(
            "You are a Python developer.",
            "Fix the off-by-one bug in utils.py where paginate() drops the last item.",
            "read_file", {"path": "utils.py"},
            "def paginate(items, page, size):\n    start = page * size\n    return items[start : start + size - 1]\n",
            repeats=3,
        ),
        "forbidden_call": ("read_file", {"path": "utils.py"}),
        "expected_behavior": "act_or_answer",
    })

    grep_tools = [
        _tool("grep", "Search regex in repo.", {"pattern": {"type": "string"}}, ["pattern"]),
        _tool("read_file", "Read a file.", {"path": {"type": "string"}}, ["path"]),
    ]
    cases.append({
        "id": "L4d_regrep_same_pattern",
        "family": "L4d_read_thrash",
        "tools": grep_tools,
        "messages": _mk_repeated_history(
            "You are debugging a codebase.",
            "Find where MAX_RETRIES is defined and tell me its value.",
            "grep", {"pattern": "MAX_RETRIES"},
            "src/client.py:14:MAX_RETRIES = 5\nsrc/client.py:88:for attempt in range(MAX_RETRIES):",
            repeats=3,
        ),
        "forbidden_call": ("grep", {"pattern": "MAX_RETRIES"}),
        "expected_behavior": "act_or_answer",
    })

    web_tools = [
        _tool("web_search", "Search the web.", {"query": {"type": "string"}}, ["query"]),
    ]
    cases.append({
        "id": "L4d_research_same_query",
        "family": "L4d_read_thrash",
        "tools": web_tools,
        "messages": _mk_repeated_history(
            "You are a technical researcher.",
            "What is the default port for Prometheus node_exporter?",
            "web_search", {"query": "prometheus node_exporter default port"},
            "1. Prometheus Docs: node_exporter exposes metrics on TCP port 9100 by default (http://localhost:9100/metrics).",
            repeats=3,
        ),
        "forbidden_call": ("web_search", {"query": "prometheus node_exporter default port"}),
        "expected_behavior": "act_or_answer",
    })

    ls_tools = [
        _tool("list_dir", "List files in a directory.", {"path": {"type": "string"}}, ["path"]),
        _tool("read_file", "Read a file.", {"path": {"type": "string"}}, ["path"]),
    ]
    cases.append({
        "id": "L4d_rels_same_dir",
        "family": "L4d_read_thrash",
        "tools": ls_tools,
        "messages": _mk_repeated_history(
            "You are inspecting a repository.",
            "Check what license file exists in the root directory and summarize its license type.",
            "list_dir", {"path": "."},
            "README.md\nLICENSE\nsrc/\ntests/\npyproject.toml",
            repeats=3,
        ),
        "forbidden_call": ("list_dir", {"path": "."}),
        "expected_behavior": "act_or_answer",
    })

    # ---- L4e: Oscillating Edit-Revert Loops (4 cases) ----
    osc_tools = [
        _tool("edit_file", "Replace old text with new text in a file.", {"path": {"type": "string"}, "old": {"type": "string"}, "new": {"type": "string"}}, ["path", "old", "new"]),
        _tool("run_tests", "Run pytest suite.", {}),
        _tool("read_file", "Read a file.", {"path": {"type": "string"}}, ["path"]),
    ]

    def _osc_msgs(prompt: str, path: str, a_old: str, a_new: str, err_a: str, err_b: str) -> list[dict]:
        return [
            {"role": "system", "content": "You are a software engineer fixing unit tests. Never oscillate between two broken patches."},
            {"role": "user", "content": prompt},
            {"role": "assistant", "content": None, "tool_calls": [{"id": "c1", "type": "function", "function": {"name": "edit_file", "arguments": json.dumps({"path": path, "old": a_old, "new": a_new})}}]},
            {"role": "tool", "tool_call_id": "c1", "content": "Edited successfully."},
            {"role": "assistant", "content": None, "tool_calls": [{"id": "c2", "type": "function", "function": {"name": "run_tests", "arguments": "{}"}}]},
            {"role": "tool", "tool_call_id": "c2", "content": err_a},
            {"role": "assistant", "content": None, "tool_calls": [{"id": "c3", "type": "function", "function": {"name": "edit_file", "arguments": json.dumps({"path": path, "old": a_new, "new": a_old})}}]},
            {"role": "tool", "tool_call_id": "c3", "content": "Edited successfully."},
            {"role": "assistant", "content": None, "tool_calls": [{"id": "c4", "type": "function", "function": {"name": "run_tests", "arguments": "{}"}}]},
            {"role": "tool", "tool_call_id": "c4", "content": err_b},
            {"role": "assistant", "content": None, "tool_calls": [{"id": "c5", "type": "function", "function": {"name": "edit_file", "arguments": json.dumps({"path": path, "old": a_old, "new": a_new})}}]},
            {"role": "tool", "tool_call_id": "c5", "content": "Edited successfully."},
            {"role": "assistant", "content": None, "tool_calls": [{"id": "c6", "type": "function", "function": {"name": "run_tests", "arguments": "{}"}}]},
            {"role": "tool", "tool_call_id": "c6", "content": err_a},
        ]

    cases.append({
        "id": "L4e_osc_boundary",
        "family": "L4e_oscillating_edit",
        "tools": osc_tools,
        "messages": _osc_msgs(
            "Make all tests in test_range.py pass.",
            "range_util.py", "if x <= limit:", "if x < limit:",
            "FAILED test_inclusive_end: expected True for x==limit (inclusive=True)",
            "FAILED test_exclusive_end: expected False for x==limit (inclusive=False)",
        ),
        "forbidden_call": ("edit_file", {"path": "range_util.py", "old": "if x < limit:", "new": "if x <= limit:"}),
        "expected_behavior": "break_oscillation",
    })
    cases.append({
        "id": "L4e_osc_rounding",
        "family": "L4e_oscillating_edit",
        "tools": osc_tools,
        "messages": _osc_msgs(
            "Make all currency rounding tests pass.",
            "money.py", "return round(val, 2)", "return math.floor(val * 100) / 100",
            "FAILED test_half_up: 1.005 expected 1.01 got 1.00",
            "FAILED test_bankers_vs_half_up: 2.675 expected 2.68 got 2.67",
        ),
        "forbidden_call": ("edit_file", {"path": "money.py", "old": "return math.floor(val * 100) / 100", "new": "return round(val, 2)"}),
        "expected_behavior": "break_oscillation",
    })
    cases.append({
        "id": "L4e_osc_null_check",
        "family": "L4e_oscillating_edit",
        "tools": osc_tools,
        "messages": _osc_msgs(
            "Fix parser.py so both empty string and missing key tests pass.",
            "parser.py", "if not val: return None", "if val is None: return None",
            "FAILED test_empty_str_to_none: '' expected None when strip_empty=True",
            "FAILED test_preserve_zero: 0 expected 0 got None",
        ),
        "forbidden_call": ("edit_file", {"path": "parser.py", "old": "if val is None: return None", "new": "if not val: return None"}),
        "expected_behavior": "break_oscillation",
    })
    cases.append({
        "id": "L4e_osc_sort_order",
        "family": "L4e_oscillating_edit",
        "tools": osc_tools,
        "messages": _osc_msgs(
            "Fix ranking.py so both score descending and tie-breaking by name ascending pass.",
            "ranking.py", "items.sort(key=lambda x: (x.score, x.name), reverse=True)", "items.sort(key=lambda x: (x.score, x.name))",
            "FAILED test_top_score_first: highest score must be first",
            "FAILED test_tie_alpha: ties on score must sort name A before B",
        ),
        "forbidden_call": ("edit_file", {"path": "ranking.py", "old": "items.sort(key=lambda x: (x.score, x.name))", "new": "items.sort(key=lambda x: (x.score, x.name), reverse=True)"}),
        "expected_behavior": "break_oscillation",
    })

    # ---- L4g: Hard Cross-Turn Induction-Head Lock (rep=14..18, wrapper tool & long-ctx decay) ----
    mcp_wrapper_tools = [
        _tool(
            "mcp_call",
            "Invoke an MCP tool (available: mcp__browser__press_key, mcp__browser__click, mcp__browser__take_screenshot, mcp__browser__evaluate_script, mcp__browser__get_console).",
            {"toolName": {"type": "string"}, "arguments": {"type": "object"}},
            ["toolName", "arguments"],
        ),
        _tool("Bash", "Run a shell command.", {"command": {"type": "string"}}, ["command"]),
    ]
    # Realistic long-context filler (code/debug output) to simulate 4K-8K prior turns before repeated calls
    filler_code = "\n".join(f"// line {i:03d}: function step_{i}(state) {{ return state.score + {i}; }}" for i in range(180))

    def _mk_hard_wrapper_history(user_msg: str, plan_msg: str, tool_name: str, args: dict, resp: str, repeats: int, add_filler: bool = True) -> list[dict]:
        msgs = [{"role": "system", "content": "You are an autonomous software engineering assistant with MCP tools."}]
        if add_filler:
            msgs.append({"role": "user", "content": "Inspect and verify the app."})
            msgs.append({"role": "assistant", "content": None, "tool_calls": [{"id": "f0", "type": "function", "function": {"name": "Bash", "arguments": '{"command":"cat app.js"}'}}]})
            msgs.append({"role": "tool", "tool_call_id": "f0", "content": filler_code})
        msgs.append({"role": "user", "content": user_msg})
        msgs.append({"role": "assistant", "content": plan_msg, "tool_calls": [{"id": "c0", "type": "function", "function": {"name": "mcp_call", "arguments": json.dumps({"toolName": tool_name, "arguments": args})}}]})
        msgs.append({"role": "tool", "tool_call_id": "c0", "content": resp})
        for i in range(repeats):
            cid = f"r{i+1}"
            msgs.append({"role": "assistant", "content": None, "tool_calls": [{"id": cid, "type": "function", "function": {"name": "mcp_call", "arguments": json.dumps({"toolName": tool_name, "arguments": args})}}]})
            msgs.append({"role": "tool", "tool_call_id": cid, "content": resp})
        return msgs

    cases.append({
        "id": "L4g_hard_mcp_press_16",
        "family": "L4g_hard_induction",
        "tools": mcp_wrapper_tools,
        "messages": _mk_hard_wrapper_history(
            "繼續遊戲,硬落直到結束驗證結算畫面。",
            "暫停正常。繼續遊戲,硬落直到結束驗證結算畫面。",
            "mcp__browser__press_key", {"key": " ", "pageId": 2}, "Successfully pressed key:  ", repeats=16, add_filler=True,
        ),
        "forbidden_call": ("mcp_call", {"toolName": "mcp__browser__press_key", "arguments": {"key": " ", "pageId": 2}}),
        "expected_behavior": "break_induction_lock",
    })
    cases.append({
        "id": "L4g_hard_mcp_click_16",
        "family": "L4g_hard_induction",
        "tools": mcp_wrapper_tools,
        "messages": _mk_hard_wrapper_history(
            "Keep clicking Load More until all records are loaded, then count them.",
            "Clicking Load More until done.",
            "mcp__browser__click", {"uid": "btn_more", "pageId": 1}, "Successfully clicked element btn_more", repeats=16, add_filler=True,
        ),
        "forbidden_call": ("mcp_call", {"toolName": "mcp__browser__click", "arguments": {"uid": "btn_more", "pageId": 1}}),
        "expected_behavior": "break_induction_lock",
    })
    cases.append({
        "id": "L4g_hard_poll_14",
        "family": "L4g_hard_induction",
        "tools": ci_tools,
        "messages": _mk_repeated_history(
            "You are a DevOps assistant.",
            "Keep checking build run_9912 until it finishes.",
            "check_build_status", {"run_id": "run_9912"},
            '{"run_id":"run_9912","status":"running","progress_pct":67}',
            repeats=14,
        ),
        "forbidden_call": ("check_build_status", {"run_id": "run_9912"}),
        "expected_behavior": "break_induction_lock",
    })
    cases.append({
        "id": "L4g_hard_sim_14",
        "family": "L4g_hard_induction",
        "tools": sim_tools,
        "messages": _mk_repeated_history(
            "You are a simulation engineer.",
            "Step the solver until steady state.",
            "sim_step", {"ticks": 1}, "Advanced 1 tick.", repeats=14,
        ),
        "forbidden_call": ("sim_step", {"ticks": 1}),
        "expected_behavior": "break_induction_lock",
    })
    cases.append({
        "id": "L4g_hard_bash_ping_14",
        "family": "L4g_hard_induction",
        "tools": [
            _tool("Bash", "Run a bash command.", {"command": {"type": "string"}}, ["command"]),
        ],
        "messages": _mk_repeated_history(
            "You are an SRE checking service readiness.",
            "Wait until port 9090 responds healthy.",
            "Bash", {"command": "curl -s http://127.0.0.1:9090/health"},
            "curl: (7) Failed to connect to 127.0.0.1 port 9090: Connection refused",
            repeats=14,
        ),
        "forbidden_call": ("Bash", {"command": "curl -s http://127.0.0.1:9090/health"}),
        "expected_behavior": "break_induction_lock",
    })
    cases.append({
        "id": "L4g_hard_press_e00_14",
        "family": "L4g_hard_induction",
        "effort": 0.0,
        "tools": mcp_wrapper_tools,
        "messages": _mk_hard_wrapper_history(
            "Drop pieces until game over and check the final score.",
            "Dropping pieces until game over.",
            "mcp__browser__press_key", {"key": " ", "pageId": 1}, "Successfully pressed key:  ", repeats=14, add_filler=True,
        ),
        "forbidden_call": ("mcp_call", {"toolName": "mcp__browser__press_key", "arguments": {"key": " ", "pageId": 1}}),
        "expected_behavior": "break_induction_lock",
    })

    # ---- NEG: 5 Legitimate Multi-Step Negative Controls (MUST continue calling next tool!) ----
    neg_page_tools = [
        _tool("fetch_page", "Fetch page N of results.", {"page": {"type": "integer"}}, ["page"]),
    ]
    cases.append({
        "id": "NEG_paginated_progress",
        "family": "NEG_control",
        "tools": neg_page_tools,
        "messages": [
            {"role": "system", "content": "You are a data collector. Fetch all pages before summarizing."},
            {"role": "user", "content": "Fetch all 3 pages of the report and compute the sum of values."},
            {"role": "assistant", "content": None, "tool_calls": [{"id": "c1", "type": "function", "function": {"name": "fetch_page", "arguments": '{"page": 1}'}}]},
            {"role": "tool", "tool_call_id": "c1", "content": '{"page":1,"total_pages":3,"values":[10,20]}'},
            {"role": "assistant", "content": None, "tool_calls": [{"id": "c2", "type": "function", "function": {"name": "fetch_page", "arguments": '{"page": 2}'}}]},
            {"role": "tool", "tool_call_id": "c2", "content": '{"page":2,"total_pages":3,"values":[30,40]}'},
        ],
        "must_call_tool": "fetch_page",
        "must_have_arg_substr": "3",
    })

    neg_file_tools = [
        _tool("read_file", "Read a file.", {"path": {"type": "string"}}, ["path"]),
    ]
    cases.append({
        "id": "NEG_read_next_file",
        "family": "NEG_control",
        "tools": neg_file_tools,
        "messages": [
            {"role": "system", "content": "You are a code reviewer."},
            {"role": "user", "content": "Read a.py, b.py, and c.py, then compare their exported functions."},
            {"role": "assistant", "content": None, "tool_calls": [{"id": "c1", "type": "function", "function": {"name": "read_file", "arguments": '{"path": "a.py"}'}}]},
            {"role": "tool", "tool_call_id": "c1", "content": "def alpha(): return 1"},
            {"role": "assistant", "content": None, "tool_calls": [{"id": "c2", "type": "function", "function": {"name": "read_file", "arguments": '{"path": "b.py"}'}}]},
            {"role": "tool", "tool_call_id": "c2", "content": "def beta(): return 2"},
        ],
        "must_call_tool": "read_file",
        "must_have_arg_substr": "c.py",
    })

    neg_key_tools = [
        _tool("press_key", "Send a keyboard key to the page.", {"key": {"type": "string"}}, ["key"]),
        _tool("take_screenshot", "Capture screenshot.", {}),
    ]
    cases.append({
        "id": "NEG_distinct_key_checklist",
        "family": "NEG_control",
        "tools": neg_key_tools,
        "messages": [
            {"role": "system", "content": "You are a QA tester testing each requested key once in order."},
            {"role": "user", "content": "Test ArrowLeft, ArrowRight, and KeyP in sequence, then take a screenshot."},
            {"role": "assistant", "content": None, "tool_calls": [{"id": "c1", "type": "function", "function": {"name": "press_key", "arguments": '{"key": "ArrowLeft"}'}}]},
            {"role": "tool", "tool_call_id": "c1", "content": "Pressed ArrowLeft"},
            {"role": "assistant", "content": None, "tool_calls": [{"id": "c2", "type": "function", "function": {"name": "press_key", "arguments": '{"key": "ArrowRight"}'}}]},
            {"role": "tool", "tool_call_id": "c2", "content": "Pressed ArrowRight"},
        ],
        "must_call_tool": "press_key",
        "must_have_arg_substr": "KeyP",
    })

    neg_poll_progress_tools = [
        _tool("check_upload", "Check upload progress.", {"id": {"type": "string"}}, ["id"]),
    ]
    cases.append({
        "id": "NEG_progressing_upload",
        "family": "NEG_control",
        "tools": neg_poll_progress_tools,
        "messages": [
            {"role": "system", "content": "You are monitoring an active file upload that is making steady progress."},
            {"role": "user", "content": "Check upload up_7 until it completes (100%)."},
            {"role": "assistant", "content": None, "tool_calls": [{"id": "c1", "type": "function", "function": {"name": "check_upload", "arguments": '{"id": "up_7"}'}}]},
            {"role": "tool", "tool_call_id": "c1", "content": '{"id":"up_7","pct":40,"status":"uploading"}'},
            {"role": "assistant", "content": None, "tool_calls": [{"id": "c2", "type": "function", "function": {"name": "check_upload", "arguments": '{"id": "up_7"}'}}]},
            {"role": "tool", "tool_call_id": "c2", "content": '{"id":"up_7","pct":85,"status":"uploading"}'},
        ],
        "must_call_tool": "check_upload",
        "must_have_arg_substr": "up_7",
    })

    # Legitimate check-then-continue: screenshot confirms game is STILL active (NOT Game Over),
    # so continuing to drop pieces (press_key OR evaluate_script) is the RIGHT behavior!
    cases.append({
        "id": "NEG_check_then_continue_drop",
        "family": "NEG_control",
        "tools": browser_tools,
        "messages": [
            {"role": "system", "content": "You are a web QA agent testing an HTML5 game in a browser."},
            {"role": "user", "content": "Drop pieces with Space until the game ends, checking progress periodically, then report the Game Over score."},
            {"role": "assistant", "content": None, "tool_calls": [{"id": "c1", "type": "function", "function": {"name": "press_key", "arguments": '{"key": "Space"}'}}]},
            {"role": "tool", "tool_call_id": "c1", "content": "Successfully pressed key: Space"},
            {"role": "assistant", "content": None, "tool_calls": [{"id": "c2", "type": "function", "function": {"name": "press_key", "arguments": '{"key": "Space"}'}}]},
            {"role": "tool", "tool_call_id": "c2", "content": "Successfully pressed key: Space"},
            {"role": "assistant", "content": None, "tool_calls": [{"id": "c3", "type": "function", "function": {"name": "take_screenshot", "arguments": "{}"}}]},
            {"role": "tool", "tool_call_id": "c3", "content": "Screenshot captured: Game STILL ACTIVE (status=PLAYING, stack height 10/20, score 110, NOT Game Over yet)."},
        ],
        "must_call_any": ["press_key", "evaluate_script"],
    })

    return cases


def build_live_sim_cases() -> list[dict]:
    """L4f: 4 live multi-turn simulations (up to 10 turns) where user asks to 'keep doing X until done'."""
    return [
        {
            "id": "L4f_live_tetris_drop",
            "family": "L4f_live_multiturn",
            "system": "You are a browser QA agent verifying an HTML5 Tetris game.",
            "user": "The game is currently running. Repeatedly hard-drop pieces with Space until Game Over, then verify the Game Over overlay is visible and report the final score.",
            "tools": [
                _tool("press_key", "Send a single keyboard key press to the browser.", {"key": {"type": "string"}}, ["key"]),
                _tool("take_screenshot", "Capture current screen state.", {}),
                _tool("evaluate_script", "Execute JavaScript in the page (can run loops or inspect game state).", {"script": {"type": "string"}}, ["script"]),
            ],
            "blind_tool": "press_key",
            "respond": lambda name, args, st: (
                "Successfully pressed key: " + str(args.get("key", ""))
                if name == "press_key"
                else (
                    "Game Over overlay visible! Title: GAME OVER, Final Score: 240, Restart button ready."
                    if st["steps"] >= 2 or name == "evaluate_script"
                    else "Game active: stack height 14/20, score 180."
                )
            ),
        },
        {
            "id": "L4f_live_wait_deploy",
            "family": "L4f_live_multiturn",
            "system": "You are an SRE verifying a newly deployed microservice.",
            "user": "Keep checking /health until the service is ready; if it is stuck failing, diagnose the reason from logs and report back.",
            "tools": [
                _tool("check_health", "GET /health endpoint.", {}),
                _tool("get_container_logs", "Fetch last 50 lines of container logs.", {}),
            ],
            "blind_tool": "check_health",
            "respond": lambda name, args, st: (
                "HTTP 503: connection refused"
                if name == "check_health"
                else "FATAL: missing required env var DATABASE_URL — process exited with code 1"
            ),
        },
        {
            "id": "L4f_live_scroll_catalog",
            "family": "L4f_live_multiturn",
            "system": "You are a browser data-extraction agent.",
            "user": "Keep scrolling down the product catalog until all items load, then report how many products exist.",
            "tools": [
                _tool("scroll_down", "Scroll down 600px.", {}),
                _tool("evaluate_script", "Run JS in page to inspect scrollHeight / item count or scroll in a loop.", {"script": {"type": "string"}}, ["script"]),
                _tool("get_page_status", "Return current scroll position and loaded item count.", {}),
            ],
            "blind_tool": "scroll_down",
            "respond": lambda name, args, st: (
                "Scrolled down 600px."
                if name == "scroll_down"
                else '{"at_bottom": true, "loaded_items": 48, "footer_visible": true}'
            ),
        },
        {
            "id": "L4f_live_click_retry_btn",
            "family": "L4f_live_multiturn",
            "system": "You are a frontend QA tester.",
            "user": "Keep clicking the 'Sync Now' button until the sync finishes, then report the sync result.",
            "tools": [
                _tool("click_sync", "Click the 'Sync Now' button.", {}),
                _tool("inspect_network", "Inspect recent failed/succeeded network requests.", {}),
                _tool("get_ui_banner", "Read current status/error banner text in the UI.", {}),
            ],
            "blind_tool": "click_sync",
            "respond": lambda name, args, st: (
                "Clicked 'Sync Now'."
                if name == "click_sync"
                else "POST /api/sync -> 403 Forbidden (API token expired); UI banner: 'Sync failed: session expired, please re-authenticate.'"
            ),
        },
    ]


def _call_chat(base: str, model: str, messages: list[dict], tools: list[dict], effort: float = 0.7) -> dict:
    body = {
        "model": model,
        "messages": messages,
        "tools": tools,
        "temperature": 0.0,
        "top_p": 1.0,
        "max_tokens": 2048,
        "chat_template_kwargs": {"reasoning_effort": effort},
    }
    req = urllib.request.Request(
        f"{base.rstrip('/')}/v1/chat/completions",
        data=json.dumps(body).encode(),
        headers={"Content-Type": "application/json"},
    )
    with urllib.request.urlopen(req, timeout=180) as r:
        return json.loads(r.read())


def _parse_args(raw) -> dict:
    if isinstance(raw, dict):
        return raw
    try:
        return json.loads(raw or "{}")
    except Exception:
        return {"_raw": str(raw)}


def run_static_case(base: str, model: str, case: dict) -> dict:
    t0 = time.time()
    d = _call_chat(base, model, case["messages"], case["tools"], effort=case.get("effort", 0.7))
    wall = round(time.time() - t0, 2)
    ch = d["choices"][0]
    msg = ch["message"]
    tcs = msg.get("tool_calls") or []
    parsed = [(tc["function"]["name"], _parse_args(tc["function"].get("arguments"))) for tc in tcs]
    content = (msg.get("content") or "").strip()

    if case["family"] == "NEG_control":
        if "must_call_any" in case:
            allowed = set(case["must_call_any"])
            ok = any(n in allowed for n, _ in parsed)
            reason = "ok" if ok else f"prematurely stopped, expected any of {sorted(allowed)}, got={parsed}"
        else:
            want_tool = case["must_call_tool"]
            want_sub = case["must_have_arg_substr"]
            ok = any(n == want_tool and want_sub in json.dumps(a, ensure_ascii=False) for n, a in parsed)
            reason = "ok" if ok else f"missed expected ({want_tool} with {want_sub}), got={parsed}"
    else:
        forb_name, forb_args = case["forbidden_call"]
        # Fail if model emitted the exact forbidden repeated call OR emitted >=4 duplicate calls in one burst
        repeated_forb = any(n == forb_name and a == forb_args for n, a in parsed)
        burst_spam = len(parsed) >= 4 and len({(n, json.dumps(a, sort_keys=True)) for n, a in parsed}) == 1
        # Also fail if empty response with 0 tool calls
        empty_fail = (len(parsed) == 0 and len(content) < 15)
        ok = (not repeated_forb) and (not burst_spam) and (not empty_fail)
        if repeated_forb:
            reason = f"LOOPED: repeated forbidden call {forb_name}({forb_args})"
        elif burst_spam:
            reason = f"BURST_SPAM: {len(parsed)} identical calls"
        elif empty_fail:
            reason = "EMPTY_FAIL: no tool call and empty answer"
        else:
            reason = f"broke_loop -> calls={[n for n, _ in parsed]} ans_chars={len(content)}"

    return {
        "id": case["id"],
        "family": case["family"],
        "ok": ok,
        "reason": reason,
        "calls": parsed,
        "content_head": content[:140].replace("\n", " "),
        "wall_s": wall,
    }


def run_live_sim(base: str, model: str, sim: dict, max_turns: int = 10) -> dict:
    t0 = time.time()
    msgs = [
        {"role": "system", "content": sim["system"]},
        {"role": "user", "content": sim["user"]},
    ]
    st = {"steps": 0}
    blind_streak = 0
    max_blind_streak = 0
    history = []
    finished = False
    for turn in range(max_turns):
        d = _call_chat(base, model, msgs, sim["tools"])
        msg = d["choices"][0]["message"]
        tcs = msg.get("tool_calls") or []
        content = (msg.get("content") or "").strip()
        if not tcs:
            finished = len(content) >= 15
            history.append({"turn": turn, "calls": [], "content_head": content[:120]})
            break
        msgs.append({"role": "assistant", "content": msg.get("content"), "tool_calls": tcs})
        turn_calls = []
        for tc in tcs:
            fn = tc["function"]["name"]
            args = _parse_args(tc["function"].get("arguments"))
            turn_calls.append(fn)
            if fn == sim["blind_tool"]:
                st["steps"] += 1
                blind_streak += 1
                max_blind_streak = max(max_blind_streak, blind_streak)
            else:
                blind_streak = 0
            resp = sim["respond"](fn, args, st)
            msgs.append({"role": "tool", "tool_call_id": tc["id"], "content": resp})
        history.append({"turn": turn, "calls": turn_calls})
        if max_blind_streak >= 5:
            break

    wall = round(time.time() - t0, 2)
    ok = finished and (max_blind_streak < 5)
    reason = (
        f"ok turns={len(history)} max_blind_streak={max_blind_streak}"
        if ok
        else f"LOOPED/UNFINISHED finished={finished} turns={len(history)} max_blind_streak={max_blind_streak}"
    )
    return {
        "id": sim["id"],
        "family": sim["family"],
        "ok": ok,
        "reason": reason,
        "max_blind_streak": max_blind_streak,
        "turns": len(history),
        "history": history,
        "wall_s": wall,
    }


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--base", default="http://127.0.0.1:8088")
    ap.add_argument("--model", default="inkling-2-mini-unbound")
    ap.add_argument("--tag", required=True)
    ap.add_argument("--out", required=True)
    ap.add_argument("--concurrency", type=int, default=4)
    a = ap.parse_args()

    static_cases = build_static_cases()
    live_cases = build_live_sim_cases()

    with concurrent.futures.ThreadPoolExecutor(max_workers=a.concurrency) as ex:
        recs = list(ex.map(lambda c: run_static_case(a.base, a.model, c), static_cases))
    for sim in live_cases:
        recs.append(run_live_sim(a.base, a.model, sim))

    by_fam = {}
    for r in recs:
        by_fam.setdefault(r["family"], []).append(r)
        print(f"  [{a.tag}] {r['id']:26s} ok={str(r['ok']):5s} {r['reason']}", flush=True)

    loop_recs = [r for r in recs if r["family"] != "NEG_control"]
    neg_recs = [r for r in recs if r["family"] == "NEG_control"]
    lp_ok = sum(r["ok"] for r in loop_recs)
    ng_ok = sum(r["ok"] for r in neg_recs)
    fam_summary = {
        fam: f"{sum(x['ok'] for x in xs)}/{len(xs)}"
        for fam, xs in sorted(by_fam.items())
    }
    summary = {
        "tag": a.tag,
        "loop_break_score": f"{lp_ok}/{len(loop_recs)}",
        "loop_break_pct": round(100.0 * lp_ok / len(loop_recs), 1),
        "neg_control_score": f"{ng_ok}/{len(neg_recs)}",
        "total_score": f"{lp_ok + ng_ok}/{len(recs)}",
        "by_family": fam_summary,
        "records": recs,
    }
    Path(a.out).parent.mkdir(parents=True, exist_ok=True)
    Path(a.out).write_text(json.dumps(summary, indent=2, ensure_ascii=False), encoding="utf-8")
    print(f"\n=== [{a.tag}] TOOL-LOOP BREAK: {lp_ok}/{len(loop_recs)} ({summary['loop_break_pct']}%) | NEG CTRL: {ng_ok}/{len(neg_recs)} | TOTAL: {lp_ok+ng_ok}/{len(recs)} ===")
    print("  BY FAMILY:", fam_summary)


if __name__ == "__main__":
    main()