beads/backend/completeness_test.go
Julian Knutsen f66375459f
test(bazel): runfiles helpers + declared inputs for scan-guard tests (#6828)
* test(bazel): add internal/testutil/bazeltest runfiles helpers

Repository-path resolution for tests that works identically under plain
go test (package cwd, full checkout), bazel test locally, and remote
execution (declared runfiles only):

- IsBazel, RepoRoot (BEADS_TEST_REPO_ROOT, then the runfiles workspace
  root, then a go.mod walk), OverrideRoot (drop-in condition for existing
  helpers; empty under plain go test), CallerDir
- Runfile for $(rlocationpath) values, GOROOT for type-checking tests
- ShardFreeEnv for helpers that re-exec a test binary

Every helper reduces to the pre-Bazel behavior under go test.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(bazel): declare source/data reads for 14 scan-guard targets

Source-scanning and repo-file tests read files their Bazel targets never
declared, so they failed under `bazel test` (and could not run on remote
workers at all). Declare narrow inputs as `data` and resolve paths through
bazeltest where the test located the tree via runtime.Caller:

- tools/bazel/go_srcs.py (run by `make bazel-sync` after gazelle) keeps a
  managed `go_srcs` filegroup in the packages whose Go source tests scan,
  plus `//internal/storage:tree_go_srcs` for the storage-tree walk. Bazel
  globs stop at package boundaries, so the aggregate needs one filegroup
  per package; the script keeps it in sync and gazelle-stable.
- Hand-written narrow inputs: //internal/storage/schema:migrations,
  //:docsync_files, //plugins/beads:plugin_files, and exports of
  .gitattributes, .claude-plugin/marketplace.json, cmd/bd list.go and
  ready.go, testutil/testdoltcommon.go, scripts README.md and the release
  catalog, each visible only to its consumer.
- runtime.Caller-based roots in backend, backend/conformance,
  internal/storage, internal/formula and test/docsync now go through
  bazeltest.CallerDir / OverrideRoot; relative-path tests need data only.
- integrations/ leaves .bazelignore (it is still gazelle-excluded) so the
  docsync link check can declare integrations/beads-mcp/PYPI.md.

Under --config=prcore every target reports the same PASS/SKIP/FAIL test
set as `go test -race -short` for its package, locally and remotely.
Plain `go test` behavior is unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(bazel): guard generated go_srcs and harden bazeltest root override

- tools/bazel/go_srcs.py: add --check (print diff, exit 1 on stale blocks);
  new `make bazel-sync-check` target runs it.
- scripts/bazel_policy_test.go: under go test, assert every tree_go_srcs
  (//internal/storage) lists exactly the BUILD.bazel packages below its
  root, run go_srcs.py --check, and forbid BUILD files under docs/ and
  engdocs/ (they would cut subtrees out of //:docsync_files).
- bazeltest: honor BEADS_TEST_REPO_ROOT only when it holds go.mod
  (RepoRoot fails loudly otherwise); drop the unused GOROOT() helper,
  whose compiled-in branch could never fire under rules_go.
- scripts/ci/lib/test-env.sh: unset BEADS_TEST_REPO_ROOT.
- Document the hand-listed out-of-tree link targets in //:docsync_files.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* build(bazel): re-sync BUILD files with main

Regenerated with make bazel-sync after commits that landed while the
scaffold PR was in CI (new internal/execenv, gitenv, gitignore packages
and new sources/deps).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(bazel): declare init_safety_help.go for docsync

TestInitSafetyCLIHelpCoversReCloneGotchas (#6431) reads
cmd/bd/init_safety_help.go; export it to //test/docsync only.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-27 08:24:08 -07:00

191 lines
6 KiB
Go

package backend_test
import (
"go/ast"
"go/parser"
"go/token"
"io/fs"
"reflect"
"runtime"
"sort"
"strings"
"testing"
"github.com/steveyegge/beads/backend"
"github.com/steveyegge/beads/backend/conformance"
"github.com/steveyegge/beads/internal/testutil/bazeltest"
)
const internalPrefix = "github.com/steveyegge/beads/internal/"
// TestPublicSurfaceComplete is the drift guard on the external-backend door:
// every named internal type reachable from the contract an external module
// must write against — the engine interface's method signatures, the exported
// fields of the types those signatures carry, the registry Backend struct, and
// the conformance fixture — must have a public alias in this package.
// Without the alias an out-of-tree implementer cannot name the type, so a
// signature change that drags in a new internal type would silently re-lock
// the door this package exists to hold open. The check compares the reflected
// type closure against the alias declarations parsed from this package's
// source, so adding the method without the alias fails here, in-tree, at test
// time.
func TestPublicSurfaceComplete(t *testing.T) {
aliases := publicAliases(t)
need := map[string]reflect.Type{}
seen := map[reflect.Type]bool{}
roots := []reflect.Type{
reflect.TypeOf((*backend.DoltStorage)(nil)).Elem(),
reflect.TypeOf(backend.Backend{}),
reflect.TypeOf(conformance.Factory(nil)),
// The role tier's entry point reaches every role fixture through its
// factory fields, so all 25 of them join this guard: a contract that
// later grows a hook carrying a new internal type fails here rather
// than on an external backend's next version bump.
reflect.TypeOf(conformance.RoleContractBundle{}),
reflect.TypeOf(conformance.IssueOperationsStagingFixture{}),
}
for _, r := range roots {
walkType(r, seen, need)
}
keys := make([]string, 0, len(need))
for k := range need {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
if aliases[k] {
continue
}
name := k[strings.LastIndexByte(k, '.')+1:]
if !ast.IsExported(name) {
// An unexported internal type in an exported position cannot be
// aliased; it would be a contract bug in its own right.
t.Errorf("unexported internal type %s is reachable from the public backend contract", k)
continue
}
t.Errorf("internal type %s is reachable from the public backend contract but has no alias in package backend", k)
}
}
// publicAliases parses the non-test sources of this package and returns the
// set of alias targets, keyed "importpath.TypeName".
func publicAliases(t *testing.T) map[string]bool {
t.Helper()
_, thisFile, _, ok := runtime.Caller(0)
if !ok {
t.Fatal("runtime.Caller failed")
}
dir := bazeltest.CallerDir(thisFile, "backend")
fset := token.NewFileSet()
pkgs, err := parser.ParseDir(fset, dir, func(fi fs.FileInfo) bool {
return !strings.HasSuffix(fi.Name(), "_test.go")
}, 0)
if err != nil {
t.Fatalf("parsing package backend: %v", err)
}
aliases := map[string]bool{}
for _, pkg := range pkgs {
for _, file := range pkg.Files {
imports := map[string]string{}
for _, imp := range file.Imports {
path := strings.Trim(imp.Path.Value, `"`)
name := path[strings.LastIndexByte(path, '/')+1:]
if imp.Name != nil {
name = imp.Name.Name
}
imports[name] = path
}
for _, decl := range file.Decls {
gd, ok := decl.(*ast.GenDecl)
if !ok || gd.Tok != token.TYPE {
continue
}
for _, spec := range gd.Specs {
ts, ok := spec.(*ast.TypeSpec)
if !ok || !ts.Assign.IsValid() {
continue // not an alias declaration
}
rhs := ts.Type
// Generic alias: storage.Iter[T] parses as IndexExpr.
switch e := rhs.(type) {
case *ast.IndexExpr:
rhs = e.X
case *ast.IndexListExpr:
rhs = e.X
}
sel, ok := rhs.(*ast.SelectorExpr)
if !ok {
continue
}
pkgIdent, ok := sel.X.(*ast.Ident)
if !ok {
continue
}
if path, ok := imports[pkgIdent.Name]; ok {
aliases[path+"."+sel.Sel.Name] = true
}
}
}
}
}
if len(aliases) == 0 {
t.Fatal("no alias declarations found; parser wiring is broken")
}
return aliases
}
// walkType records every named type from an internal package reachable from
// t through pointers, containers, function signatures, interface methods, and
// EXPORTED struct fields (unexported fields are not part of the contract an
// implementer writes against).
func walkType(t reflect.Type, seen map[reflect.Type]bool, need map[string]reflect.Type) {
if t == nil || seen[t] {
return
}
seen[t] = true
if t.Name() != "" && strings.HasPrefix(t.PkgPath(), internalPrefix) {
base := t.Name()
if i := strings.IndexByte(base, '['); i >= 0 {
base = base[:i] // generic instantiation -> its base name
}
need[t.PkgPath()+"."+base] = t
}
switch t.Kind() {
case reflect.Pointer, reflect.Slice, reflect.Array, reflect.Chan:
walkType(t.Elem(), seen, need)
case reflect.Map:
walkType(t.Key(), seen, need)
walkType(t.Elem(), seen, need)
case reflect.Struct:
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
if f.PkgPath != "" {
continue // unexported field
}
walkType(f.Type, seen, need)
}
case reflect.Interface:
for i := 0; i < t.NumMethod(); i++ {
walkType(t.Method(i).Type, seen, need)
}
case reflect.Func:
for i := 0; i < t.NumIn(); i++ {
walkType(t.In(i), seen, need)
}
for i := 0; i < t.NumOut(); i++ {
walkType(t.Out(i), seen, need)
}
}
}
// TestAliasIdentity spot-checks that the exported surface is aliases, not
// copies: identical reflect types and errors.Is-compatible sentinels.
func TestAliasIdentity(t *testing.T) {
if got := reflect.TypeOf(backend.Issue{}).PkgPath(); !strings.HasPrefix(got, internalPrefix) {
t.Errorf("backend.Issue is not an alias of the internal type (PkgPath %q)", got)
}
var f conformance.Factory = func(*testing.T) backend.DoltStorage { return nil }
_ = f // a func literal typed against the public alias satisfies the suite's Factory
}