-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontextctl.go
More file actions
1337 lines (1230 loc) · 39.3 KB
/
Copy pathcontextctl.go
File metadata and controls
1337 lines (1230 loc) · 39.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
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
// Copyright 2026 Tyler Pate (TGPSKI)
// SPDX-License-Identifier: GPL-3.0-only
//
// contextctl — deterministic tooling for the Directed Contexts pattern.
//
// contextctl scan --repo PATH emit a JSON repository inventory
// contextctl check --repo PATH [--inventory F] validate the Markdown context set
// contextctl routes --repo PATH --cases FILE evaluate route-case fixtures
// contextctl drift --repo PATH report codebase/context-set drift
//
// The root AGENTS.md routing table is canonical. This tool parses and
// validates the Markdown contract directly; there is no hidden manifest.
// The scanner is read-only: it never writes, never follows symlinks outside
// the repository, and never executes commands found in repository files.
package main
import (
"encoding/json"
"flag"
"fmt"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"time"
)
func main() {
if len(os.Args) < 2 {
usage()
os.Exit(2)
}
var err error
switch os.Args[1] {
case "scan":
err = cmdScan(os.Args[2:])
case "check":
err = cmdCheck(os.Args[2:])
case "routes":
err = cmdRoutes(os.Args[2:])
case "drift":
err = cmdDrift(os.Args[2:])
case "-h", "--help", "help":
usage()
default:
fmt.Fprintf(os.Stderr, "contextctl: unknown subcommand %q\n", os.Args[1])
usage()
os.Exit(2)
}
if err != nil {
fmt.Fprintf(os.Stderr, "contextctl: %v\n", err)
os.Exit(1)
}
}
func usage() {
fmt.Fprint(os.Stderr, `usage:
contextctl scan --repo PATH emit JSON repository inventory
contextctl check --repo PATH [--inventory F] validate the context set
[--max-lines N]
contextctl routes --repo PATH --cases FILE evaluate route-case fixtures
contextctl drift --repo PATH [--max-age-days N] [--max-lines N] [--min-lines N]
`)
}
// ───────────────────────────── inventory (scan) ─────────────────────────────
// Inventory is the deterministic scan output. Field order is fixed and all
// slices are sorted so identical repository state yields byte-stable JSON.
type Inventory struct {
Repo RepoMeta `json:"repo"`
PackageRoots []PackageRoot `json:"package_roots"`
Languages []string `json:"languages"`
EntryPoints []string `json:"entry_points"`
Instructions Instructions `json:"instruction_surfaces"`
Codeowners []CodeownerRule `json:"codeowners_rules"`
Commands []Command `json:"commands"`
GeneratedPaths []string `json:"generated_paths"`
VendoredPaths []string `json:"vendored_paths"`
SymlinkEscapes []string `json:"symlink_escapes"`
PolicySignals []string `json:"policy_signals"`
Files []string `json:"files"`
}
type RepoMeta struct {
Name string `json:"name"`
HasGit bool `json:"has_git"`
}
type PackageRoot struct {
Path string `json:"path"`
Manifests []string `json:"manifests"`
}
type Instructions struct {
PrimarySurface string `json:"primary_surface"`
RootAgentsMD bool `json:"root_agents_md"`
HasRoutingTable bool `json:"has_routing_table"`
NestedAgentsMD []string `json:"nested_agents_md"`
HarnessAliases []string `json:"harness_aliases"`
Subagents []string `json:"subagents"`
NativeAgents []string `json:"native_agents"`
Skills []string `json:"skills"`
CodeownersPath string `json:"codeowners_path"`
}
type CodeownerRule struct {
Pattern string `json:"pattern"`
Owners []string `json:"owners"`
}
type Command struct {
Source string `json:"source"`
Name string `json:"name"`
}
var skipDirs = map[string]bool{
".git": true, "node_modules": true, "vendor": true, "dist": true,
"build": true, "target": true, ".venv": true, "venv": true,
"__pycache__": true, ".next": true, ".cache": true, ".terraform": true,
".tox": true, ".mypy_cache": true, ".pytest_cache": true, "coverage": true,
}
var vendorDirNames = map[string]bool{
"node_modules": true, "vendor": true, ".venv": true, "venv": true,
".terraform": true,
}
var generatedDirNames = map[string]bool{
"dist": true, "build": true, "target": true, "__pycache__": true,
".next": true, "coverage": true,
}
var manifestLang = map[string]string{
"go.mod": "go",
"package.json": "javascript",
"tsconfig.json": "typescript",
"pyproject.toml": "python",
"setup.py": "python",
"requirements.txt": "python",
"Cargo.toml": "rust",
"pom.xml": "java",
"build.gradle": "java",
"Gemfile": "ruby",
"composer.json": "php",
"CMakeLists.txt": "c/c++",
}
// packageManifests mark a directory as a package root.
var packageManifests = map[string]bool{
"go.mod": true, "package.json": true, "pyproject.toml": true,
"setup.py": true, "Cargo.toml": true, "pom.xml": true,
"build.gradle": true, "Gemfile": true, "composer.json": true,
"CMakeLists.txt": true,
}
const maxReadBytes = 1 << 20 // never read repository files larger than 1 MiB
func cmdScan(args []string) error {
fs := flag.NewFlagSet("scan", flag.ExitOnError)
repo := fs.String("repo", "", "path to the target repository root")
fs.Parse(args)
if *repo == "" {
return fmt.Errorf("scan: --repo is required")
}
inv, err := scanRepo(*repo)
if err != nil {
return err
}
out, err := json.MarshalIndent(inv, "", " ")
if err != nil {
return err
}
fmt.Println(string(out))
return nil
}
func scanRepo(root string) (*Inventory, error) {
absRoot, err := filepath.Abs(root)
if err != nil {
return nil, err
}
info, err := os.Stat(absRoot)
if err != nil || !info.IsDir() {
return nil, fmt.Errorf("scan: %s is not a directory", root)
}
inv := &Inventory{Repo: RepoMeta{Name: filepath.Base(absRoot)}}
if st, err := os.Stat(filepath.Join(absRoot, ".git")); err == nil && st.IsDir() {
inv.Repo.HasGit = true
}
pkgRoots := map[string][]string{}
langs := map[string]bool{}
entryPoints := map[string]bool{}
walkErr := filepath.WalkDir(absRoot, func(path string, d os.DirEntry, err error) error {
if err != nil {
return nil // unreadable entries are skipped, not fatal
}
rel, _ := filepath.Rel(absRoot, path)
rel = filepath.ToSlash(rel)
if rel == "." {
return nil
}
name := d.Name()
if d.Type()&os.ModeSymlink != 0 {
target, rerr := filepath.EvalSymlinks(path)
if rerr != nil || !strings.HasPrefix(target+string(os.PathSeparator), absRoot+string(os.PathSeparator)) {
inv.SymlinkEscapes = append(inv.SymlinkEscapes, rel)
}
if d.IsDir() {
return filepath.SkipDir // never descend through symlinks
}
inv.Files = append(inv.Files, rel)
return nil
}
if d.IsDir() {
if skipDirs[name] {
if vendorDirNames[name] {
inv.VendoredPaths = append(inv.VendoredPaths, rel)
} else if generatedDirNames[name] {
inv.GeneratedPaths = append(inv.GeneratedPaths, rel)
}
return filepath.SkipDir
}
return nil
}
inv.Files = append(inv.Files, rel)
dir := filepath.ToSlash(filepath.Dir(rel))
if packageManifests[name] {
pkgRoots[dir] = append(pkgRoots[dir], name)
}
if lang, ok := manifestLang[name]; ok {
langs[lang] = true
}
switch {
case name == "main.go":
entryPoints[dir] = true
case strings.HasPrefix(name, "Dockerfile"):
entryPoints[rel] = true
case strings.HasPrefix(rel, ".github/workflows/"):
entryPoints[rel] = true
}
return nil
})
if walkErr != nil {
return nil, walkErr
}
sort.Strings(inv.Files)
inv.Languages = sortedKeys(langs)
for _, dir := range sortedKeys2(pkgRoots) {
ms := pkgRoots[dir]
sort.Strings(ms)
inv.PackageRoots = append(inv.PackageRoots, PackageRoot{Path: dir, Manifests: ms})
}
inv.EntryPoints = sortedKeys(entryPoints)
sort.Strings(inv.GeneratedPaths)
sort.Strings(inv.VendoredPaths)
sort.Strings(inv.SymlinkEscapes)
scanInstructionSurfaces(absRoot, inv)
scanCodeowners(absRoot, inv)
scanCommands(absRoot, inv)
scanPolicySignals(absRoot, inv)
normalizeEmpty(inv)
return inv, nil
}
func scanInstructionSurfaces(root string, inv *Inventory) {
ins := &inv.Instructions
for _, f := range inv.Files {
base := filepath.Base(f)
switch {
case f == "AGENTS.md":
ins.RootAgentsMD = true
if body, err := readSmall(filepath.Join(root, f)); err == nil {
ins.HasRoutingTable = strings.Contains(body, "Load this context")
}
case base == "AGENTS.md":
ins.NestedAgentsMD = append(ins.NestedAgentsMD, f)
case base == "CLAUDE.md" || base == "CODEX.md" || base == "GEMINI.md" || base == ".cursorrules":
ins.HarnessAliases = append(ins.HarnessAliases, f)
}
switch {
case strings.HasPrefix(f, ".subagents/"):
ins.Subagents = append(ins.Subagents, f)
case strings.HasPrefix(f, ".claude/agents/") || strings.HasPrefix(f, ".github/agents/") ||
strings.HasPrefix(f, ".opencode/agents/"):
ins.NativeAgents = append(ins.NativeAgents, f)
case base == "SKILL.md":
ins.Skills = append(ins.Skills, f)
}
}
sort.Strings(ins.NestedAgentsMD)
sort.Strings(ins.HarnessAliases)
sort.Strings(ins.Subagents)
sort.Strings(ins.NativeAgents)
sort.Strings(ins.Skills)
ins.PrimarySurface = primaryInstructionSurface(ins)
}
// primaryInstructionSurface names the root file an agent should read first, by
// precedence: the Context Router, then a root SKILL.md (skill repositories),
// then a router-less root AGENTS.md, then the first root harness alias. Empty
// when the repository has no root instruction surface.
func primaryInstructionSurface(ins *Instructions) string {
if ins.RootAgentsMD && ins.HasRoutingTable {
return "AGENTS.md"
}
for _, s := range ins.Skills {
if s == "SKILL.md" {
return "SKILL.md"
}
}
if ins.RootAgentsMD {
return "AGENTS.md"
}
for _, a := range ins.HarnessAliases {
if !strings.Contains(a, "/") {
return a
}
}
return ""
}
func scanCodeowners(root string, inv *Inventory) {
for _, cand := range []string{".github/CODEOWNERS", "CODEOWNERS", "docs/CODEOWNERS"} {
body, err := readSmall(filepath.Join(root, cand))
if err != nil {
continue
}
inv.Instructions.CodeownersPath = cand
for _, line := range strings.Split(body, "\n") {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") {
continue
}
fields := strings.Fields(line)
if len(fields) < 2 {
continue
}
inv.Codeowners = append(inv.Codeowners, CodeownerRule{Pattern: fields[0], Owners: fields[1:]})
}
break
}
}
var makeTargetRE = regexp.MustCompile(`^([A-Za-z0-9][A-Za-z0-9_./-]*):(?:[^=]|$)`)
func scanCommands(root string, inv *Inventory) {
if body, err := readSmall(filepath.Join(root, "Makefile")); err == nil {
seen := map[string]bool{}
for _, line := range strings.Split(body, "\n") {
if m := makeTargetRE.FindStringSubmatch(line); m != nil && !seen[m[1]] {
seen[m[1]] = true
}
}
for _, t := range sortedKeys(seen) {
inv.Commands = append(inv.Commands, Command{Source: "makefile", Name: t})
}
}
if body, err := readSmall(filepath.Join(root, "package.json")); err == nil {
var pkg struct {
Scripts map[string]string `json:"scripts"`
}
if json.Unmarshal([]byte(body), &pkg) == nil {
names := make([]string, 0, len(pkg.Scripts))
for n := range pkg.Scripts {
names = append(names, n)
}
sort.Strings(names)
for _, n := range names {
inv.Commands = append(inv.Commands, Command{Source: "package.json", Name: n})
}
}
}
}
func scanPolicySignals(root string, inv *Inventory) {
signals := map[string]bool{}
for _, f := range inv.Files {
base := filepath.Base(f)
switch {
case f == "SECURITY.md" || base == ".trivyignore" || base == ".snyk" || base == ".semgrepignore" || base == ".security-context.yaml":
signals["security:"+f] = true
case strings.HasPrefix(f, ".github/workflows/"):
signals["operations:.github/workflows"] = true
case strings.HasPrefix(base, "Dockerfile"):
signals["operations:"+f] = true
case base == ".golangci.yml" || base == ".eslintrc.json" || base == ".eslintrc.js" || base == "ruff.toml" || base == ".ruff.toml":
signals["quality:"+f] = true
case strings.HasSuffix(base, "_test.go") || strings.HasPrefix(f, "tests/") || strings.HasPrefix(f, "test/"):
signals["quality:tests"] = true
}
}
inv.PolicySignals = sortedKeys(signals)
}
// normalizeEmpty replaces nil slices so JSON renders [] instead of null.
func normalizeEmpty(inv *Inventory) {
if inv.PackageRoots == nil {
inv.PackageRoots = []PackageRoot{}
}
if inv.Languages == nil {
inv.Languages = []string{}
}
if inv.EntryPoints == nil {
inv.EntryPoints = []string{}
}
if inv.Instructions.NestedAgentsMD == nil {
inv.Instructions.NestedAgentsMD = []string{}
}
if inv.Instructions.HarnessAliases == nil {
inv.Instructions.HarnessAliases = []string{}
}
if inv.Instructions.Subagents == nil {
inv.Instructions.Subagents = []string{}
}
if inv.Instructions.NativeAgents == nil {
inv.Instructions.NativeAgents = []string{}
}
if inv.Instructions.Skills == nil {
inv.Instructions.Skills = []string{}
}
if inv.Codeowners == nil {
inv.Codeowners = []CodeownerRule{}
}
if inv.Commands == nil {
inv.Commands = []Command{}
}
if inv.GeneratedPaths == nil {
inv.GeneratedPaths = []string{}
}
if inv.VendoredPaths == nil {
inv.VendoredPaths = []string{}
}
if inv.SymlinkEscapes == nil {
inv.SymlinkEscapes = []string{}
}
if inv.PolicySignals == nil {
inv.PolicySignals = []string{}
}
if inv.Files == nil {
inv.Files = []string{}
}
}
// ─────────────────────── markdown contract parsing ──────────────────────────
// Context is one parsed .subagents/AGENTS-*.md module.
type Context struct {
File string // repo-relative path
Name string
Kind string // domain | policy
Description string
Sections map[string][]string
SectionOrder []string
OwnedGlobs []string
LastReviewed string
LineCount int
Body string
}
// Router is the parsed root AGENTS.md.
type Router struct {
File string
PrimaryRows []RouterRow
OverlayRows []RouterRow
UniversalRules []string
Links []string // all relative link targets in the file
Body string
}
type RouterRow struct {
Signal string // column 1
Target string // link target from column 2
Globs []string // code spans from column 3
}
var (
linkRE = regexp.MustCompile(`\[([^\]]*)\]\(([^)\s]+)\)`)
codeSpanRE = regexp.MustCompile("`([^`]+)`")
reviewedRE = regexp.MustCompile(`Last reviewed:\s*(\d{4}-\d{2}-\d{2})`)
)
func parseFrontmatter(lines []string) (meta map[string]string, bodyStart int) {
meta = map[string]string{}
if len(lines) == 0 || strings.TrimSpace(lines[0]) != "---" {
return meta, 0
}
for i := 1; i < len(lines); i++ {
if strings.TrimSpace(lines[i]) == "---" {
return meta, i + 1
}
if k, v, ok := strings.Cut(lines[i], ":"); ok {
key := strings.TrimSpace(k)
val := strings.Trim(strings.TrimSpace(v), `"'`)
if key != "" && !strings.HasPrefix(key, "#") {
meta[key] = val
}
}
}
return map[string]string{}, 0 // unterminated frontmatter: treat as body
}
func parseContextFile(repoRoot, relPath string) (*Context, []string) {
var problems []string
body, err := readSmall(filepath.Join(repoRoot, filepath.FromSlash(relPath)))
if err != nil {
return nil, []string{fmt.Sprintf("%s: unreadable: %v", relPath, err)}
}
lines := strings.Split(body, "\n")
ctx := &Context{File: relPath, Sections: map[string][]string{}, LineCount: len(lines), Body: body}
meta, bodyStart := parseFrontmatter(lines)
ctx.Name = meta["name"]
ctx.Kind = meta["kind"]
ctx.Description = meta["description"]
if ctx.Name == "" {
problems = append(problems, fmt.Sprintf("%s: frontmatter missing `name`", relPath))
}
if ctx.Kind != "domain" && ctx.Kind != "policy" {
problems = append(problems, fmt.Sprintf("%s: frontmatter `kind` must be domain or policy, got %q", relPath, ctx.Kind))
}
if ctx.Description == "" {
problems = append(problems, fmt.Sprintf("%s: frontmatter missing `description`", relPath))
}
current := ""
for _, line := range lines[bodyStart:] {
if strings.HasPrefix(line, "## ") {
current = strings.TrimSpace(strings.TrimPrefix(line, "## "))
ctx.SectionOrder = append(ctx.SectionOrder, current)
continue
}
if current != "" {
ctx.Sections[current] = append(ctx.Sections[current], line)
}
}
for _, line := range ctx.Sections["Owned paths"] {
trimmed := strings.TrimSpace(line)
if !strings.HasPrefix(trimmed, "- ") {
continue
}
if m := codeSpanRE.FindStringSubmatch(trimmed); m != nil {
ctx.OwnedGlobs = append(ctx.OwnedGlobs, m[1])
}
}
if m := reviewedRE.FindStringSubmatch(body); m != nil {
if _, terr := time.Parse("2006-01-02", m[1]); terr != nil {
problems = append(problems, fmt.Sprintf("%s: invalid review date %q", relPath, m[1]))
} else {
ctx.LastReviewed = m[1]
}
} else {
problems = append(problems, fmt.Sprintf("%s: missing `Last reviewed: YYYY-MM-DD` footer", relPath))
}
return ctx, problems
}
var domainSections = []string{
"Scope", "Load or spawn", "Owned paths", "Exclusions",
"Architecture and invariants", "Common mistakes", "Verification", "Adjacent contexts",
}
var policySections = []string{
"Scope", "Policy surface", "Affected contexts", "Invariants", "Activation", "Review checklist",
}
func parseRouter(repoRoot string) (*Router, []string) {
rel := "AGENTS.md"
body, err := readSmall(filepath.Join(repoRoot, rel))
if err != nil {
return nil, []string{fmt.Sprintf("%s: missing root router: %v", rel, err)}
}
r := &Router{File: rel, Body: body}
lines := strings.Split(body, "\n")
r.PrimaryRows = parseRoutingTable(lines, "Load this context")
r.OverlayRows = parseRoutingTable(lines, "Add this context")
inUniversal := false
for _, line := range lines {
if strings.HasPrefix(line, "## ") {
inUniversal = strings.Contains(line, "Universal rules")
continue
}
if inUniversal {
t := strings.TrimSpace(line)
if strings.HasPrefix(t, "- ") {
r.UniversalRules = append(r.UniversalRules, strings.TrimSpace(strings.TrimPrefix(t, "- ")))
}
}
}
for _, m := range linkRE.FindAllStringSubmatch(body, -1) {
target := m[2]
if strings.Contains(target, "://") || strings.HasPrefix(target, "#") || strings.HasPrefix(target, "mailto:") {
continue
}
r.Links = append(r.Links, strings.Split(target, "#")[0])
}
return r, nil
}
// parseRoutingTable extracts rows from the first Markdown table whose header
// row contains marker. Column layout: signal | context link | third column.
func parseRoutingTable(lines []string, marker string) []RouterRow {
var rows []RouterRow
inTable := false
for _, line := range lines {
trimmed := strings.TrimSpace(line)
isRow := strings.HasPrefix(trimmed, "|")
if !inTable {
if isRow && strings.Contains(trimmed, marker) {
inTable = true
}
continue
}
if !isRow {
break
}
cells := splitTableRow(trimmed)
if len(cells) < 2 || strings.HasPrefix(strings.ReplaceAll(cells[0], " ", ""), "---") {
continue
}
row := RouterRow{Signal: cells[0]}
if m := linkRE.FindStringSubmatch(cells[1]); m != nil {
row.Target = strings.Split(m[2], "#")[0]
}
if len(cells) > 2 {
for _, g := range codeSpanRE.FindAllStringSubmatch(cells[2], -1) {
row.Globs = append(row.Globs, g[1])
}
}
if row.Target != "" || row.Signal != "" {
rows = append(rows, row)
}
}
return rows
}
func splitTableRow(row string) []string {
row = strings.Trim(row, "|")
parts := strings.Split(row, "|")
out := make([]string, len(parts))
for i, p := range parts {
out[i] = strings.TrimSpace(p)
}
return out
}
// ───────────────────────── ownership glob matching ──────────────────────────
// normGlob reduces a pattern to (base, isTree). `dir/**` and `dir/` are
// subtree claims; anything else is an exact file claim.
func normGlob(g string) (base string, isTree bool) {
g = strings.TrimPrefix(strings.TrimSpace(g), "./")
switch {
case strings.HasSuffix(g, "/**"):
return strings.TrimSuffix(g, "/**"), true
case strings.HasSuffix(g, "/"):
return strings.TrimSuffix(g, "/"), true
default:
return g, false
}
}
// globMatches reports whether pattern covers path. A path with a trailing
// slash is a directory reference and also matches patterns beneath it.
func globMatches(pattern, path string) bool {
base, isTree := normGlob(pattern)
pathIsDir := strings.HasSuffix(path, "/")
p := strings.TrimSuffix(strings.TrimPrefix(path, "./"), "/")
if isTree {
if p == base || strings.HasPrefix(p, base+"/") {
return true
}
if pathIsDir && strings.HasPrefix(base, p+"/") {
return true // task dir encloses the owned subtree
}
return false
}
if p == base {
return true
}
return pathIsDir && strings.HasPrefix(base, p+"/")
}
// globsOverlap reports whether two ownership claims can cover the same file.
func globsOverlap(a, b string) bool {
ab, at := normGlob(a)
bb, bt := normGlob(b)
switch {
case at && bt:
return ab == bb || strings.HasPrefix(ab, bb+"/") || strings.HasPrefix(bb, ab+"/")
case at:
return bb == ab || strings.HasPrefix(bb, ab+"/")
case bt:
return ab == bb || strings.HasPrefix(ab, bb+"/")
default:
return ab == bb
}
}
// pathExists checks a glob base against the filesystem or an inventory list.
func pathExists(repoRoot, glob string, invFiles []string) bool {
base, isTree := normGlob(glob)
if len(invFiles) > 0 {
for _, f := range invFiles {
if f == base || (isTree && strings.HasPrefix(f, base+"/")) {
return true
}
}
return false
}
st, err := os.Stat(filepath.Join(repoRoot, filepath.FromSlash(base)))
if err != nil {
return false
}
if isTree {
return st.IsDir()
}
return true
}
// ─────────────────────────── context set loading ────────────────────────────
type ContextSet struct {
Root string
Router *Router
Contexts []*Context // sorted by file name
ByName map[string]*Context
Problems []string
}
func loadContextSet(repoRoot string) *ContextSet {
cs := &ContextSet{Root: repoRoot, ByName: map[string]*Context{}}
router, probs := parseRouter(repoRoot)
cs.Problems = append(cs.Problems, probs...)
cs.Router = router
subDir := filepath.Join(repoRoot, ".subagents")
entries, err := os.ReadDir(subDir)
if err != nil {
cs.Problems = append(cs.Problems, ".subagents/: missing directory")
return cs
}
var names []string
for _, e := range entries {
if !e.IsDir() && strings.HasPrefix(e.Name(), "AGENTS-") && strings.HasSuffix(e.Name(), ".md") {
names = append(names, e.Name())
}
}
sort.Strings(names)
for _, n := range names {
ctx, probs := parseContextFile(repoRoot, ".subagents/"+n)
cs.Problems = append(cs.Problems, probs...)
if ctx == nil {
continue
}
cs.Contexts = append(cs.Contexts, ctx)
if ctx.Name != "" {
if prev, dup := cs.ByName[ctx.Name]; dup {
cs.Problems = append(cs.Problems, fmt.Sprintf("%s: duplicate context name %q (also %s)", ctx.File, ctx.Name, prev.File))
} else {
cs.ByName[ctx.Name] = ctx
}
}
}
return cs
}
func (cs *ContextSet) domains() []*Context {
var out []*Context
for _, c := range cs.Contexts {
if c.Kind == "domain" {
out = append(out, c)
}
}
return out
}
// ownersOf returns the sorted names of domain contexts owning path.
func (cs *ContextSet) ownersOf(path string) []string {
seen := map[string]bool{}
for _, c := range cs.domains() {
for _, g := range c.OwnedGlobs {
if globMatches(g, path) {
seen[c.Name] = true
}
}
}
return sortedKeys(seen)
}
// ──────────────────────────────── check ─────────────────────────────────────
func cmdCheck(args []string) error {
fs := flag.NewFlagSet("check", flag.ExitOnError)
repo := fs.String("repo", "", "path to the target repository root")
invPath := fs.String("inventory", "", "scan JSON to validate path existence against (instead of disk)")
maxLines := fs.Int("max-lines", 400, "maximum lines per context guide")
fs.Parse(args)
if *repo == "" {
return fmt.Errorf("check: --repo is required")
}
var invFiles []string
if *invPath != "" {
data, err := os.ReadFile(*invPath)
if err != nil {
return fmt.Errorf("check: %v", err)
}
var inv Inventory
if err := json.Unmarshal(data, &inv); err != nil {
return fmt.Errorf("check: parsing inventory: %v", err)
}
invFiles = inv.Files
}
findings := runCheck(*repo, invFiles, *maxLines)
for _, f := range findings {
fmt.Println("FAIL " + f)
}
if len(findings) > 0 {
return fmt.Errorf("check: %d finding(s)", len(findings))
}
fmt.Println("OK context set is valid")
return nil
}
func runCheck(repoRoot string, invFiles []string, maxLines int) []string {
cs := loadContextSet(repoRoot)
findings := append([]string{}, cs.Problems...)
if cs.Router == nil {
return findings
}
// Required sections per kind; policy contexts must not claim paths.
for _, c := range cs.Contexts {
required := domainSections
if c.Kind == "policy" {
required = policySections
}
for _, sec := range required {
if _, ok := c.Sections[sec]; !ok {
findings = append(findings, fmt.Sprintf("%s: missing required section `## %s`", c.File, sec))
}
}
if c.Kind == "policy" {
if _, ok := c.Sections["Owned paths"]; ok {
findings = append(findings, fmt.Sprintf("%s: policy overlay must not have an `## Owned paths` section", c.File))
}
}
if c.Kind == "domain" && len(c.OwnedGlobs) == 0 {
findings = append(findings, fmt.Sprintf("%s: domain context declares no owned paths", c.File))
}
if c.LineCount > maxLines {
findings = append(findings, fmt.Sprintf("%s: %d lines exceeds limit %d (split candidate)", c.File, c.LineCount, maxLines))
}
// Verification / review checklist must be concrete.
checkSec, item := "Verification", "command or path in backticks"
if c.Kind == "policy" {
checkSec, item = "Review checklist", "checklist item"
}
if lines, ok := c.Sections[checkSec]; ok {
concrete := false
for _, l := range lines {
if c.Kind == "policy" && strings.Contains(l, "- [ ]") {
concrete = true
}
if c.Kind == "domain" && codeSpanRE.MatchString(l) {
concrete = true
}
}
if !concrete {
findings = append(findings, fmt.Sprintf("%s: `## %s` has no concrete %s", c.File, checkSec, item))
}
}
}
// Router link resolution (all relative links).
for _, target := range cs.Router.Links {
if !fileExistsRel(repoRoot, target, invFiles, cs) {
findings = append(findings, fmt.Sprintf("AGENTS.md: link target %s does not resolve", target))
}
}
// Router tables ↔ context files.
routed := map[string]string{} // context file -> table ("primary"|"overlay")
for _, row := range cs.Router.PrimaryRows {
routed[row.Target] = "primary"
c := cs.contextByFile(row.Target)
if c == nil {
findings = append(findings, fmt.Sprintf("AGENTS.md: routing row %q links %s which is not a parseable context", row.Signal, row.Target))
continue
}
if c.Kind != "domain" {
findings = append(findings, fmt.Sprintf("AGENTS.md: primary routing row links %s (kind %s); only domain contexts belong in the primary table", row.Target, c.Kind))
}
for _, g := range row.Globs {
if !containsGlob(c.OwnedGlobs, g) {
findings = append(findings, fmt.Sprintf("AGENTS.md: Owns column lists `%s` for %s but the context does not declare it", g, row.Target))
}
}
}
for _, row := range cs.Router.OverlayRows {
routed[row.Target] = "overlay"
c := cs.contextByFile(row.Target)
if c == nil {
findings = append(findings, fmt.Sprintf("AGENTS.md: overlay row %q links %s which is not a parseable context", row.Signal, row.Target))
continue
}
if c.Kind != "policy" {
findings = append(findings, fmt.Sprintf("AGENTS.md: overlay row links %s (kind %s); only policy contexts belong in the overlay table", row.Target, c.Kind))
}
}
for _, c := range cs.Contexts {
if _, ok := routed[c.File]; !ok {
findings = append(findings, fmt.Sprintf("%s: not referenced by any routing table in AGENTS.md", c.File))
}
}
// Index agreement.
indexPath := filepath.Join(repoRoot, ".subagents", "README.md")
if body, err := readSmall(indexPath); err != nil {
findings = append(findings, ".subagents/README.md: missing index")
} else {
indexed := map[string]bool{}
for _, m := range linkRE.FindAllStringSubmatch(body, -1) {
t := strings.Split(m[2], "#")[0]
if strings.HasPrefix(t, "AGENTS-") {
indexed[t] = true
if cs.contextByFile(".subagents/"+t) == nil {
findings = append(findings, fmt.Sprintf(".subagents/README.md: links %s which does not exist", t))
}
}
}
for _, c := range cs.Contexts {
if !indexed[strings.TrimPrefix(c.File, ".subagents/")] {
findings = append(findings, fmt.Sprintf(".subagents/README.md: does not index %s", c.File))
}
}
}
// Ownership disjointness.
findings = append(findings, ownershipOverlaps(cs)...)
// Owned paths must exist.
for _, c := range cs.domains() {
for _, g := range c.OwnedGlobs {
if !pathExists(repoRoot, g, invFiles) {
findings = append(findings, fmt.Sprintf("%s: owned path `%s` does not exist", c.File, g))
}
}
}
// Adjacent / affected links resolve to real contexts.
for _, c := range cs.Contexts {
sec := "Adjacent contexts"
if c.Kind == "policy" {
sec = "Affected contexts"
}
for _, line := range c.Sections[sec] {
for _, m := range linkRE.FindAllStringSubmatch(line, -1) {
t := strings.Split(m[2], "#")[0]
if strings.Contains(t, "://") {
continue
}
if cs.contextByFile(".subagents/"+t) == nil {
findings = append(findings, fmt.Sprintf("%s: `## %s` links %s which is not a context in this set", c.File, sec, t))
}
}
}
}
// Universal rules must not be duplicated into guides.
for _, rule := range cs.Router.UniversalRules {
if len(rule) < 20 {
continue
}
for _, c := range cs.Contexts {
if strings.Contains(c.Body, rule) {
findings = append(findings, fmt.Sprintf("%s: duplicates universal rule %q from AGENTS.md; universal rules are inherited", c.File, truncate(rule, 60)))
}
}
}
return findings
}