-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtest_command_executed.py
More file actions
1106 lines (952 loc) · 42.2 KB
/
Copy pathtest_command_executed.py
File metadata and controls
1106 lines (952 loc) · 42.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Tests for CommandExecutedCriterion."""
from datetime import datetime
from coder_eval.criteria.command_executed import _MAX_PATTERN_SEARCH_LEN, _match_haystacks, _normalize_shell
from coder_eval.evaluation.checker import SuccessChecker
from coder_eval.models import CommandExecutedCriterion
from coder_eval.models.results import TurnRecord
from coder_eval.models.telemetry import CommandTelemetry
class MockSandbox:
"""Mock sandbox for testing (not used by CommandExecutedChecker but required by SuccessChecker)."""
def __init__(self):
self.sandbox_dir = None
def _make_command(
tool_name: str = "Bash",
parameters: dict | None = None,
result_status: str = "success",
tool_id: str = "tool-1",
) -> CommandTelemetry:
"""Helper to create a CommandTelemetry instance."""
return CommandTelemetry(
tool_name=tool_name,
tool_id=tool_id,
timestamp=datetime.now(),
parameters=parameters or {},
result_status=result_status,
)
def _make_turn(commands: list[CommandTelemetry], iteration: int = 1, crashed: bool = False) -> TurnRecord:
"""Helper to create a TurnRecord with commands."""
return TurnRecord(
iteration=iteration,
user_input="test prompt",
agent_output="test output",
commands=commands,
crashed=crashed,
)
class TestCommandExecutedCriterion:
"""Test suite for CommandExecutedCriterion."""
def test_match_found(self):
"""Test matching a Bash curl command with pattern."""
sandbox = MockSandbox()
turn_records = [
_make_turn(
[
_make_command(
tool_name="Bash",
parameters={"command": "curl https://wttr.in/London"},
result_status="success",
),
]
)
]
criterion = CommandExecutedCriterion(
description="Agent used curl to fetch weather",
tool_name="Bash",
command_pattern=r"curl.*wttr\.in",
min_count=1,
require_success=True,
)
checker = SuccessChecker(sandbox)
result = checker.check(criterion, turn_records=turn_records)
assert result.score == 1.0
assert result.error is None
assert "1/1" in result.details
def test_no_match(self):
"""Test when commands exist but none match the pattern."""
sandbox = MockSandbox()
turn_records = [
_make_turn(
[
_make_command(
tool_name="Bash",
parameters={"command": "ls -la"},
result_status="success",
),
]
)
]
criterion = CommandExecutedCriterion(
description="Agent used curl",
tool_name="Bash",
command_pattern=r"curl",
min_count=1,
)
checker = SuccessChecker(sandbox)
result = checker.check(criterion, turn_records=turn_records)
assert result.score == 0.0
assert result.error is None
def test_no_turn_records(self):
"""Test when turn_records is None."""
sandbox = MockSandbox()
criterion = CommandExecutedCriterion(
description="Agent used curl",
command_pattern=r"curl",
min_count=1,
)
checker = SuccessChecker(sandbox)
result = checker.check(criterion, turn_records=None)
assert result.score == 0.0
assert result.error is not None
assert "turn_records" in result.error
def test_empty_commands(self):
"""Turns exist but have no commands ⇒ score by the same ``min_count`` math.
Used to short-circuit on a separate ``"No commands found"`` branch, but
that branch returned ``0.0`` even when ``min_count=0`` (the negative-
assertion pattern), which was wrong. Now the empty case falls through
to the normal scoring math: with ``min_count=1`` and zero matches, the
score is ``0/1 = 0.0`` and the details mirror the positive shape.
"""
sandbox = MockSandbox()
turn_records = [_make_turn(commands=[])]
criterion = CommandExecutedCriterion(
description="Agent used any command",
min_count=1,
)
checker = SuccessChecker(sandbox)
result = checker.check(criterion, turn_records=turn_records)
assert result.score == 0.0
assert "0/1 required" in result.details
def test_tool_name_filter(self):
"""Test that tool_name filter only counts matching tools."""
sandbox = MockSandbox()
turn_records = [
_make_turn(
[
_make_command(tool_name="Read", parameters={"file_path": "main.py"}, tool_id="t1"),
_make_command(tool_name="Bash", parameters={"command": "python main.py"}, tool_id="t2"),
_make_command(tool_name="Read", parameters={"file_path": "test.py"}, tool_id="t3"),
]
)
]
criterion = CommandExecutedCriterion(
description="Agent used Read tool",
tool_name="Read",
min_count=2,
)
checker = SuccessChecker(sandbox)
result = checker.check(criterion, turn_records=turn_records)
assert result.score == 1.0
assert "2/2" in result.details
def test_require_success(self):
"""Test that require_success filters out failed commands."""
sandbox = MockSandbox()
turn_records = [
_make_turn(
[
_make_command(
tool_name="Bash",
parameters={"command": "curl https://api.example.com"},
result_status="error",
tool_id="t1",
),
_make_command(
tool_name="Bash",
parameters={"command": "curl https://api.example.com"},
result_status="success",
tool_id="t2",
),
]
)
]
criterion = CommandExecutedCriterion(
description="Agent successfully used curl",
tool_name="Bash",
command_pattern=r"curl",
min_count=2,
require_success=True,
)
checker = SuccessChecker(sandbox)
result = checker.check(criterion, turn_records=turn_records)
# Only 1 successful curl, need 2
assert result.score == 0.5
def test_partial_score(self):
"""Test fractional scoring when min_count > matches found."""
sandbox = MockSandbox()
turn_records = [
_make_turn(
[
_make_command(tool_name="Bash", parameters={"command": "git add ."}, tool_id="t1"),
_make_command(tool_name="Bash", parameters={"command": "git commit -m 'test'"}, tool_id="t2"),
]
)
]
criterion = CommandExecutedCriterion(
description="Agent used git commands",
tool_name="Bash",
command_pattern=r"git",
min_count=3,
)
checker = SuccessChecker(sandbox)
result = checker.check(criterion, turn_records=turn_records)
# 2 matches out of 3 required
assert abs(result.score - 2.0 / 3.0) < 0.01
def test_match_multiline_command(self):
"""`.` must span newlines so backslash-continued commands match."""
sandbox = MockSandbox()
multiline_cmd = (
'uip is resources execute create "salesforce" "Contact" \\\n'
' --connection-id "abc-123" \\\n'
' --body \'{"LastName": "Smith"}\' \\\n'
" --output json"
)
turn_records = [
_make_turn(
[
_make_command(
tool_name="Bash",
parameters={"command": multiline_cmd},
result_status="success",
),
]
)
]
criterion = CommandExecutedCriterion(
description="Agent ran execute create with --body",
tool_name="Bash",
command_pattern=r"uip\s+is\s+resources\s+execute\s+create.*--body",
min_count=1,
)
checker = SuccessChecker(sandbox)
result = checker.check(criterion, turn_records=turn_records)
assert result.score == 1.0
assert result.error is None
def test_exclude_pattern_multiline(self):
"""`exclude_pattern` should also span newlines (DOTALL) for symmetry."""
sandbox = MockSandbox()
help_cmd = "uip foo \\\n --help"
real_cmd = "uip foo \\\n --bar"
turn_records = [
_make_turn(
[
_make_command(tool_name="Bash", parameters={"command": help_cmd}, tool_id="t1"),
_make_command(tool_name="Bash", parameters={"command": real_cmd}, tool_id="t2"),
]
)
]
criterion = CommandExecutedCriterion(
description="Agent ran uip foo (not --help)",
tool_name="Bash",
command_pattern=r"uip\s+foo",
exclude_pattern=r"foo.*--help",
min_count=1,
)
checker = SuccessChecker(sandbox)
result = checker.check(criterion, turn_records=turn_records)
assert result.score == 1.0
assert "1/1" in result.details
def test_invalid_regex(self):
"""Test that invalid regex pattern returns score=0.0 with error."""
sandbox = MockSandbox()
turn_records = [
_make_turn(
[
_make_command(tool_name="Bash", parameters={"command": "ls"}),
]
)
]
criterion = CommandExecutedCriterion(
description="Bad regex",
command_pattern=r"[invalid",
min_count=1,
)
checker = SuccessChecker(sandbox)
result = checker.check(criterion, turn_records=turn_records)
assert result.score == 0.0
assert result.error is not None
assert "Invalid regex" in result.error
def test_no_filters(self):
"""Test that no tool_name/pattern matches all commands."""
sandbox = MockSandbox()
turn_records = [
_make_turn(
[
_make_command(tool_name="Read", parameters={"file_path": "a.py"}, tool_id="t1"),
_make_command(tool_name="Bash", parameters={"command": "ls"}, tool_id="t2"),
_make_command(tool_name="Write", parameters={"file_path": "b.py"}, tool_id="t3"),
]
)
]
criterion = CommandExecutedCriterion(
description="Agent executed any commands",
min_count=3,
)
checker = SuccessChecker(sandbox)
result = checker.check(criterion, turn_records=turn_records)
assert result.score == 1.0
def test_exclude_pattern_filters_help(self):
"""exclude_pattern should skip --help invocations."""
sandbox = MockSandbox()
turn_records = [
_make_turn(
[
_make_command(
tool_name="Bash",
parameters={"command": "uip maestro flow process get --help 2>&1"},
tool_id="t1",
),
_make_command(
tool_name="Bash",
parameters={"command": "uip maestro flow process get --process-key pk1 --feed-id fid1"},
tool_id="t2",
),
]
)
]
criterion = CommandExecutedCriterion(
description="Agent ran uip maestro flow process get (not just --help)",
tool_name="Bash",
command_pattern=r"uip\s+maestro\s+flow\s+process\s+get",
exclude_pattern=r"--help",
min_count=1,
)
checker = SuccessChecker(sandbox)
result = checker.check(criterion, turn_records=turn_records)
assert result.score == 1.0
assert "1/1" in result.details
def test_exclude_pattern_all_excluded(self):
"""If all matches are excluded, score should be 0."""
sandbox = MockSandbox()
turn_records = [
_make_turn(
[
_make_command(
tool_name="Bash",
parameters={"command": "uip maestro flow process get --help"},
tool_id="t1",
),
_make_command(
tool_name="Bash",
parameters={"command": "uip maestro flow process get --help 2>&1"},
tool_id="t2",
),
]
)
]
criterion = CommandExecutedCriterion(
description="Agent ran uip maestro flow process get (not just --help)",
tool_name="Bash",
command_pattern=r"uip\s+maestro\s+flow\s+process\s+get",
exclude_pattern=r"--help",
min_count=1,
)
checker = SuccessChecker(sandbox)
result = checker.check(criterion, turn_records=turn_records)
assert result.score == 0.0
def test_exclude_pattern_no_positive_matches(self):
"""exclude_pattern with no positive matches should still yield 0."""
sandbox = MockSandbox()
turn_records = [
_make_turn(
[
_make_command(tool_name="Bash", parameters={"command": "ls -la"}, tool_id="t1"),
]
)
]
criterion = CommandExecutedCriterion(
description="Agent used curl",
tool_name="Bash",
command_pattern=r"curl",
exclude_pattern=r"--help",
min_count=1,
)
checker = SuccessChecker(sandbox)
result = checker.check(criterion, turn_records=turn_records)
assert result.score == 0.0
def test_exclude_pattern_invalid_regex(self):
"""Invalid exclude_pattern regex should return error."""
sandbox = MockSandbox()
turn_records = [
_make_turn(
[
_make_command(tool_name="Bash", parameters={"command": "uip maestro flow process get pk1"}),
]
)
]
criterion = CommandExecutedCriterion(
description="Bad exclude regex",
command_pattern=r"uip",
exclude_pattern=r"[invalid",
min_count=1,
)
checker = SuccessChecker(sandbox)
result = checker.check(criterion, turn_records=turn_records)
assert result.score == 0.0
assert result.error is not None
assert "Invalid regex" in result.error
def test_exclude_pattern_non_bash_tool(self):
"""Test exclude_pattern on non-Bash tool via JSON-serialized parameters."""
sandbox = MockSandbox()
turn_records = [
_make_turn(
[
_make_command(
tool_name="Write",
parameters={"file_path": "output.json", "content": '{"key": "value"}'},
tool_id="t1",
),
_make_command(
tool_name="Write",
parameters={"file_path": "ignore.json", "content": '{"key": "value"}'},
tool_id="t2",
),
]
)
]
criterion = CommandExecutedCriterion(
description="Agent wrote a json file but not ignore.json",
tool_name="Write",
command_pattern=r"\.json",
exclude_pattern=r"ignore\.json",
min_count=1,
)
checker = SuccessChecker(sandbox)
result = checker.check(criterion, turn_records=turn_records)
assert result.score == 1.0
def test_non_bash_tool(self):
"""Test matching non-Bash tool via JSON-serialized parameters."""
sandbox = MockSandbox()
turn_records = [
_make_turn(
[
_make_command(
tool_name="Write",
parameters={"file_path": "output.json", "content": '{"key": "value"}'},
),
]
)
]
criterion = CommandExecutedCriterion(
description="Agent wrote output.json",
tool_name="Write",
command_pattern=r"output\.json",
min_count=1,
)
checker = SuccessChecker(sandbox)
result = checker.check(criterion, turn_records=turn_records)
assert result.score == 1.0
def test_non_str_command_does_not_crash_criterion(self):
"""A non-``str`` ``command`` (Codex argv array) must not zero the criterion.
Codex sub-agent rollout recovery can carry ``command`` as an argv *list*
(codex_agent.py), which reaches ``CommandTelemetry.parameters`` verbatim.
Before the ``isinstance`` narrow, the list fell through to
``shlex.split(list)`` -> ``AttributeError: 'list' object has no attribute
'read'``, which aborted ``_matching_commands`` for the entire trajectory
and scored a pattern-less, otherwise-passing criterion 0.0.
"""
sandbox = MockSandbox()
turn_records = [
_make_turn(
[
_make_command(tool_name="Bash", parameters={"command": ["bash", "-lc", "ls"]}, tool_id="t1"),
_make_command(tool_name="Bash", parameters={"command": "echo hi"}, tool_id="t2"),
]
)
]
# Pattern-less: both Bash commands count; the argv-list one must not crash.
criterion = CommandExecutedCriterion(description="ran bash", tool_name="Bash", min_count=1)
result = SuccessChecker(sandbox).check(criterion, turn_records=turn_records)
assert result.error is None
assert result.score == 1.0
assert "2/1" in result.details
def test_non_str_command_still_matches_sibling_by_pattern(self):
"""One argv-list ``command`` must not poison a pattern match on its sibling."""
sandbox = MockSandbox()
turn_records = [
_make_turn(
[
_make_command(tool_name="Bash", parameters={"command": ["bash", "-lc", "ls"]}, tool_id="t1"),
_make_command(tool_name="Bash", parameters={"command": "uip run foo"}, tool_id="t2"),
]
)
]
criterion = CommandExecutedCriterion(
description="ran uip", tool_name="Bash", command_pattern=r"uip\s+run", min_count=1
)
result = SuccessChecker(sandbox).check(criterion, turn_records=turn_records)
assert result.error is None
assert result.score == 1.0
def test_crashed_turn_commands_are_counted(self):
"""Commands from crashed partial turns count toward min_count.
Scenario: a crash preserves 3 commands; the retry adds 2 more. The
retry continues from where the crash left off (session-resume + same
sandbox), so all 5 calls are real executed work and all 5 should
satisfy a min_count=4 requirement.
"""
sandbox = MockSandbox()
turn_records = [
_make_turn(
[
_make_command(
tool_name="Bash",
parameters={"command": "curl http://a"},
tool_id="t-crash-1",
),
_make_command(
tool_name="Bash",
parameters={"command": "curl http://b"},
tool_id="t-crash-2",
),
_make_command(
tool_name="Bash",
parameters={"command": "curl http://c"},
tool_id="t-crash-3",
),
],
crashed=True,
),
_make_turn(
[
_make_command(
tool_name="Bash",
parameters={"command": "curl http://d"},
tool_id="t-clean-1",
),
_make_command(
tool_name="Bash",
parameters={"command": "curl http://e"},
tool_id="t-clean-2",
),
],
),
]
criterion = CommandExecutedCriterion(
description="Agent used curl at least 4 times",
tool_name="Bash",
command_pattern=r"curl",
min_count=4,
)
checker = SuccessChecker(sandbox)
result = checker.check(criterion, turn_records=turn_records)
# All 5 calls (3 from partial + 2 from retry) count → 5/4 capped to 1.0.
assert result.score == 1.0
assert "5/4" in result.details
def test_all_turns_crashed_commands_still_counted(self):
"""Commands from an all-crashed run are real work and must be counted."""
sandbox = MockSandbox()
turn_records = [
_make_turn(
[
_make_command(
tool_name="Bash",
parameters={"command": "curl http://a"},
tool_id="t-crash-1",
),
],
crashed=True,
),
]
criterion = CommandExecutedCriterion(
description="Agent used curl",
command_pattern=r"curl",
min_count=1,
)
checker = SuccessChecker(sandbox)
result = checker.check(criterion, turn_records=turn_records)
assert result.score == 1.0
assert "1/1" in result.details
# ------------------------------------------------------------------
# max_count + min_count=0 negative-assertion patterns.
# Skills task YAMLs (uipath-skills) use these to express "must NOT call
# the retired command". Before max_count landed, those YAMLs failed
# pydantic validation in the `Validate Skills Task YAMLs` CI gate.
# ------------------------------------------------------------------
def test_negative_assertion_passes_when_no_match(self):
"""min_count=0, max_count=0 ⇒ pass iff the pattern never matched."""
sandbox = MockSandbox()
turn_records = [
_make_turn(
[
_make_command(
tool_name="Bash",
parameters={"command": "uip admin users list --search alice"},
tool_id="t-ok-1",
),
]
),
]
criterion = CommandExecutedCriterion(
description="Agent did NOT use the retired `uip or users list` path",
tool_name="Bash",
command_pattern=r"uip\s+or\s+users\s+list",
min_count=0,
max_count=0,
)
checker = SuccessChecker(sandbox)
result = checker.check(criterion, turn_records=turn_records)
assert result.score == 1.0
assert "allowed range 0..0" in result.details
def test_negative_assertion_fails_when_pattern_matched(self):
"""min_count=0, max_count=0 ⇒ a single retired-call match fails the gate."""
sandbox = MockSandbox()
turn_records = [
_make_turn(
[
_make_command(
tool_name="Bash",
parameters={"command": "uip or users list"},
tool_id="t-retired-1",
),
]
),
]
criterion = CommandExecutedCriterion(
description="Agent did NOT use the retired `uip or users list` path",
tool_name="Bash",
command_pattern=r"uip\s+or\s+users\s+list",
min_count=0,
max_count=0,
)
checker = SuccessChecker(sandbox)
result = checker.check(criterion, turn_records=turn_records)
assert result.score == 0.0
assert "allowed range 0..0" in result.details
def test_bounded_range_pass_inside(self):
"""min_count=2, max_count=4 ⇒ 3 matches sits inside the range."""
sandbox = MockSandbox()
commands = [
_make_command(
tool_name="Bash",
parameters={"command": "curl https://api/x"},
tool_id=f"t-{i}",
)
for i in range(3)
]
turn_records = [_make_turn(commands)]
criterion = CommandExecutedCriterion(
description="Agent retried within bounds",
tool_name="Bash",
command_pattern=r"curl",
min_count=2,
max_count=4,
)
checker = SuccessChecker(sandbox)
result = checker.check(criterion, turn_records=turn_records)
assert result.score == 1.0
assert "allowed range 2..4" in result.details
def test_bounded_range_fails_when_over_cap(self):
"""min_count=2, max_count=4 ⇒ 5 matches busts the cap (score 0.0)."""
sandbox = MockSandbox()
commands = [
_make_command(
tool_name="Bash",
parameters={"command": "curl https://api/x"},
tool_id=f"t-{i}",
)
for i in range(5)
]
turn_records = [_make_turn(commands)]
criterion = CommandExecutedCriterion(
description="Agent must not retry more than 4 times",
tool_name="Bash",
command_pattern=r"curl",
min_count=2,
max_count=4,
)
checker = SuccessChecker(sandbox)
result = checker.check(criterion, turn_records=turn_records)
assert result.score == 0.0
def test_min_count_zero_no_max_is_trivially_satisfied(self):
"""min_count=0 with no max_count ⇒ score 1.0 even when no commands match."""
sandbox = MockSandbox()
turn_records = [_make_turn([])]
criterion = CommandExecutedCriterion(
description="Optional command (passes vacuously)",
tool_name="Bash",
command_pattern=r"never-matches",
min_count=0,
)
checker = SuccessChecker(sandbox)
result = checker.check(criterion, turn_records=turn_records)
# No turn-records-empty short-circuit: turns exist but commands is [].
# Score should be 1.0 by the min_count==0 rule, not 0/0 ZeroDivisionError.
assert result.score == 1.0
def test_invalid_range_rejected_at_model_level(self):
"""max_count < min_count must be rejected by the Pydantic validator."""
import pytest as _pytest
from pydantic import ValidationError
with _pytest.raises(ValidationError, match=r"max_count.*must be >= min_count"):
CommandExecutedCriterion(
description="impossible range",
command_pattern="x",
min_count=5,
max_count=2,
)
class TestNormalizeShell:
"""Unit tests for the shell-normalization helper."""
def test_unwraps_bash_lc_and_resolves_single_quotes(self):
raw = (
'/bin/bash -lc "uip is resources run list uipath-salesforce-slack '
"'curated_channels?types=public_channel,private_channel' --output json\""
)
assert _normalize_shell(raw) == (
"uip is resources run list uipath-salesforce-slack "
"curated_channels?types=public_channel,private_channel --output json"
)
def test_unwraps_escaped_double_quotes(self):
raw = '/bin/bash -lc "uip is resources run list \\"slack\\" \\"curated_channels\\""'
assert _normalize_shell(raw) == "uip is resources run list slack curated_channels"
def test_bare_command_is_just_requoted(self):
assert _normalize_shell("uip is resources run list slack 'curated_channels'") == (
"uip is resources run list slack curated_channels"
)
def test_shell_operators_survive_as_tokens(self):
raw = "uip maestro flow validate X.flow --output json && uip maestro flow format X.flow"
assert _normalize_shell(raw) == raw # already unquoted; operators kept verbatim
def test_unbalanced_quotes_return_none(self):
assert _normalize_shell("echo 'unterminated") is None
def test_argv_joined_payload_is_not_collapsed_to_first_word(self):
"""Codex rollout recovery joins argv WITHOUT re-quoting (codex_agent.py).
The wrapper unwrap must keep every token after ``-lc``, not just the
first — otherwise ``bash -lc uip is resources ...`` collapses to ``uip``,
making the fix a silent no-op on the sub-agent path.
"""
raw = "bash -lc uip is resources run list slack curated_channels --output json"
assert _normalize_shell(raw) == "uip is resources run list slack curated_channels --output json"
def test_argv_joined_short_command(self):
assert _normalize_shell("bash -c echo hi there") == "echo hi there"
def test_every_wrapper_form_is_unwrapped(self):
"""One case per shell/flag shape the agents emit — the allowlist can't rot.
The predicate replaced an enumerated allowlist that omitted ``zsh``
(Codex's shell on macOS, codex_agent.py) and ``-ic`` while listing the
exotic ``-lic``; on those hosts the normalization silently reverted to
the pre-fix false-negative behaviour. Each entry must strip the wrapper.
"""
cases = {
# zsh — Codex's default login shell on macOS
'/bin/zsh -lc "uip is resources run list slack curated_channels"': (
"uip is resources run list slack curated_channels"
),
'zsh -lc "echo hi"': "echo hi",
'sh -c "echo hi"': "echo hi",
'dash -c "echo hi"': "echo hi",
'ksh -c "echo hi"': "echo hi",
'bash -ic "echo hi"': "echo hi", # interactive + command
'/usr/bin/bash -lic "echo hi"': "echo hi", # login + interactive + command
"bash -l -c 'echo hi'": "echo hi", # split login/command flags
}
for raw, expected in cases.items():
assert _normalize_shell(raw) == expected, raw
def test_non_shell_arg0_is_not_unwrapped(self):
"""A non-shell program (basename not ending in ``sh``) is only re-quoted.
``git -c <config>`` is the motivating case: ``-c`` is a real git flag, but
because ``git`` is not a shell the payload must NOT be unwrapped.
"""
assert _normalize_shell("git -c user.name=x status") == "git -c user.name=x status"
assert _normalize_shell("uip is resources run list slack 'curated_channels'") == (
"uip is resources run list slack curated_channels"
)
def test_empty_and_whitespace_input_return_none(self):
"""Empty / whitespace-only input has no tokens -> None (benign, not an error)."""
assert _normalize_shell("") is None
assert _normalize_shell(" ") is None
def test_inner_unbalanced_quotes_return_none(self):
"""A wrapper whose script token can't be re-split falls back to None."""
# Outer double quotes balance, so the script token is `echo 'unterminated`;
# re-splitting that raises ValueError on the stray single quote.
assert _normalize_shell('bash -lc "echo \'unterminated"') is None
def test_non_wrapper_positional_returns_verbatim(self):
"""A shell with a positional before any -c is a script invocation, not `-c`.
`bash script.sh -c foo` runs the file `script.sh`; the later `-c` is an
argument to the script, not a command flag, so nothing is unwrapped.
"""
assert _normalize_shell("bash script.sh -c foo") == "bash script.sh -c foo"
def test_shell_with_flags_but_no_command_flag_is_verbatim(self):
"""A shell invoked with only non-``-c`` flags (no command) unwraps nothing.
The wrapper scan exhausts without finding a command flag or a positional,
so the tokens are returned as-is.
"""
assert _normalize_shell("bash --norc -i") == "bash --norc -i"
def test_is_memoized(self):
"""The hot early-stop path re-scans the trajectory; normalize once per command.
Counting via ``cache_info`` (not wall-clock) so the guard can't flake.
"""
_normalize_shell.cache_clear()
raw = "bash -lc 'echo hello world'"
first = _normalize_shell(raw)
second = _normalize_shell(raw)
assert first == second == "echo hello world"
assert _normalize_shell.cache_info().hits >= 1 # second call served from cache
class TestShellQuotingNormalization:
"""Patterns match regardless of how the agent quoted the command.
Regression for ``skill-flow-paginated-reference-lookup``: the agent
paginated ``uip is resources run list <slack> 'curated_channels?...'``
correctly (a sibling ``nextPage=`` criterion matched the same calls), but the
gating pagination criterion's pattern allowed only a bare or ``\\"``-escaped
token — the agent single-quoted the resource arg — so it scored 0.0 (false
negative). Normalizing the command before matching fixes the whole class
without touching any task YAML.
"""
# The exact recorded shape: `bash -lc "..."` wrapper, resource arg in SINGLE
# quotes. Second call adds a nextPage token (still single-quoted).
_PAGE1 = (
'/bin/bash -lc "uip is resources run list uipath-salesforce-slack '
"'curated_channels?types=public_channel,private_channel' --connection-id abc --output json\""
)
_PAGE2 = (
'/bin/bash -lc "uip is resources run list uipath-salesforce-slack '
"'curated_channels?types=public_channel,private_channel' "
"--query 'nextPage=eyJwYWdlIjoyfQ' --output json\""
)
# The ORIGINAL, unchanged pattern from the task YAML: allows an optional
# backslash + optional DOUBLE quote, but no single quote.
_YAML_PATTERN = r'uip\s+is\s+resources\s+run\s+list\s+\\?"?uipath-salesforce-slack\\?"?\s+\\?"?curated_channels'
def test_single_quoted_calls_now_counted_with_original_pattern(self):
"""The unchanged YAML pattern now counts both single-quoted calls."""
sandbox = MockSandbox()
turn_records = [
_make_turn(
[
_make_command(tool_name="Bash", parameters={"command": self._PAGE1}, tool_id="t1"),
_make_command(tool_name="Bash", parameters={"command": self._PAGE2}, tool_id="t2"),
]
)
]
criterion = CommandExecutedCriterion(
description="paginated curated_channels list ran >1x",
tool_name="Bash",
command_pattern=self._YAML_PATTERN,
min_count=2,
)
result = SuccessChecker(sandbox).check(criterion, turn_records=turn_records)
assert result.score == 1.0
assert "2/2" in result.details
def test_escaped_double_quote_form_still_matches(self):
"""Backward compat: the escaping style the pattern anticipated still hits."""
sandbox = MockSandbox()
raw = (
'/bin/bash -lc "uip is resources run list \\"uipath-salesforce-slack\\" '
'\\"curated_channels?types=x\\" --output json"'
)
turn_records = [_make_turn([_make_command(tool_name="Bash", parameters={"command": raw})])]
criterion = CommandExecutedCriterion(
description="curated_channels list ran",
tool_name="Bash",
command_pattern=self._YAML_PATTERN,
min_count=1,
)
result = SuccessChecker(sandbox).check(criterion, turn_records=turn_records)
assert result.score == 1.0
def test_shell_operator_pattern_still_matches(self):
"""`&&`/`|` patterns keep working — operators survive normalization."""
sandbox = MockSandbox()
cmd = "/bin/bash -lc 'uip maestro flow validate X.flow --output json && uip maestro flow format X.flow'"
turn_records = [_make_turn([_make_command(tool_name="Bash", parameters={"command": cmd})])]
criterion = CommandExecutedCriterion(
description="validate then format",
tool_name="Bash",
command_pattern=r"uip\s+maestro\s+flow\s+validate.*&&.*uip\s+maestro\s+flow\s+format",
min_count=1,
)
result = SuccessChecker(sandbox).check(criterion, turn_records=turn_records)
assert result.score == 1.0
def test_unbalanced_quotes_fall_back_to_raw_without_crashing(self):
"""A command shlex can't parse still matches against its raw text."""
sandbox = MockSandbox()
turn_records = [_make_turn([_make_command(tool_name="Bash", parameters={"command": "echo 'unterminated"})])]
criterion = CommandExecutedCriterion(