// Package guardstest turns the prose rules in AGENTS.md into tests. // // CARLOS's own rule: "a guard a shell step can satisfy is a guard a // shell step can be wrong about — put guards inside the test binary." // Every rule here is one AGENTS.md states, and the point is that // nobody has to remember it. // // There is no production code in this package. package guardstest import ( "go/ast" "go/parser" "go/token" "os" "path/filepath" "regexp" "runtime" "strings" "testing" ) // repoRoot is found from this file's own path, never from the working // directory: `go test ./...` and a run from an editor have different // working directories and only one of them would be right. func repoRoot(t *testing.T) string { t.Helper() _, file, _, ok := runtime.Caller(0) if !ok { t.Fatal("runtime.Caller failed") } return filepath.Dir(filepath.Dir(filepath.Dir(file))) } // walk visits every file under root with one of the given extensions, // skipping the directories that hold nothing we wrote. func walk(t *testing.T, root string, exts []string, fn func(path string, body []byte)) { t.Helper() err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error { if err != nil { return err } if info.IsDir() { switch info.Name() { case ".git", "node_modules", "releases", ".claude", "vendor": return filepath.SkipDir } return nil } for _, ext := range exts { if strings.HasSuffix(path, ext) { b, err := os.ReadFile(path) if err != nil { return err } fn(path, b) return nil } } return nil }) if err != nil { t.Fatalf("walk: %v", err) } } // The 300-line cap, on everything we write. // // Exemptions are by EXACT PATH and each carries its reason. The // vendored scripts are rastrillo's, delivered by the scaffold and // pinned byte-for-byte by vendored_test.go — editing them to satisfy a // line cap would break that pin, which is the more valuable guard. var lineCapExempt = map[string]string{ "internal/calendar/static/datetime.js": "vendored from rastrillo; pinned byte-for-byte", "internal/calendar/static/rastrillo.js": "rastrillo's, written from estilo's busy by scripts/writeestilo; pinned byte-for-byte", "internal/calendar/static/select.js": "vendored from rastrillo; pinned byte-for-byte", "internal/calendar/static/tokens.css": "vendored from rastrillo; pinned byte-for-byte", "internal/calendar/static/theme.css": "written from estilo by scripts/writeestilo; pinned byte-for-byte", } func TestNoFileExceedsTheLineCap(t *testing.T) { const cap = 300 root := repoRoot(t) walk(t, root, []string{".go", ".js"}, func(path string, body []byte) { rel, _ := filepath.Rel(root, path) rel = filepath.ToSlash(rel) if _, ok := lineCapExempt[rel]; ok { return } if n := len(strings.Split(string(body), "\n")); n > cap { t.Errorf("%s is %d lines, cap is %d — split it", rel, n, cap) } }) } // An exemption for a file that no longer exists proves nothing, and // quietly accumulates. Sheets shipped a walk that skipped vendor/ and // therefore proved nothing at all; this is the test that catches the // equivalent here. func TestEveryLineCapExemptionIsLive(t *testing.T) { root := repoRoot(t) for rel, reason := range lineCapExempt { if _, err := os.Stat(filepath.Join(root, rel)); err != nil { t.Errorf("line-cap exemption %q (%s) names a file that does not exist", rel, reason) } } } // sessions.UserID returns (0, false) under the magic-link plugin, // because the Subject is a verified address rather than a numeric id. // Every owner-scoped query built on it silently filters to person 0 — // a calendar that looks empty rather than broken, which is the more // expensive failure. // // An AST walk rather than a grep, so this comment — which names the // call it forbids — does not need an exemption from its own rule. func TestNeverSessionsUserID(t *testing.T) { root := repoRoot(t) fset := token.NewFileSet() walk(t, root, []string{".go"}, func(path string, body []byte) { rel, _ := filepath.Rel(root, path) f, err := parser.ParseFile(fset, path, body, 0) if err != nil { return // a file that does not parse is the compiler's problem } // Only if the file actually imports the sessions package. imported := "" for _, im := range f.Imports { if p := strings.Trim(im.Path.Value, `"`); p == "amadan.net/rastrillo/rastrillo/sessions" || p == preMoveRastrillo+"/sessions" { imported = "sessions" if im.Name != nil { imported = im.Name.Name } } } if imported == "" { return } ast.Inspect(f, func(n ast.Node) bool { sel, ok := n.(*ast.SelectorExpr) if !ok || sel.Sel.Name != "UserID" { return true } if id, ok := sel.X.(*ast.Ident); ok && id.Name == imported { t.Errorf("%s calls %s.UserID — use auth.From(r), and CurrentPerson(r) for the id", filepath.ToSlash(rel), imported) } return true }) }) } // A cgo SQLite driver would break CGO_ENABLED=0, and the failure is a // binary that will not build for the platform rather than one that // misbehaves — but it is cheap to catch here and expensive to discover // at ship time. func TestNoCgoSQLiteDriver(t *testing.T) { root := repoRoot(t) forbidden := []string{"gorm.io/driver/sqlite", "github.com/mattn/go-sqlite3", "glebarez"} walk(t, root, []string{".go", ".mod"}, func(path string, body []byte) { rel, _ := filepath.Rel(root, path) if strings.HasSuffix(rel, "guards_test.go") { return // this file names them in order to forbid them } for _, f := range forbidden { if strings.Contains(string(body), f) { t.Errorf("%s references %s — the stack is cgo-free", filepath.ToSlash(rel), f) } } }) } // Every var(--rst-*) this app's own CSS uses must actually be declared // by the vendored token or theme files. // // Written because an invented token name is invisible: the property // falls back to nothing, the element renders unstyled-ish, and nobody // notices until a screen looks slightly wrong on a canary. func TestEveryTokenWeUseIsDefined(t *testing.T) { root := repoRoot(t) static := filepath.Join(root, "internal", "calendar", "static") declared := map[string]bool{} for _, name := range []string{"tokens.css", "theme.css"} { b, err := os.ReadFile(filepath.Join(static, name)) if err != nil { t.Fatalf("read %s: %v", name, err) } for _, m := range regexp.MustCompile(`(--rst-[A-Za-z0-9-]+)\s*:`).FindAllStringSubmatch(string(b), -1) { declared[m[1]] = true } } if len(declared) < 20 { t.Fatalf("only %d tokens found in the vendored CSS; the parse is wrong, so this test proves nothing", len(declared)) } used := regexp.MustCompile(`var\((--rst-[A-Za-z0-9-]+)`) for _, name := range []string{"calendar.css"} { b, err := os.ReadFile(filepath.Join(static, name)) if err != nil { t.Fatalf("read %s: %v", name, err) } for _, m := range used.FindAllStringSubmatch(string(b), -1) { if !declared[m[1]] { t.Errorf("%s uses %s, which no vendored stylesheet declares", name, m[1]) } } } } // This app's own components take cal-. rst- is the framework's // namespace and a future release may claim a name we took; estilo- is // the suite's, and a month grid is not a suite component until a second // app copies one. func TestOurCSSDoesNotClaimAnotherPrefix(t *testing.T) { root := repoRoot(t) b, err := os.ReadFile(filepath.Join(root, "internal", "calendar", "static", "calendar.css")) if err != nil { t.Fatalf("read calendar.css: %v", err) } // Selectors only. var(--rst-*) is a token reference and entirely // correct — this app is meant to use the framework's tokens. bad := regexp.MustCompile(`\[\s*(rst|estilo)-|\.(rst|estilo)-`) for _, m := range bad.FindAllString(string(b), -1) { t.Errorf("calendar.css defines a selector for another namespace: %q — this app's prefix is cal-", m) } } // Seven rastrillo utilities keep the class spelling and have no // attribute twin. Written in attribute position they silently do // nothing — the failure that put a visible "sr-only" label in sheets' // toolbar. func TestUtilitiesAreNeverWrittenAsAttributes(t *testing.T) { root := repoRoot(t) utilities := []string{"rst-sr-only", "rst-mono", "rst-grow", "rst-m-hide", "rst-danger", "rst-nm", "rst-cell-mut"} walk(t, filepath.Join(root, "internal", "calendar", "templates"), []string{".html"}, func(path string, body []byte) { rel, _ := filepath.Rel(root, path) for _, u := range utilities { // In attribute position it appears as a bare word // preceded by whitespace inside a tag, never as // class="...". bare := regexp.MustCompile(`<[^>]*\s` + regexp.QuoteMeta(u) + `[\s=>]`) for _, m := range bare.FindAllString(string(body), -1) { if strings.Contains(m, `class=`) { continue } t.Errorf("%s writes %s in attribute position (%q); it is a class-only utility", filepath.ToSlash(rel), u, strings.TrimSpace(m)) } } }) } // preMoveRastrillo is rastrillo's module path before it moved to // amadan.net/rastrillo/rastrillo (v0.25.0). Nothing after v0.23.0 was // released under it, so code importing it gets no rastrillo fix, and // its own vendored-asset check cannot tell. That is how Calendar kept // zooming iOS on every tap for a month after rastrillo fixed it // (polish audit r3, item 1). const preMoveRastrillo = "github.com/carlosframework/rastrillo" // preMoveAllowed is the one file that may still import it, and why: // rastrillo/native's server takes the old path's *sessions.Sessions. // Delete the entry when native/server moves. var preMoveAllowed = map[string]string{ "internal/calendar/native.go": preMoveRastrillo + "/sessions", } // TestNoPreMoveRastrillo fails on any import of rastrillo's old module // path outside preMoveAllowed. func TestNoPreMoveRastrillo(t *testing.T) { root := repoRoot(t) fset := token.NewFileSet() walk(t, root, []string{".go"}, func(path string, body []byte) { rel, _ := filepath.Rel(root, path) rel = filepath.ToSlash(rel) f, err := parser.ParseFile(fset, path, body, parser.ImportsOnly) if err != nil { return // a file that does not parse is the compiler's problem } for _, im := range f.Imports { imp := strings.Trim(im.Path.Value, `"`) if (imp == preMoveRastrillo || strings.HasPrefix(imp, preMoveRastrillo+"/")) && preMoveAllowed[rel] != imp { t.Errorf("%s: imports %q, rastrillo's frozen pre-move path; use amadan.net/rastrillo/rastrillo", rel, imp) } } }) }