#
Junjie
9 天以前 abda5558251735836c6e5089818295a7c9175f63
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
package com.zy.ai.service;
 
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.zy.ai.domain.autotune.AutoTuneApplyRequest;
import com.zy.ai.domain.autotune.AutoTuneApplyResult;
import com.zy.ai.domain.autotune.AutoTuneChangeCommand;
import com.zy.ai.domain.autotune.AutoTuneSnapshot;
import com.zy.ai.domain.autotune.AutoTuneJobStatus;
import com.zy.ai.domain.autotune.AutoTuneTriggerType;
import com.zy.ai.entity.AiAutoTuneChange;
import com.zy.ai.entity.AiAutoTuneJob;
import com.zy.ai.entity.AiPromptTemplate;
import com.zy.ai.entity.ChatCompletionRequest;
import com.zy.ai.entity.ChatCompletionResponse;
import com.zy.ai.enums.AiPromptScene;
import com.zy.ai.mcp.service.SpringAiMcpToolManager;
import com.zy.ai.mcp.tool.AutoTuneMcpTools;
import com.zy.ai.service.impl.AutoTuneAgentServiceImpl;
import com.zy.ai.service.impl.AutoTuneCoordinatorServiceImpl;
import com.zy.asrs.service.WrkMastService;
import com.zy.common.utils.RedisUtil;
import com.zy.core.enums.RedisKeyType;
import com.zy.system.entity.OperateLog;
import com.zy.system.service.ConfigService;
import com.zy.system.service.OperateLogService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.test.util.ReflectionTestUtils;
 
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.LongSupplier;
 
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyDouble;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
 
@ExtendWith(MockitoExtension.class)
class AutoTuneCoordinatorServiceImplTest {
 
    private AutoTuneMcpTools tools;
 
    @Mock
    private AutoTuneSnapshotService autoTuneSnapshotService;
    @Mock
    private AutoTuneApplyService autoTuneApplyService;
    @Mock
    private AiAutoTuneJobService aiAutoTuneJobService;
    @Mock
    private AiAutoTuneChangeService aiAutoTuneChangeService;
    @Mock
    private AiAutoTuneMcpCallService aiAutoTuneMcpCallService;
    @Mock
    private LlmChatService llmChatService;
    @Mock
    private SpringAiMcpToolManager mcpToolManager;
    @Mock
    private AiPromptTemplateService aiPromptTemplateService;
    @Mock
    private ConfigService configService;
    @Mock
    private WrkMastService wrkMastService;
    @Mock
    private AutoTuneAgentService autoTuneAgentService;
    @Mock
    private RedisUtil redisUtil;
    @Mock
    private OperateLogService operateLogService;
 
    @BeforeEach
    void setUp() {
        tools = new AutoTuneMcpTools(
                autoTuneSnapshotService,
                autoTuneApplyService,
                aiAutoTuneJobService,
                aiAutoTuneChangeService,
                aiAutoTuneMcpCallService);
    }
 
    @Test
    void snapshotToolDelegatesToSnapshotService() {
        AutoTuneSnapshot snapshot = new AutoTuneSnapshot();
        when(autoTuneSnapshotService.buildSnapshot()).thenReturn(snapshot);
 
        AutoTuneSnapshot result = tools.getAutoTuneSnapshot();
 
        assertSame(snapshot, result);
        verify(autoTuneSnapshotService).buildSnapshot();
    }
 
    @Test
    void recentJobsReturnsBoundedCompactSummariesWithChanges() {
        AiAutoTuneJob job = new AiAutoTuneJob();
        job.setId(7L);
        job.setTriggerType("agent");
        job.setStatus("success");
        job.setSummary("applied");
        job.setSuccessCount(1);
        job.setRejectCount(0);
        AiAutoTuneChange change = new AiAutoTuneChange();
        change.setJobId(70L);
        change.setTargetType("sys_config");
        change.setTargetKey("conveyorStationTaskLimit");
        change.setRequestedValue("12");
        change.setResultStatus("success");
        com.zy.ai.entity.AiAutoTuneMcpCall mcpCall = new com.zy.ai.entity.AiAutoTuneMcpCall();
        mcpCall.setAgentJobId(7L);
        mcpCall.setCallSeq(1);
        mcpCall.setToolName("wcs_local_dispatch_apply_auto_tune_changes");
        mcpCall.setStatus("success");
        mcpCall.setApplyJobId(70L);
 
        when(aiAutoTuneJobService.list(any(Wrapper.class))).thenReturn(Collections.singletonList(job));
        when(aiAutoTuneMcpCallService.list(any(Wrapper.class))).thenReturn(Collections.singletonList(mcpCall));
        when(aiAutoTuneChangeService.list(any(Wrapper.class))).thenReturn(Collections.singletonList(change));
 
        List<Map<String, Object>> result = tools.getRecentAutoTuneJobs(99);
 
        assertEquals(1, result.size());
        assertEquals(7L, result.get(0).get("id"));
        assertFalse(result.get(0).containsKey("reasoningDigest"));
        assertEquals(1, result.get(0).get("mcpCallCount"));
        List<?> changes = (List<?>) result.get(0).get("changes");
        assertEquals(1, changes.size());
 
        ArgumentCaptor<Wrapper<AiAutoTuneJob>> wrapperCaptor = ArgumentCaptor.forClass(Wrapper.class);
        verify(aiAutoTuneJobService).list(wrapperCaptor.capture());
        assertTrue(wrapperCaptor.getValue().getSqlSegment().contains("limit 20"));
    }
 
    @Test
    void applyToolDelegatesToApplyServiceWithDryRunAndChanges() {
        AutoTuneApplyResult expected = new AutoTuneApplyResult();
        expected.setDryRun(true);
        expected.setSuccess(true);
        when(autoTuneApplyService.apply(any(AutoTuneApplyRequest.class))).thenReturn(expected);
 
        AutoTuneChangeCommand command = new AutoTuneChangeCommand();
        command.setTargetType("sys_config");
        command.setTargetKey("conveyorStationTaskLimit");
        command.setNewValue("12");
        List<AutoTuneChangeCommand> changes = Collections.singletonList(command);
 
        AutoTuneApplyResult result = tools.applyAutoTuneChanges("reduce congestion", 10, "agent", true, null, changes);
 
        assertSame(expected, result);
        assertNotNull(result.getDryRunToken());
        ArgumentCaptor<AutoTuneApplyRequest> captor = ArgumentCaptor.forClass(AutoTuneApplyRequest.class);
        verify(autoTuneApplyService).apply(captor.capture());
        assertEquals("reduce congestion", captor.getValue().getReason());
        assertEquals(10, captor.getValue().getAnalysisIntervalMinutes());
        assertEquals("agent", captor.getValue().getTriggerType());
        assertEquals(Boolean.TRUE, captor.getValue().getDryRun());
        assertSame(changes, captor.getValue().getChanges());
    }
 
