-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcontext_test.go
More file actions
2734 lines (2411 loc) · 75.8 KB
/
context_test.go
File metadata and controls
2734 lines (2411 loc) · 75.8 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
package codingcontext
import (
"context"
"fmt"
"log/slog"
"os"
"path/filepath"
"strings"
"testing"
"github.com/kitproj/coding-context-cli/pkg/codingcontext/selectors"
"github.com/kitproj/coding-context-cli/pkg/codingcontext/taskparser"
)
const cursorSkillName = "cursor-skill"
// Test helper functions for creating fixtures
// buildMarkdownContent wraps content with a YAML frontmatter block when
// frontmatter is non-empty. Returns content unchanged when frontmatter is empty.
func buildMarkdownContent(frontmatter, content string) string {
if frontmatter == "" {
return content
}
return fmt.Sprintf("---\n%s\n---\n%s", frontmatter, content)
}
// writeMarkdownFile writes a markdown file (with optional frontmatter) to path,
// creating any missing parent directories.
func writeMarkdownFile(t *testing.T, path, frontmatter, content string) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(path), 0o750); err != nil {
t.Fatalf("failed to create directory for %s: %v", path, err)
}
if err := os.WriteFile(path, []byte(buildMarkdownContent(frontmatter, content)), 0o600); err != nil {
t.Fatalf("failed to write file %s: %v", path, err)
}
}
// createTask creates a task file in the .agents/tasks directory.
func createTask(t *testing.T, dir, name, frontmatter, content string) {
t.Helper()
writeMarkdownFile(t, filepath.Join(dir, ".agents", "tasks", name+".md"), frontmatter, content)
}
// createRule creates a rule file at relPath within dir.
func createRule(t *testing.T, dir, relPath, frontmatter, content string) {
t.Helper()
writeMarkdownFile(t, filepath.Join(dir, relPath), frontmatter, content)
}
// createCommand creates a command file in the .agents/commands directory.
func createCommand(t *testing.T, dir, name, frontmatter, content string) {
t.Helper()
writeMarkdownFile(t, filepath.Join(dir, ".agents", "commands", name+".md"), frontmatter, content)
}
// createBootstrapScript creates a bootstrap script for a rule file.
func createBootstrapScript(t *testing.T, dir, rulePath, scriptContent string) {
t.Helper()
fullRulePath := filepath.Join(dir, rulePath)
baseNameWithoutExt := strings.TrimSuffix(fullRulePath, filepath.Ext(fullRulePath))
bootstrapPath := baseNameWithoutExt + "-bootstrap"
// Bootstrap scripts are executed directly (support shebangs); require 0755
// #nosec G306 -- bootstrap scripts require 0755 for direct execution
if err := os.WriteFile(bootstrapPath, []byte(scriptContent), 0o755); err != nil {
t.Fatalf("failed to create bootstrap script: %v", err)
}
}
func createSkill(t *testing.T, dir, subdir, content string) {
t.Helper()
skillDir := filepath.Join(dir, subdir)
if err := os.MkdirAll(skillDir, 0o750); err != nil {
t.Fatalf("failed to create skill directory: %v", err)
}
skillPath := filepath.Join(skillDir, "SKILL.md")
if err := os.WriteFile(skillPath, []byte(content), 0o600); err != nil {
t.Fatalf("failed to create skill file: %v", err)
}
}
// TestNew tests the constructor with various options.
func TestNew(t *testing.T) {
t.Parallel()
tests := []struct {
name string
opts []Option
check func(t *testing.T, c *Context)
}{
{name: "default context", opts: nil, check: checkNewDefault},
{
name: "with params",
opts: []Option{WithParams(taskparser.Params{"key1": []string{"value1"}, "key2": []string{"value2"}})},
check: checkNewWithParams,
},
{
name: "with selectors",
opts: []Option{WithSelectors(selectors.Selectors{"env": {"dev": true, "test": true}})},
check: checkNewWithSelectors,
},
{
name: "with manifest URL",
opts: []Option{WithManifestURL("https://example.com/manifest.txt")},
check: checkNewWithManifestURL,
},
{
name: "with search paths",
opts: []Option{WithSearchPaths("/path/one", "/path/two")},
check: checkNewWithSearchPaths,
},
{
name: "with custom logger",
opts: []Option{WithLogger(slog.New(slog.NewTextHandler(os.Stderr, nil)))},
check: checkNewWithLogger,
},
{name: "with resume mode", opts: []Option{WithResume(true)}, check: checkNewWithResume},
{name: "with bootstrap disabled", opts: []Option{WithBootstrap(false)}, check: checkNewBootstrapDisabled},
{
name: "resume and bootstrap are independent",
opts: []Option{WithResume(true), WithBootstrap(false)},
check: checkNewResumeAndBootstrapIndependent,
},
{name: "with agent", opts: []Option{WithAgent(AgentCursor)}, check: checkNewWithAgent},
{
name: "multiple options combined",
opts: []Option{
WithParams(taskparser.Params{"env": []string{"production"}}),
WithSelectors(selectors.Selectors{"lang": {"go": true}}),
WithSearchPaths("/custom/path"),
WithResume(false),
WithAgent(AgentCopilot),
},
check: checkNewMultipleCombined,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
c := New(tt.opts...)
if tt.check != nil {
tt.check(t, c)
}
})
}
}
func checkRunBasicSimpleTask(t *testing.T, result *Result) {
t.Helper()
if !strings.Contains(result.Task.Content, "This is a simple task.") {
t.Errorf("expected task content 'This is a simple task.', got %q", result.Task.Content)
}
if result.Tokens <= 0 {
t.Error("expected positive token count")
}
}
func checkRunBasicFrontmatter(t *testing.T, result *Result) {
t.Helper()
if !strings.Contains(result.Task.Content, "Task content here.") {
t.Errorf("expected task content, got %q", result.Task.Content)
}
if result.Task.FrontMatter.Content["priority"] != "high" {
t.Error("expected priority=high in frontmatter")
}
}
func checkRunBasicParamSubstitution(t *testing.T, result *Result) {
t.Helper()
if !strings.Contains(result.Task.Content, "Environment: production") {
t.Errorf("expected 'Environment: production' in content, got %q", result.Task.Content)
}
if !strings.Contains(result.Task.Content, "Feature: auth") {
t.Errorf("expected 'Feature: auth' in content, got %q", result.Task.Content)
}
}
func checkRunBasicUnresolvedParam(t *testing.T, result *Result) {
t.Helper()
if !strings.Contains(result.Task.Content, "${missing_param}") {
t.Errorf("expected unresolved parameter to remain as ${missing_param}, got %q", result.Task.Content)
}
}
func checkRunBasicSelectors(t *testing.T, result *Result) {
t.Helper()
if !strings.Contains(result.Task.Content, "Task with selectors") {
t.Errorf("unexpected content: %q", result.Task.Content)
}
}
func checkRunBasicMultipleParams(t *testing.T, result *Result) {
t.Helper()
expected := "User: alice, Email: alice@example.com, Role: admin"
if !strings.Contains(result.Task.Content, expected) {
t.Errorf("expected %q in content, got %q", expected, result.Task.Content)
}
}
func checkNewDefault(t *testing.T, c *Context) {
t.Helper()
if c.params == nil {
t.Error("expected params to be initialized")
}
if c.includes == nil {
t.Error("expected includes to be initialized")
}
if c.logger == nil {
t.Error("expected logger to be initialized")
}
if c.cmdRunner == nil {
t.Error("expected cmdRunner to be initialized")
}
}
func checkNewWithParams(t *testing.T, c *Context) {
t.Helper()
if c.params.Value("key1") != "value1" {
t.Errorf("expected params[key1]=value1, got %v", c.params.Value("key1"))
}
if c.params.Value("key2") != "value2" {
t.Errorf("expected params[key2]=value2, got %v", c.params.Value("key2"))
}
}
func checkNewWithSelectors(t *testing.T, c *Context) {
t.Helper()
if !c.includes.GetValue("env", "dev") {
t.Error("expected env=dev selector")
}
if !c.includes.GetValue("env", "test") {
t.Error("expected env=test selector")
}
}
func checkNewWithManifestURL(t *testing.T, c *Context) {
t.Helper()
if c.manifestURL != "https://example.com/manifest.txt" {
t.Errorf("expected manifestURL to be set, got %v", c.manifestURL)
}
}
func checkNewWithSearchPaths(t *testing.T, c *Context) {
t.Helper()
if len(c.searchPaths) != 2 {
t.Errorf("expected 2 search paths, got %d", len(c.searchPaths))
}
if c.searchPaths[0] != "/path/one" {
t.Errorf("expected first path to be /path/one, got %v", c.searchPaths[0])
}
if c.searchPaths[1] != "/path/two" {
t.Errorf("expected second path to be /path/two, got %v", c.searchPaths[1])
}
}
func checkNewWithLogger(t *testing.T, c *Context) {
t.Helper()
if c.logger == nil {
t.Error("expected logger to be set")
}
}
func checkNewWithResume(t *testing.T, c *Context) {
t.Helper()
if !c.resume {
t.Error("expected resume to be true")
}
if !c.doBootstrap {
t.Error("expected doBootstrap to be true by default")
}
}
func checkNewBootstrapDisabled(t *testing.T, c *Context) {
t.Helper()
if c.doBootstrap {
t.Error("expected doBootstrap to be false")
}
}
func checkNewResumeAndBootstrapIndependent(t *testing.T, c *Context) {
t.Helper()
if !c.resume {
t.Error("expected resume to be true")
}
if c.doBootstrap {
t.Error("expected doBootstrap to be false")
}
}
func checkNewWithAgent(t *testing.T, c *Context) {
t.Helper()
if c.agent != AgentCursor {
t.Errorf("expected agent to be cursor, got %v", c.agent)
}
}
func checkNewMultipleCombined(t *testing.T, c *Context) {
t.Helper()
if c.params.Value("env") != "production" {
t.Error("params not set correctly")
}
if !c.includes.GetValue("lang", "go") {
t.Error("selectors not set correctly")
}
if len(c.searchPaths) != 1 || c.searchPaths[0] != "/custom/path" {
t.Error("search paths not set correctly")
}
if c.resume != false {
t.Error("resume not set correctly")
}
if c.agent != AgentCopilot {
t.Error("agent not set correctly")
}
}
// TestContext_Run_Basic tests basic task execution scenarios.
//
//nolint:funlen
func TestContext_Run_Basic(t *testing.T) {
t.Parallel()
tests := []struct {
name string
setup func(t *testing.T, dir string)
opts []Option
taskName string
wantErr bool
errContains string
check func(t *testing.T, result *Result)
}{
{
name: "simple task with plain text",
setup: func(t *testing.T, dir string) {
t.Helper()
createTask(t, dir, "simple", "", "This is a simple task.")
},
taskName: "simple",
wantErr: false,
check: checkRunBasicSimpleTask,
},
{
name: "task with frontmatter",
setup: func(t *testing.T, dir string) {
t.Helper()
createTask(t, dir, "with-frontmatter", "priority: high\nenv: dev", "Task content here.")
},
taskName: "with-frontmatter",
wantErr: false,
check: checkRunBasicFrontmatter,
},
{
name: "task with parameter substitution",
setup: func(t *testing.T, dir string) {
t.Helper()
createTask(t, dir, "params-task", "", "Environment: ${env}\nFeature: ${feature}")
},
opts: []Option{
WithParams(taskparser.Params{"env": []string{"production"}, "feature": []string{"auth"}}),
},
taskName: "params-task",
wantErr: false,
check: checkRunBasicParamSubstitution,
},
{
name: "task with unresolved parameter",
setup: func(t *testing.T, dir string) {
t.Helper()
createTask(t, dir, "unresolved", "", "Missing: ${missing_param}")
},
taskName: "unresolved",
wantErr: false,
check: checkRunBasicUnresolvedParam,
},
{
name: "task not found returns error",
setup: func(t *testing.T, _ string) { t.Helper() },
taskName: "nonexistent",
wantErr: true,
errContains: "task not found",
},
{
name: "task with selectors sets includes",
setup: func(t *testing.T, dir string) {
t.Helper()
createTask(t, dir, "selector-task", "selectors:\n env: production\n lang: go", "Task with selectors")
},
taskName: "selector-task",
wantErr: false,
check: checkRunBasicSelectors,
},
{
name: "multiple params in same content",
setup: func(t *testing.T, dir string) {
t.Helper()
createTask(t, dir, "multi-params", "", "User: ${user}, Email: ${email}, Role: ${role}")
},
opts: []Option{
WithParams(taskparser.Params{
"user": []string{"alice"}, "email": []string{"alice@example.com"}, "role": []string{"admin"},
}),
},
taskName: "multi-params",
wantErr: false,
check: checkRunBasicMultipleParams,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
tmpDir := t.TempDir()
tt.setup(t, tmpDir)
opts := append([]Option{WithSearchPaths(tmpDir)}, tt.opts...)
c := New(opts...)
result, err := c.Run(context.Background(), tt.taskName)
if (err != nil) != tt.wantErr {
t.Errorf("Run() error = %v, wantErr %v", err, tt.wantErr)
return
}
if tt.wantErr && tt.errContains != "" {
if !strings.Contains(err.Error(), tt.errContains) {
t.Errorf("expected error to contain %q, got %v", tt.errContains, err)
}
return
}
if !tt.wantErr && tt.check != nil {
tt.check(t, result)
}
})
}
}
func checkRulesCount(n int) func(t *testing.T, result *Result) {
return func(t *testing.T, result *Result) {
t.Helper()
if len(result.Rules) != n {
t.Errorf("expected %d rules, got %d", n, len(result.Rules))
}
}
}
func checkRulesFilteredBySelectors(t *testing.T, result *Result) {
t.Helper()
if len(result.Rules) != 2 {
t.Errorf("expected 2 rules, got %d", len(result.Rules))
}
foundProd := false
for _, rule := range result.Rules {
if strings.Contains(rule.Content, "Production rule") {
foundProd = true
break
}
}
if !foundProd {
t.Error("expected to find production rule")
}
}
func checkRulesParamSubstitution(t *testing.T, result *Result) {
t.Helper()
if len(result.Rules) != 1 {
t.Fatalf("expected 1 rule, got %d", len(result.Rules))
}
if !strings.Contains(result.Rules[0].Content, "Project: myapp") {
t.Errorf("expected parameter substitution in rule, got %q", result.Rules[0].Content)
}
}
func checkRulesTokenCounting(t *testing.T, result *Result) {
t.Helper()
if result.Tokens <= 0 {
t.Error("expected positive total token count")
}
totalRuleTokens := 0
for _, rule := range result.Rules {
if rule.Tokens <= 0 {
t.Error("expected positive token count for each rule")
}
totalRuleTokens += rule.Tokens
}
if result.Task.Tokens <= 0 {
t.Error("expected positive token count for task")
}
expectedTotal := totalRuleTokens + result.Task.Tokens
if result.Tokens != expectedTotal {
t.Errorf("expected total tokens %d, got %d", expectedTotal, result.Tokens)
}
}
// TestContext_Run_Rules tests rule discovery and filtering.
//
//nolint:funlen,maintidx
func TestContext_Run_Rules(t *testing.T) {
t.Parallel()
tests := []struct {
name string
setup func(t *testing.T, dir string)
opts []Option
taskName string
wantErr bool
check func(t *testing.T, result *Result)
}{
{
name: "discover rules in standard paths",
setup: func(t *testing.T, dir string) {
t.Helper()
createTask(t, dir, "task1", "", "Task content")
createRule(t, dir, ".agents/rules/rule1.md", "", "Rule 1 content")
createRule(t, dir, ".cursor/rules/rule2.md", "", "Rule 2 content")
},
taskName: "task1",
wantErr: false,
check: checkRulesCount(2),
},
{
name: "filter rules by selectors from task frontmatter",
setup: func(t *testing.T, dir string) {
t.Helper()
createTask(t, dir, "filtered-task", "selectors:\n env: production", "Task with selectors")
createRule(t, dir, ".agents/rules/prod-rule.md", "env: production", "Production rule")
createRule(t, dir, ".agents/rules/dev-rule.md", "env: development", "Development rule")
createRule(t, dir, ".agents/rules/no-env.md", "", "No env specified")
},
taskName: "filtered-task",
wantErr: false,
check: checkRulesFilteredBySelectors,
},
{
name: "rules with parameter substitution",
setup: func(t *testing.T, dir string) {
t.Helper()
createTask(t, dir, "param-task", "", "Task")
createRule(t, dir, ".agents/rules/param-rule.md", "", "Project: ${project}")
},
opts: []Option{
WithParams(taskparser.Params{"project": []string{"myapp"}}),
},
taskName: "param-task",
wantErr: false,
check: checkRulesParamSubstitution,
},
{
name: "bootstrap disabled skips rule discovery",
setup: func(t *testing.T, dir string) {
t.Helper()
createTask(t, dir, "bootstrap-task", "", "Task content")
createRule(t, dir, ".agents/rules/rule1.md", "", "Rule content")
},
opts: []Option{
WithBootstrap(false),
},
taskName: "bootstrap-task",
wantErr: false,
check: checkRulesCount(0),
},
{
name: "resume mode does not skip rule discovery",
setup: func(t *testing.T, dir string) {
t.Helper()
createTask(t, dir, "resume-task", "", "Task content")
createRule(t, dir, ".agents/rules/rule1.md", "", "Rule content")
},
opts: []Option{
WithResume(true),
},
taskName: "resume-task",
wantErr: false,
check: checkRulesCount(1),
},
{
name: "bootstrap script executed for rules",
setup: func(t *testing.T, dir string) {
t.Helper()
createTask(t, dir, "bootstrap-task", "", "Task")
createRule(t, dir, ".agents/rules/rule-with-bootstrap.md", "", "Rule content")
createBootstrapScript(t, dir, ".agents/rules/rule-with-bootstrap.md", "#!/bin/sh\necho 'bootstrapped'")
},
taskName: "bootstrap-task",
wantErr: false,
check: checkRulesCount(1),
},
{
name: "bootstrap disabled skips bootstrap scripts",
setup: func(t *testing.T, dir string) {
t.Helper()
createTask(t, dir, "no-bootstrap", "", "Task")
createRule(t, dir, ".agents/rules/rule1.md", "", "Rule")
createBootstrapScript(t, dir, ".agents/rules/rule1.md", "#!/bin/sh\nexit 1")
},
opts: []Option{
WithBootstrap(false),
},
taskName: "no-bootstrap",
wantErr: false,
check: checkRulesCount(0),
},
{
name: "bootstrap from frontmatter is preferred",
setup: func(t *testing.T, dir string) {
t.Helper()
createTask(t, dir, "frontmatter-bootstrap", "", "Task")
// Create rule with bootstrap in frontmatter that writes a marker file
createRule(t, dir, ".agents/rules/rule-with-frontmatter.md",
"bootstrap: |\n #!/bin/sh\n echo 'frontmatter' > "+filepath.Join(dir, "bootstrap-ran.txt")+"\n",
"Rule content")
},
taskName: "frontmatter-bootstrap",
wantErr: false,
check: checkRulesCount(1),
},
{
name: "bootstrap from frontmatter preferred over file",
setup: func(t *testing.T, dir string) {
t.Helper()
createTask(t, dir, "frontmatter-priority", "", "Task")
// Create rule with BOTH frontmatter and file bootstrap
// Frontmatter writes "frontmatter", file writes "file"
markerPath := filepath.Join(dir, "bootstrap-marker.txt")
createRule(t, dir, ".agents/rules/priority-rule.md",
"bootstrap: |\n #!/bin/sh\n echo 'frontmatter' > "+markerPath+"\n",
"Rule content")
// Also create a file-based bootstrap (should be ignored)
createBootstrapScript(t, dir, ".agents/rules/priority-rule.md",
"#!/bin/sh\necho 'file' > "+markerPath)
},
taskName: "frontmatter-priority",
wantErr: false,
check: checkRulesCount(1),
},
{
name: "bootstrap from file when frontmatter empty",
setup: func(t *testing.T, dir string) {
t.Helper()
createTask(t, dir, "file-fallback", "", "Task")
// Create rule WITHOUT frontmatter bootstrap
markerPath := filepath.Join(dir, "bootstrap-marker.txt")
createRule(t, dir, ".agents/rules/fallback-rule.md", "", "Rule content")
// Create file-based bootstrap (should be used)
createBootstrapScript(t, dir, ".agents/rules/fallback-rule.md",
"#!/bin/sh\necho 'file' > "+markerPath)
},
taskName: "file-fallback",
wantErr: false,
check: checkRulesCount(1),
},
{
name: "agent option collects all rules",
setup: func(t *testing.T, dir string) {
t.Helper()
createTask(t, dir, "agent-task", "", "Task")
createRule(t, dir, ".agents/rules/generic.md", "", "Generic rule")
createRule(t, dir, ".cursor/rules/cursor-rule.md", "", "Cursor rule")
createRule(t, dir, ".github/agents/copilot-rule.md", "", "Copilot rule")
},
opts: []Option{
WithAgent(AgentCursor),
},
taskName: "agent-task",
wantErr: false,
check: checkRulesCount(3),
},
{
name: "task frontmatter agent overrides option",
setup: func(t *testing.T, dir string) {
t.Helper()
createTask(t, dir, "override-task", "agent: copilot", "Task")
createRule(t, dir, ".cursor/rules/cursor-rule.md", "", "Cursor rule")
createRule(t, dir, ".github/agents/copilot-rule.md", "", "Copilot rule")
},
opts: []Option{
WithAgent(AgentCursor), // This should be overridden by task frontmatter
},
taskName: "override-task",
wantErr: false,
check: checkRulesCount(2),
},
{
name: "multiple selector values with OR logic",
setup: func(t *testing.T, dir string) {
t.Helper()
createTask(t, dir, "multi-selector", "selectors:\n env:\n - dev\n - test", "Task")
createRule(t, dir, ".agents/rules/dev-rule.md", "env: dev", "Dev rule")
createRule(t, dir, ".agents/rules/test-rule.md", "env: test", "Test rule")
createRule(t, dir, ".agents/rules/prod-rule.md", "env: prod", "Prod rule")
},
taskName: "multi-selector",
wantErr: false,
check: checkRulesCount(2),
},
{
name: "CLI selectors combined with task selectors use OR logic",
setup: func(t *testing.T, dir string) {
t.Helper()
createTask(t, dir, "or-task", "selectors:\n env: production", "Task with env=production")
createRule(t, dir, ".agents/rules/prod-rule.md", "env: production", "Production rule")
createRule(t, dir, ".agents/rules/dev-rule.md", "env: development", "Development rule")
createRule(t, dir, ".agents/rules/test-rule.md", "env: test", "Test rule")
},
opts: []Option{
WithSelectors(selectors.Selectors{"env": {"development": true}}), // CLI selector for development
},
taskName: "or-task",
wantErr: false,
check: checkRulesCount(2), // prod + dev; test excluded
},
{
name: "CLI selectors combined with array task selectors use OR logic",
setup: func(t *testing.T, dir string) {
t.Helper()
createTask(t, dir, "array-or", "selectors:\n env:\n - production\n - staging", "Task with array selectors")
createRule(t, dir, ".agents/rules/prod-rule.md", "env: production", "Production rule")
createRule(t, dir, ".agents/rules/staging-rule.md", "env: staging", "Staging rule")
createRule(t, dir, ".agents/rules/dev-rule.md", "env: development", "Development rule")
createRule(t, dir, ".agents/rules/test-rule.md", "env: test", "Test rule")
},
opts: []Option{
WithSelectors(selectors.Selectors{"env": {"development": true}}), // CLI adds development
},
taskName: "array-or",
wantErr: false,
check: checkRulesCount(3), // prod + staging + dev; test excluded
},
{
name: "token counting for rules",
setup: func(t *testing.T, dir string) {
t.Helper()
createTask(t, dir, "token-task", "", "Task content")
createRule(t, dir, ".agents/rules/rule1.md", "", "This is rule 1 content")
createRule(t, dir, ".agents/rules/rule2.md", "", "This is rule 2 content")
},
taskName: "token-task",
wantErr: false,
check: checkRulesTokenCounting,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
tmpDir := t.TempDir()
tt.setup(t, tmpDir)
opts := append([]Option{WithSearchPaths(tmpDir)}, tt.opts...)
c := New(opts...)
result, err := c.Run(context.Background(), tt.taskName)
if (err != nil) != tt.wantErr {
t.Errorf("Run() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !tt.wantErr && tt.check != nil {
tt.check(t, result)
}
})
}
}
func checkTaskContains(s string) func(t *testing.T, result *Result) {
return func(t *testing.T, result *Result) {
t.Helper()
if !strings.Contains(result.Task.Content, s) {
t.Errorf("expected %q in task content, got %q", s, result.Task.Content)
}
}
}
func checkTaskNotEmpty(t *testing.T, result *Result) {
t.Helper()
if strings.TrimSpace(result.Task.Content) == "" {
t.Errorf("expected non-empty content, got %q", result.Task.Content)
}
}
func checkCommandsSingleRef(t *testing.T, result *Result) {
t.Helper()
if !strings.Contains(result.Task.Content, "Before command") {
t.Error("expected task content before command")
}
if !strings.Contains(result.Task.Content, "Hello, World!") {
t.Error("expected command content to be substituted")
}
if !strings.Contains(result.Task.Content, "After command") {
t.Error("expected task content after command")
}
}
func checkCommandsMixedText(t *testing.T, result *Result) {
t.Helper()
content := result.Task.Content
if !strings.Contains(content, "# Title") {
t.Error("expected title text")
}
if !strings.Contains(content, "Middle text") {
t.Error("expected middle text")
}
if !strings.Contains(content, "End text") {
t.Error("expected end text")
}
}
func checkCommandsSelectorsFilterRules(t *testing.T, result *Result) {
t.Helper()
if len(result.Rules) != 2 {
t.Errorf("expected 2 rules, got %d", len(result.Rules))
}
foundPostgres := false
for _, rule := range result.Rules {
if strings.Contains(rule.Content, "PostgreSQL rule") {
foundPostgres = true
break
}
}
if !foundPostgres {
t.Error("expected to find PostgreSQL rule")
}
}
// TestContext_Run_Commands tests command substitution in tasks.
//
//nolint:funlen
func TestContext_Run_Commands(t *testing.T) {
t.Parallel()
tests := []struct {
name string
setup func(t *testing.T, dir string)
opts []Option
taskName string
wantErr bool
errContains string
check func(t *testing.T, result *Result)
}{
{
name: "task with single command reference",
setup: func(t *testing.T, dir string) {
t.Helper()
createTask(t, dir, "with-command", "", "Before command\n/greet\nAfter command")
createCommand(t, dir, "greet", "", "Hello, World!")
},
taskName: "with-command",
wantErr: false,
check: checkCommandsSingleRef,
},
{
name: "command with parameters",
setup: func(t *testing.T, dir string) {
t.Helper()
createTask(t, dir, "cmd-with-params", "", "/greet name=\"Alice\"")
createCommand(t, dir, "greet", "", "Hello, ${name}!")
},
taskName: "cmd-with-params",
wantErr: false,
check: checkTaskContains("Hello, Alice!"),
},
{
name: "command with context parameters",
setup: func(t *testing.T, dir string) {
t.Helper()
createTask(t, dir, "ctx-params", "", "/deploy")
createCommand(t, dir, "deploy", "", "Deploying to ${env}")
},
opts: []Option{
WithParams(taskparser.Params{"env": []string{"staging"}}),
},
taskName: "ctx-params",
wantErr: false,
check: checkTaskContains("Deploying to staging"),
},
{
name: "multiple commands in task",
setup: func(t *testing.T, dir string) {
t.Helper()
createTask(t, dir, "multi-cmd", "", "/intro\n\n/body\n\n/outro\n")
createCommand(t, dir, "intro", "", "Introduction")
createCommand(t, dir, "body", "", "Main content")
createCommand(t, dir, "outro", "", "Conclusion")
},
taskName: "multi-cmd",
wantErr: false,
check: checkTaskNotEmpty,
},
{
name: "command not found passes through as-is",
setup: func(t *testing.T, dir string) {
t.Helper()
createTask(t, dir, "missing-cmd", "", "/nonexistent")
},
taskName: "missing-cmd",
wantErr: false,
check: func(t *testing.T, result *Result) {
t.Helper()
if !strings.Contains(result.Prompt, "/nonexistent") {
t.Errorf("expected pass-through of /nonexistent, got %q", result.Prompt)
}
},
},
{
name: "command parameter overrides context parameter",
setup: func(t *testing.T, dir string) {
t.Helper()
createTask(t, dir, "override-param", "", "/msg value=\"specific\"")
createCommand(t, dir, "msg", "", "Value: ${value}")
},
opts: []Option{
WithParams(taskparser.Params{"value": []string{"general"}}),
},
taskName: "override-param",
wantErr: false,
check: checkTaskContains("Value: specific"),
},
{
name: "command with multiple parameters",
setup: func(t *testing.T, dir string) {
t.Helper()
createTask(t, dir, "multi-params", "", "/info name=\"Bob\" age=\"30\" role=\"developer\"")
createCommand(t, dir, "info", "", "Name: ${name}, Age: ${age}, Role: ${role}")
},
taskName: "multi-params",
wantErr: false,
check: checkTaskContains("Name: Bob, Age: 30, Role: developer"),
},
{
name: "mixed text and commands",