-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathresolve_test.go
More file actions
760 lines (662 loc) · 26.3 KB
/
Copy pathresolve_test.go
File metadata and controls
760 lines (662 loc) · 26.3 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
package agentcontext_test
import (
"crypto/sha256"
"os"
"path/filepath"
"runtime"
"testing"
"github.com/stretchr/testify/require"
"github.com/coder/coder/v2/agent/agentcontext"
"github.com/coder/coder/v2/testutil"
)
func mustWriteFile(t *testing.T, path, content string) {
t.Helper()
require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755))
require.NoError(t, os.WriteFile(path, []byte(content), 0o600))
}
func mustWriteSkill(t *testing.T, dir, name, description string) {
t.Helper()
require.NoError(t, os.MkdirAll(filepath.Join(dir, name), 0o755))
mustWriteFile(t, filepath.Join(dir, name, "SKILL.md"),
"---\nname: "+name+"\ndescription: "+description+"\n---\nSkill body for "+name)
}
func findResource(t *testing.T, resources []agentcontext.Resource, kind agentcontext.ResourceKind, source string) agentcontext.Resource {
t.Helper()
for _, r := range resources {
if r.Kind == kind && r.Source == source {
return r
}
}
t.Fatalf("resource not found: kind=%s source=%s", kind, source)
return agentcontext.Resource{}
}
func TestResolver_ProjectAGENTSFile(t *testing.T) {
t.Parallel()
dir := t.TempDir()
mustWriteFile(t, filepath.Join(dir, "AGENTS.md"), "# Project rules\n\nDo the thing.")
r := &agentcontext.Resolver{}
snap := r.Resolve([]agentcontext.ScanRoot{{Path: dir}})
require.Len(t, snap.Resources, 1)
got := snap.Resources[0]
require.Equal(t, agentcontext.KindInstructionFile, got.Kind)
require.Equal(t, agentcontext.StatusOK, got.Status)
require.Equal(t, filepath.Join(dir, "AGENTS.md"), got.Source)
require.Contains(t, string(got.Payload), "Do the thing.")
require.Equal(t, "Project rules", got.Description)
require.NotEqual(t, [32]byte{}, got.ContentHash)
}
// TestResolver_InstructionNamesAreCaseSensitive verifies the
// resolver matches instruction filenames exactly, mirroring
// codex. A lower-case agents.md (for example a generated API
// reference doc) must not be mistaken for an instruction file.
func TestResolver_InstructionNamesAreCaseSensitive(t *testing.T) {
t.Parallel()
dir := t.TempDir()
mustWriteFile(t, filepath.Join(dir, "agents.md"), "lower\n")
mustWriteFile(t, filepath.Join(dir, "CLAUDE.md"), "claude\n")
r := &agentcontext.Resolver{}
snap := r.Resolve([]agentcontext.ScanRoot{{Path: dir}})
require.Len(t, snap.Resources, 1)
require.Equal(t, filepath.Join(dir, "CLAUDE.md"), snap.Resources[0].Source)
}
func TestResolver_SkillsContainerEmitsEachSubdir(t *testing.T) {
t.Parallel()
dir := t.TempDir()
mustWriteSkill(t, filepath.Join(dir, ".agents", "skills"), "make-coffee", "Coffee skill")
mustWriteSkill(t, filepath.Join(dir, ".agents", "skills"), "fold-laundry", "Laundry skill")
r := &agentcontext.Resolver{}
snap := r.Resolve([]agentcontext.ScanRoot{{Path: dir}})
var kinds []string
for _, res := range snap.Resources {
kinds = append(kinds, res.Kind.String()+":"+filepath.Base(res.Source))
}
require.ElementsMatch(t, []string{
"skill:make-coffee",
"skill:fold-laundry",
}, kinds)
}
func TestResolver_DuplicateSkillNamesFirstRootWins(t *testing.T) {
t.Parallel()
dir := t.TempDir()
firstRoot := filepath.Join(dir, "b", "skills")
secondRoot := filepath.Join(dir, "a", "skills")
mustWriteSkill(t, firstRoot, "make-coffee", "first root")
mustWriteSkill(t, secondRoot, "make-coffee", "second root")
r := &agentcontext.Resolver{}
snap := r.Resolve([]agentcontext.ScanRoot{
{Path: firstRoot},
{Path: secondRoot},
})
require.Len(t, snap.Resources, 1)
require.Equal(t, filepath.Join(firstRoot, "make-coffee"), snap.Resources[0].Source)
require.Equal(t, "first root", snap.Resources[0].Description)
}
func TestResolver_DuplicateSkillNamesFirstValidRootWins(t *testing.T) {
t.Parallel()
dir := t.TempDir()
firstRoot := filepath.Join(dir, "b", "skills")
secondRoot := filepath.Join(dir, "a", "skills")
mustWriteFile(t, filepath.Join(firstRoot, "make-coffee", "SKILL.md"),
"---\nname: drink-tea\ndescription: invalid\n---\nBody")
mustWriteSkill(t, secondRoot, "make-coffee", "second root")
r := &agentcontext.Resolver{}
snap := r.Resolve([]agentcontext.ScanRoot{
{Path: firstRoot},
{Path: secondRoot},
})
require.Len(t, snap.Resources, 2)
winner := findResource(t, snap.Resources, agentcontext.KindSkill, filepath.Join(secondRoot, "make-coffee"))
require.Equal(t, agentcontext.StatusOK, winner.Status)
require.Equal(t, "second root", winner.Description)
}
func TestResolver_DuplicateSkillIDPrefersValidOccurrence(t *testing.T) {
t.Parallel()
if runtime.GOOS == "windows" {
t.Skip("symlink creation requires elevated privileges on Windows")
}
wd := t.TempDir()
skillDir := filepath.Join(wd, ".agents", "skills", "make-coffee")
target := filepath.Join(wd, "shared", "SKILL.md")
mustWriteFile(t, target,
"---\nname: make-coffee\ndescription: valid from broad root\n---\nBody")
require.NoError(t, os.MkdirAll(skillDir, 0o755))
require.NoError(t, os.Symlink(target, filepath.Join(skillDir, "SKILL.md")))
r := &agentcontext.Resolver{}
snap := r.Resolve([]agentcontext.ScanRoot{
{Path: filepath.Join(wd, ".agents", "skills")},
{Path: wd},
})
require.Len(t, snap.Resources, 1)
require.Equal(t, agentcontext.StatusOK, snap.Resources[0].Status)
require.Equal(t, "valid from broad root", snap.Resources[0].Description)
}
func TestResolver_DuplicateSkillIDUsesValidDiscoveryOrder(t *testing.T) {
t.Parallel()
if runtime.GOOS == "windows" {
t.Skip("symlink creation requires elevated privileges on Windows")
}
wd := t.TempDir()
firstSkillDir := filepath.Join(wd, ".agents", "skills", "make-coffee")
target := filepath.Join(wd, "shared", "SKILL.md")
mustWriteFile(t, target,
"---\nname: make-coffee\ndescription: valid from broad root\n---\nBody")
require.NoError(t, os.MkdirAll(firstSkillDir, 0o755))
require.NoError(t, os.Symlink(target, filepath.Join(firstSkillDir, "SKILL.md")))
secondRoot := filepath.Join(t.TempDir(), "skills")
mustWriteSkill(t, secondRoot, "make-coffee", "first valid root")
r := &agentcontext.Resolver{}
snap := r.Resolve([]agentcontext.ScanRoot{
{Path: filepath.Join(wd, ".agents", "skills")},
{Path: secondRoot},
{Path: wd},
})
require.Len(t, snap.Resources, 1)
require.Equal(t, filepath.Join(secondRoot, "make-coffee"), snap.Resources[0].Source)
require.Equal(t, "first valid root", snap.Resources[0].Description)
}
func TestResolver_SkillNameMismatchInvalid(t *testing.T) {
t.Parallel()
dir := t.TempDir()
skillsDir := filepath.Join(dir, ".agents", "skills", "make-coffee")
require.NoError(t, os.MkdirAll(skillsDir, 0o755))
mustWriteFile(t, filepath.Join(skillsDir, "SKILL.md"),
"---\nname: drink-tea\ndescription: oops\n---\nBody")
r := &agentcontext.Resolver{}
snap := r.Resolve([]agentcontext.ScanRoot{{Path: dir}})
require.Len(t, snap.Resources, 1)
got := snap.Resources[0]
require.Equal(t, agentcontext.KindSkill, got.Kind)
require.Equal(t, agentcontext.StatusInvalid, got.Status)
require.Contains(t, got.Error, "does not match directory")
}
// TestResolver_SkillNameNonKebabInvalid exercises the kebab-case
// validation branch in readSkillMeta. The skill name matches the
// parent directory (so the mismatch check passes) but contains
// characters that SkillNamePattern rejects. Without this test
// the kebab branch could be deleted and the suite would still
// pass.
func TestResolver_SkillNameNonKebabInvalid(t *testing.T) {
t.Parallel()
dir := t.TempDir()
skillDir := filepath.Join(dir, ".agents", "skills", "Make_Coffee")
require.NoError(t, os.MkdirAll(skillDir, 0o755))
mustWriteFile(t, filepath.Join(skillDir, "SKILL.md"),
"---\nname: Make_Coffee\ndescription: oops\n---\nBody")
r := &agentcontext.Resolver{}
snap := r.Resolve([]agentcontext.ScanRoot{{Path: dir}})
require.Len(t, snap.Resources, 1)
got := snap.Resources[0]
require.Equal(t, agentcontext.KindSkill, got.Kind)
require.Equal(t, agentcontext.StatusInvalid, got.Status)
require.Contains(t, got.Error, "kebab-case")
}
func TestResolver_MCPConfigEmitted(t *testing.T) {
t.Parallel()
dir := t.TempDir()
contents := `{"mcpServers": {"github": {"env": {"GITHUB_TOKEN": "secret-token"}}}}`
mustWriteFile(t, filepath.Join(dir, ".mcp.json"), contents)
r := &agentcontext.Resolver{}
snap := r.Resolve([]agentcontext.ScanRoot{{Path: dir}})
require.Len(t, snap.Resources, 1)
got := snap.Resources[0]
require.Equal(t, agentcontext.KindMCPConfig, got.Kind)
require.Equal(t, agentcontext.StatusOK, got.Status)
// The .mcp.json payload is intentionally not shipped:
// the file can contain secret-bearing Env/Headers values.
// Only the path + ContentHash are exposed, so consumers
// can detect changes without ever seeing the bytes.
require.Empty(t, got.Payload, "readMCPConfig must not include the file payload")
require.NotEqual(t, [32]byte{}, got.ContentHash, "readMCPConfig must populate ContentHash for change detection")
require.Equal(t, uint64(len(contents)), got.SizeBytes)
}
// TestResolver_SymlinkInsideScanRootAllowed exercises the
// monorepo case where a top-level AGENTS.md is symlinked to
// shared content elsewhere inside the same workspace tree. The
// target lives under the scan root, so the resolver follows the
// symlink, emits the target bytes, and attributes the resource
// to the resolved target path.
func TestResolver_SymlinkInsideScanRootAllowed(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("symlinks require admin privileges on Windows runners")
}
t.Parallel()
dir := testutil.TempDirResolved(t)
target := filepath.Join(dir, "docs", "AGENTS.md")
require.NoError(t, os.MkdirAll(filepath.Dir(target), 0o755))
mustWriteFile(t, target, "shared monorepo guidance")
link := filepath.Join(dir, "AGENTS.md")
require.NoError(t, os.Symlink(target, link))
r := &agentcontext.Resolver{}
snap := r.Resolve([]agentcontext.ScanRoot{{Path: dir}})
// The nested target is not independently recognized (only the
// top-level symlink is), so exactly one resource is emitted,
// carrying the target bytes and attributed to the target.
require.Len(t, snap.Resources, 1)
got := snap.Resources[0]
require.Equal(t, agentcontext.StatusOK, got.Status)
require.Equal(t, target, got.Source)
require.Equal(t, "shared monorepo guidance", string(got.Payload))
}
// TestResolver_SymlinkedInstructionFilesDeduplicated reproduces
// the common repo layout where CLAUDE.md and .cursorrules are
// symlinks to a single AGENTS.md. All three resolve to the same
// file, so the resolver must emit one instruction resource
// attributed to the real AGENTS.md rather than three copies of
// identical content.
func TestResolver_SymlinkedInstructionFilesDeduplicated(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("symlinks require admin privileges on Windows runners")
}
t.Parallel()
dir := testutil.TempDirResolved(t)
agents := filepath.Join(dir, "AGENTS.md")
mustWriteFile(t, agents, "the one true guidance")
require.NoError(t, os.Symlink(agents, filepath.Join(dir, "CLAUDE.md")))
require.NoError(t, os.Symlink(agents, filepath.Join(dir, ".cursorrules")))
r := &agentcontext.Resolver{}
snap := r.Resolve([]agentcontext.ScanRoot{{Path: dir}})
require.Len(t, snap.Resources, 1)
got := snap.Resources[0]
require.Equal(t, agentcontext.KindInstructionFile, got.Kind)
require.Equal(t, agents, got.Source)
require.Equal(t, "the one true guidance", string(got.Payload))
}
// TestResolver_InstructionFilesOnlyAtScanRoot verifies the
// resolver does not descend into subdirectories to collect
// nested instruction files, mirroring codex. A nested
// site/AGENTS.md is ignored while the top-level one is kept.
func TestResolver_InstructionFilesOnlyAtScanRoot(t *testing.T) {
t.Parallel()
dir := t.TempDir()
mustWriteFile(t, filepath.Join(dir, "AGENTS.md"), "root")
mustWriteFile(t, filepath.Join(dir, "site", "AGENTS.md"), "nested")
r := &agentcontext.Resolver{}
snap := r.Resolve([]agentcontext.ScanRoot{{Path: dir}})
require.Len(t, snap.Resources, 1)
require.Equal(t, filepath.Join(dir, "AGENTS.md"), snap.Resources[0].Source)
require.Equal(t, "root", string(snap.Resources[0].Payload))
}
// TestResolver_SymlinkOutsideScanRootRejected guards the
// security boundary. A malicious workspace cannot ship a
// snapshot containing ~/.ssh/id_rsa or /etc/passwd by placing a
// symlink with that target at AGENTS.md, .mcp.json, or
// SKILL.md inside the scan root.
func TestResolver_SymlinkOutsideScanRootRejected(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("symlinks require admin privileges on Windows runners")
}
t.Parallel()
dir := t.TempDir()
secretDir := t.TempDir()
secret := filepath.Join(secretDir, "id_rsa")
mustWriteFile(t, secret, "-----BEGIN OPENSSH PRIVATE KEY-----")
link := filepath.Join(dir, "AGENTS.md")
require.NoError(t, os.Symlink(secret, link))
r := &agentcontext.Resolver{}
snap := r.Resolve([]agentcontext.ScanRoot{{Path: dir}})
require.Len(t, snap.Resources, 1)
got := snap.Resources[0]
require.Equal(t, agentcontext.StatusInvalid, got.Status)
require.Empty(t, got.Payload, "escaping symlink target must not be shipped")
require.Contains(t, got.Error, "escapes scan root")
}
// TestResolver_BrokenSymlink emits Unreadable for a dangling
// link rather than crashing the walk.
func TestResolver_BrokenSymlink(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("symlinks require admin privileges on Windows runners")
}
t.Parallel()
dir := t.TempDir()
link := filepath.Join(dir, "AGENTS.md")
require.NoError(t, os.Symlink(filepath.Join(dir, "does-not-exist"), link))
r := &agentcontext.Resolver{}
snap := r.Resolve([]agentcontext.ScanRoot{{Path: dir}})
require.Len(t, snap.Resources, 1)
require.Equal(t, agentcontext.StatusUnreadable, snap.Resources[0].Status)
}
func TestResolver_OversizeInstructionFile(t *testing.T) {
t.Parallel()
dir := t.TempDir()
// Write a file larger than the per-resource cap.
big := make([]byte, 200)
for i := range big {
big[i] = 'a'
}
mustWriteFile(t, filepath.Join(dir, "AGENTS.md"), string(big))
r := &agentcontext.Resolver{MaxResourceBytes: 100}
snap := r.Resolve([]agentcontext.ScanRoot{{Path: dir}})
require.Len(t, snap.Resources, 1)
got := snap.Resources[0]
require.Equal(t, agentcontext.StatusOversize, got.Status)
require.Empty(t, got.Payload)
require.Equal(t, uint64(200), got.SizeBytes)
// Hash over capped slice is still populated so callers
// can detect "still oversize but content changed".
require.NotEqual(t, [32]byte{}, got.ContentHash)
}
func TestResolver_AggregateCapExcludes(t *testing.T) {
t.Parallel()
// Instruction files are only read at a scan root's top level,
// so each contributing file lives at its own scan root.
dirRoot := t.TempDir()
dirA := t.TempDir()
dirB := t.TempDir()
mustWriteFile(t, filepath.Join(dirRoot, "AGENTS.md"), "small")
mustWriteFile(t, filepath.Join(dirA, "AGENTS.md"), "AAAA")
mustWriteFile(t, filepath.Join(dirB, "AGENTS.md"), "BBBB")
// Aggregate cap of 9 bytes lets two of the three (5+4) bytes
// through but excludes the third regardless of order.
r := &agentcontext.Resolver{MaxSnapshotBytes: 9}
snap := r.Resolve([]agentcontext.ScanRoot{
{Path: dirRoot},
{Path: dirA},
{Path: dirB},
})
var excluded int
for _, res := range snap.Resources {
if res.Status == agentcontext.StatusExcluded {
excluded++
}
}
require.Equal(t, 1, excluded)
}
func TestResolver_CountCapExcludes(t *testing.T) {
t.Parallel()
// Instruction files are only read at a scan root's top level,
// so spread the five files across five scan roots.
roots := make([]agentcontext.ScanRoot, 0, 5)
for i := 0; i < 5; i++ {
d := t.TempDir()
mustWriteFile(t, filepath.Join(d, "AGENTS.md"), "x")
roots = append(roots, agentcontext.ScanRoot{Path: d})
}
r := &agentcontext.Resolver{MaxResources: 3}
snap := r.Resolve(roots)
require.Len(t, snap.Resources, 5)
var excluded int
for _, res := range snap.Resources {
if res.Status == agentcontext.StatusExcluded {
excluded++
}
}
require.Equal(t, 2, excluded)
}
// TestResolver_MCPConfigOnlyAtScanRoot verifies that .mcp.json is
// recognized only at a scan root's top level. A nested config is
// ignored because the resolver no longer walks the tree.
func TestResolver_MCPConfigOnlyAtScanRoot(t *testing.T) {
t.Parallel()
dir := t.TempDir()
mustWriteFile(t, filepath.Join(dir, ".mcp.json"), `{"mcpServers": {}}`)
mustWriteFile(t, filepath.Join(dir, "sub", ".mcp.json"), `{"mcpServers": {}}`)
r := &agentcontext.Resolver{}
snap := r.Resolve([]agentcontext.ScanRoot{{Path: dir}})
require.Len(t, snap.Resources, 1)
require.Equal(t, agentcontext.KindMCPConfig, snap.Resources[0].Kind)
require.Equal(t, filepath.Join(dir, ".mcp.json"), snap.Resources[0].Source)
}
// TestResolver_SkillsOnlyFromFixedContainers verifies skills are
// discovered from the fixed container locations (skills,
// .agents/skills, .claude/skills, .codex/skills) and never from an
// arbitrary skills/ directory nested elsewhere in the tree.
func TestResolver_SkillsOnlyFromFixedContainers(t *testing.T) {
t.Parallel()
dir := t.TempDir()
mustWriteSkill(t, filepath.Join(dir, "skills"), "water-plants", "p")
mustWriteSkill(t, filepath.Join(dir, ".agents", "skills"), "make-coffee", "c")
mustWriteSkill(t, filepath.Join(dir, ".claude", "skills"), "fold-laundry", "l")
mustWriteSkill(t, filepath.Join(dir, ".codex", "skills"), "walk-dog", "d")
// A skills/ directory buried under an arbitrary path is not a
// fixed container location and must be ignored.
mustWriteSkill(t, filepath.Join(dir, "pkg", "skills"), "buried", "b")
r := &agentcontext.Resolver{}
snap := r.Resolve([]agentcontext.ScanRoot{{Path: dir}})
var names []string
for _, res := range snap.Resources {
require.Equal(t, agentcontext.KindSkill, res.Kind)
names = append(names, filepath.Base(res.Source))
}
require.ElementsMatch(t,
[]string{"water-plants", "make-coffee", "fold-laundry", "walk-dog"}, names)
}
func TestResolver_UserSourceAttribution(t *testing.T) {
t.Parallel()
dir := t.TempDir()
mustWriteFile(t, filepath.Join(dir, "AGENTS.md"), "user-added")
r := &agentcontext.Resolver{}
snap := r.Resolve([]agentcontext.ScanRoot{{Path: dir, UserSource: dir}})
require.Len(t, snap.Resources, 1)
require.Equal(t, dir, snap.Resources[0].SourcePath)
}
func TestResolver_MissingRootSilentlyIgnored(t *testing.T) {
t.Parallel()
r := &agentcontext.Resolver{}
snap := r.Resolve([]agentcontext.ScanRoot{{Path: "/nonexistent/path"}})
require.Empty(t, snap.Resources)
require.Empty(t, snap.SnapshotError)
}
func TestResolver_SingleFileRootClassified(t *testing.T) {
t.Parallel()
dir := t.TempDir()
path := filepath.Join(dir, "AGENTS.md")
mustWriteFile(t, path, "x")
r := &agentcontext.Resolver{}
snap := r.Resolve([]agentcontext.ScanRoot{{Path: path}})
require.Len(t, snap.Resources, 1)
require.Equal(t, agentcontext.KindInstructionFile, snap.Resources[0].Kind)
}
func TestResolver_DuplicateRootsDeduplicated(t *testing.T) {
t.Parallel()
dir := t.TempDir()
mustWriteFile(t, filepath.Join(dir, "AGENTS.md"), "x")
r := &agentcontext.Resolver{}
snap := r.Resolve([]agentcontext.ScanRoot{
{Path: dir},
{Path: dir},
{Path: dir},
})
require.Len(t, snap.Resources, 1)
}
func TestResolver_MCPResources(t *testing.T) {
t.Parallel()
dir := t.TempDir()
mcpRes := agentcontext.Resource{
ID: "mcp_server:github",
Kind: agentcontext.KindMCPServer,
Source: "github",
Status: agentcontext.StatusOK,
Payload: []byte("tool-list-json"),
ContentHash: sha256.Sum256([]byte("tool-list-json")),
Description: "GitHub MCP server",
}
r := &agentcontext.Resolver{
MCPResources: func() []agentcontext.Resource { return []agentcontext.Resource{mcpRes} },
}
snap := r.Resolve([]agentcontext.ScanRoot{{Path: dir}})
got := findResource(t, snap.Resources, agentcontext.KindMCPServer, "github")
require.Equal(t, agentcontext.StatusOK, got.Status)
require.Equal(t, "GitHub MCP server", got.Description)
}
// TestResolver_MCPResourcesRespectAggregateByteCap guards the
// contract that a single oversized MCP payload cannot blow past
// MaxSnapshotBytes with StatusOK.
func TestResolver_MCPResourcesRespectAggregateByteCap(t *testing.T) {
t.Parallel()
dir := t.TempDir()
big := make([]byte, 1024)
for i := range big {
big[i] = 'x'
}
mcpRes := agentcontext.Resource{
ID: "mcp_server:big",
Kind: agentcontext.KindMCPServer,
Source: "big",
Status: agentcontext.StatusOK,
Payload: big,
ContentHash: sha256.Sum256(big),
}
r := &agentcontext.Resolver{
MaxSnapshotBytes: 512,
MCPResources: func() []agentcontext.Resource { return []agentcontext.Resource{mcpRes} },
}
snap := r.Resolve([]agentcontext.ScanRoot{{Path: dir}})
got := findResource(t, snap.Resources, agentcontext.KindMCPServer, "big")
require.Equal(t, agentcontext.StatusExcluded, got.Status,
"MCP payload exceeding MaxSnapshotBytes must be excluded")
require.Empty(t, got.Payload)
require.NotEmpty(t, snap.SnapshotError, "snapshot must surface the cap breach")
}
// TestResolver_MCPExcludedFromAggregateHash verifies that MCP resources
// (config and live servers) are carried in the snapshot but excluded
// from the drift/aggregate hash, so an MCP server connecting (or its
// tools changing) does not flip already-hydrated chats to dirty.
func TestResolver_MCPExcludedFromAggregateHash(t *testing.T) {
t.Parallel()
dir := t.TempDir()
// An instruction file provides drift-relevant pinned content.
mustWriteFile(t, filepath.Join(dir, "AGENTS.md"), "workspace rules")
base := (&agentcontext.Resolver{}).Resolve([]agentcontext.ScanRoot{{Path: dir}})
mcpRes := agentcontext.Resource{
ID: "mcp_server:github",
Kind: agentcontext.KindMCPServer,
Source: "github",
Name: "github",
Status: agentcontext.StatusOK,
ContentHash: sha256.Sum256([]byte("tool-list")),
Tools: []agentcontext.MCPTool{{Name: "search"}},
}
withMCP := (&agentcontext.Resolver{
MCPResources: func() []agentcontext.Resource { return []agentcontext.Resource{mcpRes} },
}).Resolve([]agentcontext.ScanRoot{{Path: dir}})
// The MCP server resource is present in the snapshot...
got := findResource(t, withMCP.Resources, agentcontext.KindMCPServer, "github")
require.Len(t, got.Tools, 1)
// ...but does not change the drift/aggregate hash.
require.Equal(t, base.AggregateHash, withMCP.AggregateHash,
"MCP resources must not participate in the drift hash")
}
// TestResolver_UnreadableInstructionFile verifies the
// permission-denied walk path produces a StatusUnreadable
// resource classified with the correct kind, matching the
// classification the resolver would emit on a successful read.
func TestResolver_UnreadableInstructionFile(t *testing.T) {
t.Parallel()
if runtime.GOOS == "windows" {
t.Skip("file mode 0o000 does not deny reads on Windows")
}
if os.Geteuid() == 0 {
t.Skip("root bypasses file mode permissions")
}
dir := t.TempDir()
path := filepath.Join(dir, "AGENTS.md")
mustWriteFile(t, path, "hello")
require.NoError(t, os.Chmod(path, 0o000))
t.Cleanup(func() { _ = os.Chmod(path, 0o600) })
r := &agentcontext.Resolver{}
snap := r.Resolve([]agentcontext.ScanRoot{{Path: dir}})
require.Len(t, snap.Resources, 1)
got := snap.Resources[0]
require.Equal(t, agentcontext.KindInstructionFile, got.Kind)
require.Equal(t, agentcontext.StatusUnreadable, got.Status)
require.NotEmpty(t, got.Error)
}
// TestResolver_UnreadableMCPConfig confirms the walk-error path
// uses the file's real kind, not a hardcoded fallback. Without
// this, a permission flip on .mcp.json would produce a phantom
// resource ID swap when the permission is later restored.
func TestResolver_UnreadableMCPConfig(t *testing.T) {
t.Parallel()
if runtime.GOOS == "windows" {
t.Skip("file mode 0o000 does not deny reads on Windows")
}
if os.Geteuid() == 0 {
t.Skip("root bypasses file mode permissions")
}
dir := t.TempDir()
path := filepath.Join(dir, ".mcp.json")
mustWriteFile(t, path, `{"mcpServers": {}}`)
require.NoError(t, os.Chmod(path, 0o000))
t.Cleanup(func() { _ = os.Chmod(path, 0o600) })
r := &agentcontext.Resolver{}
snap := r.Resolve([]agentcontext.ScanRoot{{Path: dir}})
require.Len(t, snap.Resources, 1)
got := snap.Resources[0]
require.Equal(t, agentcontext.KindMCPConfig, got.Kind)
require.Equal(t, agentcontext.StatusUnreadable, got.Status)
require.NotEmpty(t, got.Error)
}
func TestResourceKindString(t *testing.T) {
t.Parallel()
tests := []struct {
kind agentcontext.ResourceKind
want string
}{
{agentcontext.KindUnspecified, "unknown"},
{agentcontext.KindInstructionFile, "instruction_file"},
{agentcontext.KindSkill, "skill"},
{agentcontext.KindMCPConfig, "mcp_config"},
{agentcontext.KindMCPServer, "mcp_server"},
{agentcontext.KindPlugin, "plugin"},
{agentcontext.KindHook, "hook"},
{agentcontext.KindSubagent, "subagent"},
{agentcontext.KindCommand, "command"},
{agentcontext.ResourceKind(999), "unknown"},
}
for _, tt := range tests {
require.Equal(t, tt.want, tt.kind.String())
}
}
func TestResourceStatusString(t *testing.T) {
t.Parallel()
tests := []struct {
status agentcontext.ResourceStatus
want string
}{
{agentcontext.StatusOK, "ok"},
{agentcontext.StatusOversize, "oversize"},
{agentcontext.StatusUnreadable, "unreadable"},
{agentcontext.StatusInvalid, "invalid"},
{agentcontext.StatusExcluded, "excluded"},
{agentcontext.ResourceStatus(999), "unknown"},
}
for _, tt := range tests {
require.Equal(t, tt.want, tt.status.String())
}
}
func TestComputeAggregateHash_DeterministicAcrossOrder(t *testing.T) {
t.Parallel()
a := agentcontext.Resource{
ID: "instruction_file:/a/AGENTS.md",
Kind: agentcontext.KindInstructionFile,
Source: "/a/AGENTS.md",
Status: agentcontext.StatusOK,
}
b := agentcontext.Resource{
ID: "instruction_file:/b/AGENTS.md",
Kind: agentcontext.KindInstructionFile,
Source: "/b/AGENTS.md",
Status: agentcontext.StatusOK,
}
got1 := agentcontext.ComputeAggregateHash([]agentcontext.Resource{a, b})
got2 := agentcontext.ComputeAggregateHash([]agentcontext.Resource{b, a})
require.Equal(t, got1, got2)
}
func TestComputeAggregateHash_ChangesOnContent(t *testing.T) {
t.Parallel()
base := agentcontext.Resource{
ID: "instruction_file:/a/AGENTS.md",
Kind: agentcontext.KindInstructionFile,
Source: "/a/AGENTS.md",
Status: agentcontext.StatusOK,
}
hash1 := agentcontext.ComputeAggregateHash([]agentcontext.Resource{base})
withContent := base
withContent.ContentHash = [32]byte{0x01}
hash2 := agentcontext.ComputeAggregateHash([]agentcontext.Resource{withContent})
require.NotEqual(t, hash1, hash2)
withStatus := base
withStatus.Status = agentcontext.StatusOversize
hash3 := agentcontext.ComputeAggregateHash([]agentcontext.Resource{withStatus})
require.NotEqual(t, hash1, hash3)
}