    @Test
    void applyToolRejectsMissingDryRunBeforeServiceCall() {
        AutoTuneChangeCommand command = change("sys_config", null, "conveyorStationTaskLimit", "12");
 
        IllegalArgumentException exception = assertThrows(IllegalArgumentException.class,
                () -> tools.applyAutoTuneChanges("missing dryRun", 10, "agent", null, null,
                        Collections.singletonList(command)));
 
        assertTrue(exception.getMessage().contains("dryRun is required"));
        verify(autoTuneApplyService, never()).apply(any(AutoTuneApplyRequest.class));
    }
 
    @Test
    void applyToolRejectsDirectRealApplyWithoutDryRunToken() {
        AutoTuneChangeCommand command = change("sys_config", null, "conveyorStationTaskLimit", "12");
 
        IllegalArgumentException exception = assertThrows(IllegalArgumentException.class,
                () -> tools.applyAutoTuneChanges("direct apply", 10, "agent", false, null,
                        Collections.singletonList(command)));
 
        assertTrue(exception.getMessage().contains("dryRunToken is required"));
        verify(autoTuneApplyService, never()).apply(any(AutoTuneApplyRequest.class));
    }
 
    @Test
    void applyToolAllowsRealApplyOnlyWithMatchingDryRunToken() {
        AutoTuneApplyResult dryRunResult = new AutoTuneApplyResult();
        dryRunResult.setDryRun(true);
        dryRunResult.setSuccess(true);
        AutoTuneApplyResult applyResult = new AutoTuneApplyResult();
        applyResult.setDryRun(false);
        applyResult.setSuccess(true);
        when(autoTuneApplyService.apply(any(AutoTuneApplyRequest.class))).thenReturn(dryRunResult, applyResult);
        AutoTuneChangeCommand command = change(" sys_config ", "ignored", " conveyorStationTaskLimit ", " 12 ");
        List<AutoTuneChangeCommand> changes = Collections.singletonList(command);
 
        AutoTuneApplyResult preview = tools.applyAutoTuneChanges("preview", 10, "agent", true, null, changes);
        AutoTuneApplyResult applied = tools.applyAutoTuneChanges("apply", 10, "agent", false,
                preview.getDryRunToken(), changes);
 
        assertSame(applyResult, applied);
        ArgumentCaptor<AutoTuneApplyRequest> captor = ArgumentCaptor.forClass(AutoTuneApplyRequest.class);
        verify(autoTuneApplyService, times(2)).apply(captor.capture());
        assertEquals(Boolean.TRUE, captor.getAllValues().get(0).getDryRun());
        assertEquals(Boolean.FALSE, captor.getAllValues().get(1).getDryRun());
    }
 
    @Test
    void applyToolRejectsMismatchedDryRunToken() {
        AutoTuneApplyResult dryRunResult = new AutoTuneApplyResult();
        dryRunResult.setDryRun(true);
        dryRunResult.setSuccess(true);
        when(autoTuneApplyService.apply(any(AutoTuneApplyRequest.class))).thenReturn(dryRunResult);
 
        AutoTuneApplyResult preview = tools.applyAutoTuneChanges("preview", 10, "agent", true, null,
                Collections.singletonList(change("sys_config", null, "conveyorStationTaskLimit", "12")));
 
        IllegalArgumentException exception = assertThrows(IllegalArgumentException.class,
                () -> tools.applyAutoTuneChanges("apply", 10, "agent", false, preview.getDryRunToken(),
                        Collections.singletonList(change("sys_config", null, "conveyorStationTaskLimit", "13"))));
 
        assertTrue(exception.getMessage().contains("does not match"));
        verify(autoTuneApplyService, times(1)).apply(any(AutoTuneApplyRequest.class));
    }
 
    @Test
    void applyToolRejectsExpiredDryRunToken() {
        AtomicLong currentTimeMillis = new AtomicLong(1_000L);
        ReflectionTestUtils.invokeMethod(tools, "setCurrentTimeMillisSupplier", (LongSupplier) currentTimeMillis::get);
        AutoTuneApplyResult dryRunResult = new AutoTuneApplyResult();
        dryRunResult.setDryRun(true);
        dryRunResult.setSuccess(true);
        when(autoTuneApplyService.apply(any(AutoTuneApplyRequest.class))).thenReturn(dryRunResult);
        List<AutoTuneChangeCommand> changes = Collections.singletonList(
                change("sys_config", null, "conveyorStationTaskLimit", "12"));
 
        AutoTuneApplyResult preview = tools.applyAutoTuneChanges("preview", 10, "agent", true, null, changes);
        currentTimeMillis.addAndGet(10L * 60L * 1000L + 1L);
        IllegalArgumentException exception = assertThrows(IllegalArgumentException.class,
                () -> tools.applyAutoTuneChanges("apply", 10, "agent", false, preview.getDryRunToken(), changes));
 
        assertTrue(exception.getMessage().contains("expired"));
        verify(autoTuneApplyService, times(1)).apply(any(AutoTuneApplyRequest.class));
    }
 
    @Test
    void rollbackToolDelegatesToApplyServiceRollback() {
        AutoTuneApplyResult expected = new AutoTuneApplyResult();
        when(autoTuneApplyService.rollbackLastSuccessfulJob("bad result")).thenReturn(expected);
 
        AutoTuneApplyResult result = tools.revertLastAutoTuneJob("bad result");
 
        assertSame(expected, result);
        verify(autoTuneApplyService).rollbackLastSuccessfulJob("bad result");
    }
 
    @Test
    void coordinatorSkipsWhenDisabled() {
        when(configService.getConfigValue("aiAutoTuneEnabled", "N")).thenReturn("N");
 
        AutoTuneCoordinatorService.AutoTuneCoordinatorResult result = coordinatorService().runAutoTuneIfEligible();
 
        assertTrue(result.getSkipped());
        assertEquals("disabled", result.getReason());
        verify(wrkMastService, never()).count(any(Wrapper.class));
        verify(autoTuneAgentService, never()).runAutoTune(anyString());
    }
 
    @Test
    void coordinatorSkipsWhenNoActiveTasks() {
        when(configService.getConfigValue("aiAutoTuneEnabled", "N")).thenReturn("Y");
        when(configService.getConfigValue("aiAutoTuneIntervalMinutes", "10")).thenReturn("10");
        when(wrkMastService.count(any(Wrapper.class))).thenReturn(0L);
 
        AutoTuneCoordinatorService.AutoTuneCoordinatorResult result = coordinatorService().runAutoTuneIfEligible();
 
        assertTrue(result.getSkipped());
        assertEquals("no_active_tasks", result.getReason());
        verify(autoTuneAgentService, never()).runAutoTune(anyString());
    }
 
    @Test
    void coordinatorSkipsWhenIntervalNotReached() {
        AiAutoTuneJob recentJob = new AiAutoTuneJob();
        recentJob.setId(11L);
        recentJob.setFinishTime(new Date());
        when(configService.getConfigValue("aiAutoTuneEnabled", "N")).thenReturn("true");
        when(configService.getConfigValue("aiAutoTuneIntervalMinutes", "10")).thenReturn("10");
        when(wrkMastService.count(any(Wrapper.class))).thenReturn(1L);
        when(redisUtil.get(RedisKeyType.AI_AUTO_TUNE_LAST_TRIGGER_GUARD.key)).thenReturn(null);
        when(aiAutoTuneJobService.list(any(Wrapper.class))).thenReturn(Collections.singletonList(recentJob));
 
        AutoTuneCoordinatorService.AutoTuneCoordinatorResult result = coordinatorService().runAutoTuneIfEligible();
 
        assertTrue(result.getSkipped());
        assertEquals("interval_not_reached", result.getReason());
        verify(autoTuneAgentService, never()).runAutoTune(anyString());
    }
 
    @Test
    void coordinatorTriggersAgentWhenEligible() {
        AutoTuneAgentService.AutoTuneAgentResult agentResult = successfulAgentResult();
        when(configService.getConfigValue("aiAutoTuneEnabled", "N")).thenReturn("1");
        when(configService.getConfigValue("aiAutoTuneIntervalMinutes", "10")).thenReturn("10");
        when(wrkMastService.count(any(Wrapper.class))).thenReturn(1L);
        when(redisUtil.get(RedisKeyType.AI_AUTO_TUNE_LAST_TRIGGER_GUARD.key)).thenReturn(null);
        when(aiAutoTuneJobService.list(any(Wrapper.class))).thenReturn(Collections.emptyList());
        when(redisUtil.trySetStringIfAbsent(anyString(), anyString(), anyLong())).thenReturn(true);
        when(autoTuneAgentService.runAutoTune(AutoTuneTriggerType.AUTO.getCode())).thenReturn(agentResult);
 
        AutoTuneCoordinatorService.AutoTuneCoordinatorResult result = coordinatorService().runAutoTuneIfEligible();
 
        assertFalse(result.getSkipped());
        assertTrue(result.getTriggered());
        assertSame(agentResult, result.getAgentResult());
        verify(autoTuneAgentService).runAutoTune(AutoTuneTriggerType.AUTO.getCode());
        verify(operateLogService).save(any());
        verify(redisUtil).set(anyString(), any(), anyLong());
        verify(redisUtil).compareAndDelete(anyString(), anyString());
    }
 
    @Test
    void coordinatorKeepsAgentResultWhenOperateLogFails() {
        AutoTuneAgentService.AutoTuneAgentResult agentResult = successfulAgentResult();
        when(configService.getConfigValue("aiAutoTuneEnabled", "N")).thenReturn("Y");
        when(configService.getConfigValue("aiAutoTuneIntervalMinutes", "10")).thenReturn("10");
        when(wrkMastService.count(any(Wrapper.class))).thenReturn(1L);
        when(redisUtil.get(RedisKeyType.AI_AUTO_TUNE_LAST_TRIGGER_GUARD.key)).thenReturn(null);
        when(aiAutoTuneJobService.list(any(Wrapper.class))).thenReturn(Collections.emptyList());
        when(redisUtil.trySetStringIfAbsent(anyString(), anyString(), anyLong())).thenReturn(true);
        when(autoTuneAgentService.runAutoTune(AutoTuneTriggerType.AUTO.getCode())).thenReturn(agentResult);
        doThrow(new RuntimeException("log failed")).when(operateLogService).save(any());
 
        AutoTuneCoordinatorService.AutoTuneCoordinatorResult result = coordinatorService().runAutoTuneIfEligible();
 
        assertFalse(result.getSkipped());
        assertTrue(result.getTriggered());
        assertSame(agentResult, result.getAgentResult());
        verify(redisUtil).compareAndDelete(anyString(), anyString());
    }
 
    @Test
    void coordinatorRunsAgentAndReleasesLockWhenGuardWriteFails() {
        AutoTuneAgentService.AutoTuneAgentResult agentResult = successfulAgentResult();
        when(configService.getConfigValue("aiAutoTuneEnabled", "N")).thenReturn("Y");
        when(configService.getConfigValue("aiAutoTuneIntervalMinutes", "10")).thenReturn("10");
        when(wrkMastService.count(any(Wrapper.class))).thenReturn(1L);
        when(redisUtil.get(RedisKeyType.AI_AUTO_TUNE_LAST_TRIGGER_GUARD.key)).thenReturn(null);
        when(aiAutoTuneJobService.list(any(Wrapper.class))).thenReturn(Collections.emptyList());
        when(redisUtil.trySetStringIfAbsent(anyString(), anyString(), anyLong())).thenReturn(true);
        doThrow(new RuntimeException("guard failed"))
                .when(redisUtil)
                .set(eq(RedisKeyType.AI_AUTO_TUNE_LAST_TRIGGER_GUARD.key), any(), eq(600L));
        when(autoTuneAgentService.runAutoTune(AutoTuneTriggerType.AUTO.getCode())).thenReturn(agentResult);
 
        AutoTuneCoordinatorService.AutoTuneCoordinatorResult result = coordinatorService().runAutoTuneIfEligible();
 
        assertFalse(result.getSkipped());
        assertTrue(result.getTriggered());
        assertSame(agentResult, result.getAgentResult());
        verify(autoTuneAgentService).runAutoTune(AutoTuneTriggerType.AUTO.getCode());
        verify(redisUtil).compareAndDelete(anyString(), anyString());
    }
 
    @Test
    void coordinatorSetsGuardWhenAgentReturnsFailure() {
        AutoTuneAgentService.AutoTuneAgentResult agentResult = failedAgentResult();
        when(configService.getConfigValue("aiAutoTuneEnabled", "N")).thenReturn("Y");
        when(configService.getConfigValue("aiAutoTuneIntervalMinutes", "10")).thenReturn("10");
        when(wrkMastService.count(any(Wrapper.class))).thenReturn(1L);
        when(redisUtil.get(RedisKeyType.AI_AUTO_TUNE_LAST_TRIGGER_GUARD.key)).thenReturn(null);
        when(aiAutoTuneJobService.list(any(Wrapper.class))).thenReturn(Collections.emptyList());
        when(redisUtil.trySetStringIfAbsent(anyString(), anyString(), anyLong())).thenReturn(true);
        when(autoTuneAgentService.runAutoTune(AutoTuneTriggerType.AUTO.getCode())).thenReturn(agentResult);
 
        AutoTuneCoordinatorService.AutoTuneCoordinatorResult result = coordinatorService().runAutoTuneIfEligible();
 
        assertFalse(result.getSkipped());
        assertSame(agentResult, result.getAgentResult());
        verify(redisUtil).set(eq(RedisKeyType.AI_AUTO_TUNE_LAST_TRIGGER_GUARD.key), any(), eq(600L));
    }
 
    @Test
    void coordinatorSetsGuardWhenAgentThrows() {
        when(configService.getConfigValue("aiAutoTuneEnabled", "N")).thenReturn("Y");
        when(configService.getConfigValue("aiAutoTuneIntervalMinutes", "10")).thenReturn("10");
        when(wrkMastService.count(any(Wrapper.class))).thenReturn(1L);
        when(redisUtil.get(RedisKeyType.AI_AUTO_TUNE_LAST_TRIGGER_GUARD.key)).thenReturn(null);
        when(aiAutoTuneJobService.list(any(Wrapper.class))).thenReturn(Collections.emptyList());
        when(redisUtil.trySetStringIfAbsent(anyString(), anyString(), anyLong())).thenReturn(true);
        when(autoTuneAgentService.runAutoTune(AutoTuneTriggerType.AUTO.getCode())).thenThrow(new RuntimeException("agent failed"));
 
        AutoTuneCoordinatorService.AutoTuneCoordinatorResult result = coordinatorService().runAutoTuneIfEligible();
 
        assertFalse(result.getSkipped());
        assertFalse(result.getAgentResult().getSuccess());
        verify(redisUtil).set(eq(RedisKeyType.AI_AUTO_TUNE_LAST_TRIGGER_GUARD.key), any(), eq(600L));
        verify(redisUtil).compareAndDelete(anyString(), anyString());
    }
 
    @Test
    void coordinatorSkipsWhenRunningLockIsNotAcquired() {
        when(configService.getConfigValue("aiAutoTuneEnabled", "N")).thenReturn("Y");
        when(configService.getConfigValue("aiAutoTuneIntervalMinutes", "10")).thenReturn("10");
        when(wrkMastService.count(any(Wrapper.class))).thenReturn(1L);
        when(redisUtil.get(RedisKeyType.AI_AUTO_TUNE_LAST_TRIGGER_GUARD.key)).thenReturn(null);
        when(aiAutoTuneJobService.list(any(Wrapper.class))).thenReturn(Collections.emptyList());
        when(redisUtil.trySetStringIfAbsent(anyString(), anyString(), anyLong())).thenReturn(false);
 
        AutoTuneCoordinatorService.AutoTuneCoordinatorResult result = coordinatorService().runAutoTuneIfEligible();
 
        assertTrue(result.getSkipped());
        assertEquals("running_lock_not_acquired", result.getReason());
        verify(autoTuneAgentService, never()).runAutoTune(anyString());
        verify(redisUtil, never()).compareAndDelete(anyString(), anyString());
    }
 
    @Test
    void manualTriggerRunsAgentWithRunningLockAndDoesNotWriteSchedulerGuard() {
        AutoTuneAgentService.AutoTuneAgentResult agentResult = successfulAgentResult();
        agentResult.setTriggerType(AutoTuneTriggerType.MANUAL.getCode());
        when(configService.getConfigValue("aiAutoTuneIntervalMinutes", "10")).thenReturn("10");
        when(wrkMastService.count(any(Wrapper.class))).thenReturn(1L);
        when(redisUtil.trySetStringIfAbsent(anyString(), anyString(), anyLong())).thenReturn(true);
        when(autoTuneAgentService.runAutoTune(AutoTuneTriggerType.MANUAL.getCode())).thenReturn(agentResult);
 
        AutoTuneCoordinatorService.AutoTuneCoordinatorResult result = coordinatorService().runManualAutoTune();
 
        assertFalse(result.getSkipped());
        assertTrue(result.getTriggered());
        assertSame(agentResult, result.getAgentResult());
        verify(autoTuneAgentService).runAutoTune(AutoTuneTriggerType.MANUAL.getCode());
        verify(redisUtil, never()).set(eq(RedisKeyType.AI_AUTO_TUNE_LAST_TRIGGER_GUARD.key), any(), anyLong());
        verify(redisUtil).compareAndDelete(anyString(), anyString());
 
        ArgumentCaptor<OperateLog> operateLogCaptor = ArgumentCaptor.forClass(OperateLog.class);
        verify(operateLogService).save(operateLogCaptor.capture());
        assertEquals("ai_auto_tune_manual_trigger", operateLogCaptor.getValue().getAction());
 
        ArgumentCaptor<AiAutoTuneJob> jobCaptor = ArgumentCaptor.forClass(AiAutoTuneJob.class);
        verify(aiAutoTuneJobService).save(jobCaptor.capture());
        AiAutoTuneJob auditJob = jobCaptor.getValue();
        assertEquals(AutoTuneTriggerType.MANUAL.getCode(), auditJob.getTriggerType());
        assertEquals(AutoTuneJobStatus.NO_CHANGE.getCode(), auditJob.getStatus());
        assertNotNull(auditJob.getStartTime());
        assertNotNull(auditJob.getFinishTime());
        assertEquals(1, auditJob.getHasActiveTasks());
        assertEquals(AiPromptScene.AUTO_TUNE_DISPATCH.getCode(), auditJob.getPromptSceneCode());
        assertEquals("no changes needed", auditJob.getSummary());
        assertEquals(10, auditJob.getIntervalBefore());
        assertEquals(10, auditJob.getIntervalAfter());
        assertEquals(0, auditJob.getSuccessCount());
        assertEquals(0, auditJob.getRejectCount());
        assertEquals(1, auditJob.getLlmCallCount());
        assertEquals(10, auditJob.getPromptTokens());
        assertEquals(5, auditJob.getCompletionTokens());
        assertEquals(15, auditJob.getTotalTokens());
    }
 
    @Test
    void manualTriggerAuditsSuccessOnlyWhenActualApplyHappened() {
        AutoTuneAgentService.AutoTuneAgentResult agentResult = actualAppliedAgentResult();
        agentResult.setTriggerType(AutoTuneTriggerType.MANUAL.getCode());
        when(configService.getConfigValue("aiAutoTuneIntervalMinutes", "10")).thenReturn("10");
        when(wrkMastService.count(any(Wrapper.class))).thenReturn(1L);
        when(redisUtil.trySetStringIfAbsent(anyString(), anyString(), anyLong())).thenReturn(true);
        when(autoTuneAgentService.runAutoTune(AutoTuneTriggerType.MANUAL.getCode())).thenReturn(agentResult);
 
        AutoTuneCoordinatorService.AutoTuneCoordinatorResult result = coordinatorService().runManualAutoTune();
 
        assertFalse(result.getSkipped());
        ArgumentCaptor<AiAutoTuneJob> jobCaptor = ArgumentCaptor.forClass(AiAutoTuneJob.class);
        verify(aiAutoTuneJobService).save(jobCaptor.capture());
        AiAutoTuneJob auditJob = jobCaptor.getValue();
        assertEquals(AutoTuneJobStatus.SUCCESS.getCode(), auditJob.getStatus());
        assertEquals(3, auditJob.getSuccessCount());
        assertEquals(0, auditJob.getRejectCount());
    }
 
    @Test
    void manualTriggerWritesMcpCallAuditUnderAgentJob() {
        AutoTuneAgentService.AutoTuneAgentResult agentResult = actualAppliedAgentResult();
        agentResult.setTriggerType(AutoTuneTriggerType.MANUAL.getCode());
        agentResult.setMcpCalls(Collections.singletonList(mcpCallResult()));
        when(configService.getConfigValue("aiAutoTuneIntervalMinutes", "10")).thenReturn("10");
        when(wrkMastService.count(any(Wrapper.class))).thenReturn(1L);
        when(redisUtil.trySetStringIfAbsent(anyString(), anyString(), anyLong())).thenReturn(true);
        when(autoTuneAgentService.runAutoTune(AutoTuneTriggerType.MANUAL.getCode())).thenReturn(agentResult);
        when(aiAutoTuneJobService.save(any(AiAutoTuneJob.class))).thenAnswer(invocation -> {
            AiAutoTuneJob job = invocation.getArgument(0);
            job.setId(88L);
            return true;
        });
        when(aiAutoTuneMcpCallService.saveBatch(any())).thenReturn(true);
 
        coordinatorService().runManualAutoTune();
 
        ArgumentCaptor<List> mcpCallsCaptor = ArgumentCaptor.forClass(List.class);
        verify(aiAutoTuneMcpCallService).saveBatch(mcpCallsCaptor.capture());
        List<?> savedCalls = mcpCallsCaptor.getValue();
        assertEquals(1, savedCalls.size());
        com.zy.ai.entity.AiAutoTuneMcpCall savedCall = (com.zy.ai.entity.AiAutoTuneMcpCall) savedCalls.get(0);
        assertEquals(88L, savedCall.getAgentJobId());
        assertEquals("wcs_local_dispatch_apply_auto_tune_changes", savedCall.getToolName());
        assertEquals(1, savedCall.getDryRun());
        assertEquals(77L, savedCall.getApplyJobId());
    }
 
    @Test
    void manualTriggerPreservesFullAuditSummaryAndErrorMessage() {
        String longSummary = "自动调参失败原因".repeat(120);
        AutoTuneAgentService.AutoTuneAgentResult agentResult = failedAgentResult();
        agentResult.setTriggerType(AutoTuneTriggerType.MANUAL.getCode());
        agentResult.setSummary(longSummary);
        when(configService.getConfigValue("aiAutoTuneIntervalMinutes", "10")).thenReturn("10");
        when(wrkMastService.count(any(Wrapper.class))).thenReturn(1L);
        when(redisUtil.trySetStringIfAbsent(anyString(), anyString(), anyLong())).thenReturn(true);
        when(autoTuneAgentService.runAutoTune(AutoTuneTriggerType.MANUAL.getCode())).thenReturn(agentResult);
 
        coordinatorService().runManualAutoTune();
 
        ArgumentCaptor<AiAutoTuneJob> jobCaptor = ArgumentCaptor.forClass(AiAutoTuneJob.class);
        verify(aiAutoTuneJobService).save(jobCaptor.capture());
        AiAutoTuneJob auditJob = jobCaptor.getValue();
        assertEquals(longSummary, auditJob.getSummary());
        assertEquals(longSummary, auditJob.getErrorMessage());
    }
 
    @Test
    void manualTriggerSkipsWhenRunningLockIsNotAcquired() {
        when(redisUtil.trySetStringIfAbsent(anyString(), anyString(), anyLong())).thenReturn(false);
 
        AutoTuneCoordinatorService.AutoTuneCoordinatorResult result = coordinatorService().runManualAutoTune();
 
        assertTrue(result.getSkipped());
        assertEquals("running_lock_not_acquired", result.getReason());
        verify(autoTuneAgentService, never()).runAutoTune(anyString());
        verify(redisUtil, never()).compareAndDelete(anyString(), anyString());
    }
 
    @Test
    void agentExecutesSnapshotDryRunAndRealApplyToolSequence() {
        AutoTuneAgentServiceImpl service = new AutoTuneAgentServiceImpl(
                llmChatService,
                mcpToolManager,
                aiPromptTemplateService);
        AiPromptTemplate promptTemplate = new AiPromptTemplate();
        promptTemplate.setContent("system prompt");
        when(aiPromptTemplateService.resolvePublished("wcs_auto_tune_dispatch")).thenReturn(promptTemplate);
        when(mcpToolManager.buildOpenAiTools()).thenReturn(allowedOpenAiTools());
        when(mcpToolManager.callTool(any(), any(JSONObject.class))).thenAnswer(invocation -> {
            String toolName = invocation.getArgument(0);
            JSONObject arguments = invocation.getArgument(1);
            if ("wcs_local_dispatch_apply_auto_tune_changes".equals(toolName)
                    && Boolean.TRUE.equals(arguments.getBoolean("dryRun"))) {
                LinkedHashMap<String, Object> dryRunOutput = new LinkedHashMap<>();
                dryRunOutput.put("success", true);
                dryRunOutput.put("dryRun", true);
                dryRunOutput.put("dryRunToken", "token-123");
                return dryRunOutput;
            }
            if ("wcs_local_dispatch_apply_auto_tune_changes".equals(toolName)
                    && Boolean.FALSE.equals(arguments.getBoolean("dryRun"))) {
                LinkedHashMap<String, Object> applyOutput = new LinkedHashMap<>();
                applyOutput.put("success", true);
                applyOutput.put("dryRun", false);
                applyOutput.put("successCount", 1);
                applyOutput.put("rejectCount", 0);
                return applyOutput;
            }
            return Collections.singletonMap("ok", true);
        });
        when(llmChatService.chatCompletionOrThrow(any(), anyDouble(), anyInt(), any()))
                .thenReturn(
                        response("read snapshot", toolCall("call_1", "wcs_local_dispatch_get_auto_tune_snapshot", "{}"), 10, 5),
                        response("dry-run first", toolCall("call_2", "wcs_local_dispatch_apply_auto_tune_changes",
                                "{\"dryRun\":true,\"changes\":[{\"targetType\":\"sys_config\",\"targetKey\":\"conveyorStationTaskLimit\",\"newValue\":\"12\"}]}"), 11, 6),
                        response("apply after dry-run", toolCall("call_3", "wcs_local_dispatch_apply_auto_tune_changes",
                                "{\"dryRun\":false,\"dryRunToken\":\"token-123\",\"changes\":[{\"targetType\":\"sys_config\",\"targetKey\":\"conveyorStationTaskLimit\",\"newValue\":\"12\"}]}"), 12, 7),
                        response("已完成自动调参", null, 13, 8)
                );
 
        AutoTuneAgentService.AutoTuneAgentResult result = service.runAutoTune("scheduler");
 
        assertTrue(result.getSuccess());
        assertEquals("scheduler", result.getTriggerType());
        assertEquals(3, result.getToolCallCount());
        assertEquals(4, result.getLlmCallCount());
        assertEquals(46L, result.getPromptTokens());
        assertEquals(26L, result.getCompletionTokens());
        assertEquals(72L, result.getTotalTokens());
        assertTrue(result.getSummary().contains("已完成自动调参"));
        assertTrue(result.getActualApplyCalled());
        assertFalse(result.getRollbackCalled());
        assertEquals(1, result.getSuccessCount());
        assertEquals(0, result.getRejectCount());
 
        ArgumentCaptor<String> toolNameCaptor = ArgumentCaptor.forClass(String.class);
        ArgumentCaptor<JSONObject> argumentCaptor = ArgumentCaptor.forClass(JSONObject.class);
        verify(mcpToolManager, times(3)).callTool(toolNameCaptor.capture(), argumentCaptor.capture());
        assertEquals("wcs_local_dispatch_get_auto_tune_snapshot", toolNameCaptor.getAllValues().get(0));
        assertEquals("wcs_local_dispatch_apply_auto_tune_changes", toolNameCaptor.getAllValues().get(1));
        assertEquals(Boolean.TRUE, argumentCaptor.getAllValues().get(1).getBoolean("dryRun"));
        assertEquals(Boolean.FALSE, argumentCaptor.getAllValues().get(2).getBoolean("dryRun"));
        assertEquals("token-123", argumentCaptor.getAllValues().get(2).getString("dryRunToken"));
 
        ArgumentCaptor<List<Object>> toolsCaptor = ArgumentCaptor.forClass(List.class);
        verify(llmChatService, times(4)).chatCompletionOrThrow(any(), anyDouble(), anyInt(), toolsCaptor.capture());
        List<String> visibleToolNames = toolNames(toolsCaptor.getAllValues().get(0));
        assertEquals(4, visibleToolNames.size());
        assertTrue(visibleToolNames.contains("wcs_local_dispatch_get_auto_tune_snapshot"));
        assertTrue(visibleToolNames.contains("wcs_local_dispatch_get_recent_auto_tune_jobs"));
        assertTrue(visibleToolNames.contains("wcs_local_dispatch_apply_auto_tune_changes"));
        assertTrue(visibleToolNames.contains("wcs_local_dispatch_revert_last_auto_tune_job"));
        assertFalse(visibleToolNames.contains("wcs_local_device_get_crn_status"));
    }
 
    @Test
    void agentForcesAutoTriggerTypeOnApplyTools() {
        AutoTuneAgentServiceImpl service = agentService();
        when(mcpToolManager.buildOpenAiTools()).thenReturn(allowedOpenAiTools());
        when(mcpToolManager.callTool(any(), any(JSONObject.class))).thenReturn(Collections.singletonMap("ok", true));
        when(llmChatService.chatCompletionOrThrow(any(), anyDouble(), anyInt(), any()))
                .thenReturn(
                        response("snapshot", toolCall("call_1", "wcs_local_dispatch_get_auto_tune_snapshot",
                                "{}"), 10, 5),
                        response("dry run", toolCall("call_2", "wcs_local_dispatch_apply_auto_tune_changes",
                                "{\"dryRun\":true,\"changes\":[]}"), 10, 5),
                        response("done", null, 10, 5)
                );
 
        AutoTuneAgentService.AutoTuneAgentResult result = service.runAutoTune("auto");
 
        assertTrue(result.getSuccess());
        ArgumentCaptor<JSONObject> argumentCaptor = ArgumentCaptor.forClass(JSONObject.class);
        verify(mcpToolManager).callTool(eq("wcs_local_dispatch_apply_auto_tune_changes"), argumentCaptor.capture());
        assertEquals("auto", argumentCaptor.getValue().getString("triggerType"));
    }
 
    @Test
    void agentMarksSnapshotOnlyRunAsNoActualMutationEvenIfAssistantClaimsApplied() {
        AutoTuneAgentServiceImpl service = agentService();
        when(mcpToolManager.buildOpenAiTools()).thenReturn(allowedOpenAiTools());
        when(mcpToolManager.callTool(any(), any(JSONObject.class))).thenReturn(Collections.singletonMap("ok", true));
        when(llmChatService.chatCompletionOrThrow(any(), anyDouble(), anyInt(), any()))
                .thenReturn(
                        response("snapshot", toolCall("call_1", "wcs_local_dispatch_get_auto_tune_snapshot", "{}"), 10, 5),
                        response("已执行 dry-run 并实际应用成功", null, 10, 5)
                );
 
        AutoTuneAgentService.AutoTuneAgentResult result = service.runAutoTune("manual");
 
        assertTrue(result.getSuccess());
        assertFalse(result.getActualApplyCalled());
        assertFalse(result.getRollbackCalled());
        assertEquals(0, result.getSuccessCount());
        assertTrue(result.getSummary().startsWith("自动调参 Agent 未调用实际应用或回滚工具,未修改运行参数。"));
    }
 
    @Test
    void agentMarksRejectedDryRunAsFailedAndFeedsBackGenericConstraints() {
        AutoTuneAgentServiceImpl service = agentService();
        when(mcpToolManager.buildOpenAiTools()).thenReturn(allowedOpenAiTools());
        when(mcpToolManager.callTool(any(), any(JSONObject.class))).thenAnswer(invocation -> {
            String toolName = invocation.getArgument(0);
            if ("wcs_local_dispatch_get_auto_tune_snapshot".equals(toolName)) {
                return Collections.singletonMap("ok", true);
            }
            LinkedHashMap<String, Object> rejectedChange = new LinkedHashMap<>();
            rejectedChange.put("targetType", "sys_config");
            rejectedChange.put("targetId", "");
            rejectedChange.put("targetKey", "crnOutBatchRunningLimit");
            rejectedChange.put("oldValue", "5");
            rejectedChange.put("requestedValue", "9");
            rejectedChange.put("resultStatus", "rejected");
            rejectedChange.put("rejectReason", "crnOutBatchRunningLimit 单次调整步长不能超过 3");
 
            LinkedHashMap<String, Object> dryRunOutput = new LinkedHashMap<>();
            dryRunOutput.put("success", false);
            dryRunOutput.put("dryRun", true);
            dryRunOutput.put("rejectCount", 1);
            dryRunOutput.put("changes", Collections.singletonList(rejectedChange));
            return dryRunOutput;
        });
        when(llmChatService.chatCompletionOrThrow(any(), anyDouble(), anyInt(), any()))
                .thenReturn(
                        response("snapshot", toolCall("call_1", "wcs_local_dispatch_get_auto_tune_snapshot", "{}"), 10, 5),
                        response("dry run rejected", toolCall("call_2", "wcs_local_dispatch_apply_auto_tune_changes",
                                "{\"dryRun\":true,\"changes\":[{\"targetType\":\"sys_config\",\"targetKey\":\"crnOutBatchRunningLimit\",\"newValue\":\"9\"}]}"), 10, 5),
                        response("停止实际应用", null, 10, 5)
                );
 
        AutoTuneAgentService.AutoTuneAgentResult result = service.runAutoTune("auto");
 
        assertFalse(result.getSuccess());
        assertTrue(result.getSummary().contains("被拒绝的 dry-run/apply"));
        assertEquals(0, result.getSuccessCount());
        assertEquals(1, result.getRejectCount());
        ArgumentCaptor<List<ChatCompletionRequest.Message>> messagesCaptor = ArgumentCaptor.forClass(List.class);
        verify(llmChatService, times(3)).chatCompletionOrThrow(messagesCaptor.capture(), anyDouble(), anyInt(), any());
        String userInstruction = messagesCaptor.getAllValues().stream()
                .flatMap(List::stream)
                .filter(message -> "user".equals(message.getRole()))
                .map(ChatCompletionRequest.Message::getContent)
                .filter(content -> content != null && content.contains("ruleSnapshot"))
                .findFirst()
                .orElse("");
        assertTrue(userInstruction.contains("所有提交给"));
        assertTrue(userInstruction.contains("minValue"));
        assertTrue(userInstruction.contains("cooldownMinutes"));
        String rejectedToolMessage = messagesCaptor.getAllValues().stream()
                .flatMap(List::stream)
                .filter(message -> "tool".equals(message.getRole()))
                .map(ChatCompletionRequest.Message::getContent)
                .filter(content -> content != null && content.contains("rejectCount"))
                .findFirst()
                .orElse("");
        assertTrue(rejectedToolMessage.contains("禁止继续实际应用"));
        assertTrue(rejectedToolMessage.contains("ruleSnapshot"));
        assertTrue(rejectedToolMessage.contains("maxStep"));
        assertFalse(rejectedToolMessage.contains("outBufferCapacity"));
    }
 
    @Test
    void agentKeepsOriginalLlmFailureReason() {
        AutoTuneAgentServiceImpl service = agentService();
        when(mcpToolManager.buildOpenAiTools()).thenReturn(allowedOpenAiTools());
        when(llmChatService.chatCompletionOrThrow(any(), anyDouble(), anyInt(), any()))
                .thenThrow(new IllegalStateException("OpenAI Responses 调用失败: HTTP 502"));
 
        AutoTuneAgentService.AutoTuneAgentResult result = service.runAutoTune("auto");
 
        assertFalse(result.getSuccess());
        assertTrue(result.getSummary().contains("OpenAI Responses 调用失败: HTTP 502"));
        assertFalse(result.getSummary().contains("LLM returned empty response"));
    }
 
    @Test
    void agentFailsAndDoesNotExecuteDisallowedToolCall() {
        AutoTuneAgentServiceImpl service = agentService();
        when(mcpToolManager.buildOpenAiTools()).thenReturn(allowedOpenAiTools());
        when(llmChatService.chatCompletionOrThrow(any(), anyDouble(), anyInt(), any()))
                .thenReturn(response("bad tool", toolCall("call_1", "wcs_local_device_get_crn_status", "{}"), 10, 5));
 
        AutoTuneAgentService.AutoTuneAgentResult result = service.runAutoTune("scheduler");
 
        assertFalse(result.getSuccess());
        assertEquals(0, result.getToolCallCount());
        assertTrue(result.getSummary().contains("Disallowed auto-tune MCP tool"));
        verify(mcpToolManager, never()).callTool(any(), any(JSONObject.class));
    }
 
    @Test
    void agentFailsWhenAllowedToolThrows() {
        AutoTuneAgentServiceImpl service = agentService();
        when(mcpToolManager.buildOpenAiTools()).thenReturn(allowedOpenAiTools());
        when(mcpToolManager.callTool(any(), any(JSONObject.class))).thenThrow(new RuntimeException("boom"));
        when(llmChatService.chatCompletionOrThrow(any(), anyDouble(), anyInt(), any()))
                .thenReturn(response("snapshot", toolCall("call_1", "wcs_local_dispatch_get_auto_tune_snapshot", "{}"), 10, 5));
 
        AutoTuneAgentService.AutoTuneAgentResult result = service.runAutoTune("scheduler");
 
        assertFalse(result.getSuccess());
        assertEquals(0, result.getToolCallCount());
        assertTrue(result.getSummary().contains("Auto-tune MCP tool failed"));
        verify(mcpToolManager).callTool(any(), any(JSONObject.class));
    }
 
    @Test
    void agentFailsWhenLlmReturnsNoToolCalls() {
        AutoTuneAgentServiceImpl service = agentService();
        when(mcpToolManager.buildOpenAiTools()).thenReturn(allowedOpenAiTools());
        when(llmChatService.chatCompletionOrThrow(any(), anyDouble(), anyInt(), any()))
                .thenReturn(response("no changes needed", null, 10, 5));
 
        AutoTuneAgentService.AutoTuneAgentResult result = service.runAutoTune("scheduler");
 
        assertFalse(result.getSuccess());
        assertEquals(0, result.getToolCallCount());
        assertTrue(result.getSummary().contains("未调用任何允许的 MCP 工具"));
    }
 
    @Test
    void agentFailsWhenMaxRoundsReached() {
        AutoTuneAgentServiceImpl service = agentService();
        when(mcpToolManager.buildOpenAiTools()).thenReturn(allowedOpenAiTools());
        when(mcpToolManager.callTool(any(), any(JSONObject.class))).thenReturn(Collections.singletonMap("ok", true));
        when(llmChatService.chatCompletionOrThrow(any(), anyDouble(), anyInt(), any()))
                .thenReturn(response("keep going", toolCall("call_1", "wcs_local_dispatch_get_auto_tune_snapshot", "{}"), 10, 5));
 
        AutoTuneAgentService.AutoTuneAgentResult result = service.runAutoTune("scheduler");
 
        assertFalse(result.getSuccess());
        assertEquals(10, result.getToolCallCount());
        assertTrue(result.getMaxRoundsReached());
        assertTrue(result.getSummary().contains("达到最大工具调用轮次"));
    }
 
    private AutoTuneAgentServiceImpl agentService() {
        AiPromptTemplate promptTemplate = new AiPromptTemplate();
        promptTemplate.setContent("system prompt");
        when(aiPromptTemplateService.resolvePublished("wcs_auto_tune_dispatch")).thenReturn(promptTemplate);
        return new AutoTuneAgentServiceImpl(llmChatService, mcpToolManager, aiPromptTemplateService);
    }
 
    private AutoTuneCoordinatorServiceImpl coordinatorService() {
        return new AutoTuneCoordinatorServiceImpl(
                configService,
                wrkMastService,
                aiAutoTuneJobService,
                aiAutoTuneMcpCallService,
                autoTuneAgentService,
                redisUtil,
                operateLogService);
    }
 
    private AutoTuneAgentService.AutoTuneAgentResult successfulAgentResult() {
        AutoTuneAgentService.AutoTuneAgentResult result = new AutoTuneAgentService.AutoTuneAgentResult();
        result.setSuccess(true);
        result.setTriggerType(AutoTuneTriggerType.AUTO.getCode());
        result.setSummary("no changes needed");
        result.setToolCallCount(1);
        result.setLlmCallCount(1);
        result.setPromptTokens(10L);
        result.setCompletionTokens(5L);
        result.setTotalTokens(15L);
        result.setMaxRoundsReached(false);
        result.setActualApplyCalled(false);
        result.setRollbackCalled(false);
        result.setSuccessCount(0);
        result.setRejectCount(0);
        return result;
    }
 
    private AutoTuneAgentService.AutoTuneAgentResult actualAppliedAgentResult() {
        AutoTuneAgentService.AutoTuneAgentResult result = successfulAgentResult();
        result.setSummary("applied");
        result.setActualApplyCalled(true);
        result.setSuccessCount(3);
        result.setRejectCount(0);
        return result;
    }
 
    private AutoTuneAgentService.McpCallResult mcpCallResult() {
        AutoTuneAgentService.McpCallResult result = new AutoTuneAgentService.McpCallResult();
        result.setCallSeq(1);
        result.setToolName("wcs_local_dispatch_apply_auto_tune_changes");
        result.setStatus("success");
        result.setDryRun(true);
        result.setApplyJobId(77L);
        result.setSuccessCount(1);
        result.setRejectCount(0);
        result.setDurationMs(12L);
        result.setRequestJson("{\"dryRun\":true}");
        result.setResponseJson("{\"success\":true}");
        return result;
    }
 
    private AutoTuneAgentService.AutoTuneAgentResult failedAgentResult() {
        AutoTuneAgentService.AutoTuneAgentResult result = successfulAgentResult();
        result.setSuccess(false);
        result.setSummary("failed");
        return result;
    }
 
    private AutoTuneChangeCommand change(String targetType, String targetId, String targetKey, String newValue) {
        AutoTuneChangeCommand command = new AutoTuneChangeCommand();
        command.setTargetType(targetType);
        command.setTargetId(targetId);
        command.setTargetKey(targetKey);
        command.setNewValue(newValue);
        return command;
    }
 
    private List<Object> allowedOpenAiTools() {
        List<Object> tools = new ArrayList<>();
        tools.add(openAiTool("wcs_local_dispatch_get_auto_tune_snapshot"));
        tools.add(openAiTool("wcs_local_dispatch_get_recent_auto_tune_jobs"));
        tools.add(openAiTool("wcs_local_dispatch_apply_auto_tune_changes"));
        tools.add(openAiTool("wcs_local_dispatch_revert_last_auto_tune_job"));
        tools.add(openAiTool("wcs_local_device_get_crn_status"));
        return tools;
    }
 
    private Map<String, Object> openAiTool(String name) {
        LinkedHashMap<String, Object> function = new LinkedHashMap<>();
        function.put("name", name);
        function.put("parameters", Collections.emptyMap());
 
        LinkedHashMap<String, Object> tool = new LinkedHashMap<>();
        tool.put("type", "function");
        tool.put("function", function);
        return tool;
    }
 
    private List<String> toolNames(List<Object> tools) {
        List<String> names = new ArrayList<>();
        for (Object tool : tools) {
            Map<?, ?> toolMap = (Map<?, ?>) tool;
            Map<?, ?> function = (Map<?, ?>) toolMap.get("function");
            names.add(String.valueOf(function.get("name")));
        }
        return names;
    }
 
    private ChatCompletionResponse response(String content,
                                            ChatCompletionRequest.ToolCall toolCall,
                                            int promptTokens,
                                            int completionTokens) {
        ChatCompletionRequest.Message message = new ChatCompletionRequest.Message();
        message.setRole("assistant");
        message.setContent(content);
        if (toolCall != null) {
            message.setTool_calls(Collections.singletonList(toolCall));
        }
 
        ChatCompletionResponse.Choice choice = new ChatCompletionResponse.Choice();
        choice.setIndex(0);
        choice.setMessage(message);
 
        ChatCompletionResponse.Usage usage = new ChatCompletionResponse.Usage();
        usage.setPromptTokens(promptTokens);
        usage.setCompletionTokens(completionTokens);
        usage.setTotalTokens(promptTokens + completionTokens);
 
        ChatCompletionResponse response = new ChatCompletionResponse();
        List<ChatCompletionResponse.Choice> choices = new ArrayList<>();
        choices.add(choice);
        response.setChoices(choices);
        response.setUsage(usage);
        return response;
    }
 
    private ChatCompletionRequest.ToolCall toolCall(String id, String name, String arguments) {
        ChatCompletionRequest.Function function = new ChatCompletionRequest.Function();
        function.setName(name);
        function.setArguments(arguments);
 
        ChatCompletionRequest.ToolCall toolCall = new ChatCompletionRequest.ToolCall();
        toolCall.setId(id);
        toolCall.setType("function");
        toolCall.setFunction(function);
        return toolCall;
    }
}