Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

fix: the module-wide census walks descend into a nested git worktree and report its copies as violations, and the new shared census home is package-scoped so they cannot be converted onto it (PIN-235)

Luigi Agosti0e9220dd9a3d
diff --git a/internal/bridge/ambient_globals_test.go b/internal/bridge/ambient_globals_test.go
index ffcde59b..4ea110f1 100644
--- a/internal/bridge/ambient_globals_test.go
+++ b/internal/bridge/ambient_globals_test.go
@@ -5,12 +5,11 @@ import (
"go/ast"
"go/parser"
"go/token"
- "io/fs"
- "os"
- "path/filepath"
"sort"
"strings"
"testing"
+
+ "github.com/pinchtab/pinchtab/internal/srccensus"
)
// An isolated-world node handle lives in the TOP frame's isolated context, so
@@ -72,29 +71,9 @@ const isolatedResolveWindow = 200
// going stale: a new producer under any name fails here, naming itself, instead of
// quietly removing its own callers from the census.
func TestIsolatedHandleProducersAreAllInScope(t *testing.T) {
- root, err := filepath.Abs("../..")
- if err != nil {
- t.Fatal(err)
- }
-
producers := 0
- walkErr := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
- if err != nil {
- return err
- }
- if d.IsDir() || !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") {
- return nil
- }
- rel, relErr := filepath.Rel(root, path)
- if relErr != nil {
- return relErr
- }
- name := filepath.ToSlash(rel)
- raw, err := os.ReadFile(path)
- if err != nil {
- return err
- }
- src := string(raw)
+ for _, file := range srccensus.Tree(t, "../..", moduleGoFileFloor) {
+ name, src := file.Name, file.Text
// Both spellings, from the one table the resolution census already owns. That
// census added the typed pairing precisely because a check knowing only the
@@ -118,20 +97,21 @@ func TestIsolatedHandleProducersAreAllInScope(t *testing.T) {
}
}
if !isolating {
- return nil
+ continue
}
producers++
+ inScope := false
for _, token := range isolatedHandleTokens {
if strings.Contains(src, token) {
- return nil
+ inScope = true
+ break
}
}
+ if inScope {
+ continue
+ }
t.Errorf("%s resolves a node with an executionContextId, so its handles are top-frame isolated, but it matches no entry in isolatedHandleTokens — the ambient-globals census cannot see it or its callers. Add the producer's exported name to isolatedHandleTokens.", name)
- return nil
- })
- if walkErr != nil {
- t.Fatal(walkErr)
}
if producers == 0 {
t.Fatal("no file resolves a node with an executionContextId — this check is verifying nothing")
@@ -483,34 +463,14 @@ func sortedKeys[V any](m map[string]V) []string {
}
func TestIsolatedHandleDeclarationsShadowAmbientGlobals(t *testing.T) {
- root, err := filepath.Abs("../..")
- if err != nil {
- t.Fatal(err)
- }
-
scope := censusScope{
exercised: map[string]int{},
canonicalOutOfScope: map[string]int{},
violations: map[string]bool{},
}
- walkErr := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
- if err != nil {
- return err
- }
- if d.IsDir() || !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") {
- return nil
- }
- rel, relErr := filepath.Rel(root, path)
- if relErr != nil {
- return relErr
- }
- name := filepath.ToSlash(rel)
- raw, err := os.ReadFile(path)
- if err != nil {
- return err
- }
- src := string(raw)
+ for _, file := range srccensus.Tree(t, "../..", moduleGoFileFloor) {
+ name, src := file.Name, file.Text
canonical := strings.Count(jsCode(src), canonicalViewLine)
inScope := false
@@ -527,7 +487,7 @@ func TestIsolatedHandleDeclarationsShadowAmbientGlobals(t *testing.T) {
if canonical > 0 {
scope.canonicalOutOfScope[name] = canonical
}
- return nil
+ continue
}
scope.scopedFiles++
scope.canonicalInScopedSrc += canonical
@@ -535,7 +495,7 @@ func TestIsolatedHandleDeclarationsShadowAmbientGlobals(t *testing.T) {
literals, parseErr := goRawLiterals(name, src)
if parseErr != nil {
t.Errorf("%s: parse: %v", name, parseErr)
- return nil
+ continue
}
for _, decl := range callFunctionDeclarations(literals) {
scope.checkedDecls++
@@ -564,10 +524,6 @@ func TestIsolatedHandleDeclarationsShadowAmbientGlobals(t *testing.T) {
strings.Join(formLines(forms), "\n "))
}
}
- return nil
- })
- if walkErr != nil {
- t.Fatal(walkErr)
}
t.Logf("census scope: %d files obtain isolated handles, %d callFunctionOn declarations scanned, ambient mentions %v, canonical preamble %d/%d in scope, %d out of scope",
diff --git a/internal/bridge/isolated_world_test.go b/internal/bridge/isolated_world_test.go
index 06be471c..e9a778ad 100644
--- a/internal/bridge/isolated_world_test.go
+++ b/internal/bridge/isolated_world_test.go
@@ -3,15 +3,13 @@ package bridge
import (
"context"
"encoding/base64"
- "io/fs"
- "os"
- "path/filepath"
"strings"
"testing"
"time"
"github.com/chromedp/chromedp"
"github.com/pinchtab/pinchtab/internal/selector"
+ "github.com/pinchtab/pinchtab/internal/srccensus"
"github.com/pinchtab/pinchtab/internal/testbrowser"
)
@@ -159,6 +157,11 @@ func TestIsolatedNodeObjectIDFailsClosedWithoutContext(t *testing.T) {
}
}
+// moduleGoFileFloor is the vacuity floor the module-wide censuses in this package pass to
+// srccensus.Tree. Set well under the real count so ordinary growth or deletion does not
+// touch it, but far above what a walk that lost the tree would return.
+const moduleGoFileFloor = 400
+
// mainWorldResolvers is the boundary as it actually stands, as data. These files
// still resolve a bare backend node id, so their Runtime.callFunctionOn work runs
// in the main world. They are the OPERATION paths — what is done to a node once
@@ -196,31 +199,12 @@ var resolveNodeSpellings = []struct{ call, isolated string }{
}
func TestIsolatedWorldBoundaryCensus(t *testing.T) {
- root, err := filepath.Abs("../..")
- if err != nil {
- t.Fatal(err)
- }
-
found := map[string]bool{}
checked := map[string]int{}
- walkErr := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
- if err != nil {
- return err
- }
- if d.IsDir() || !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") {
- return nil
- }
- rel, relErr := filepath.Rel(root, path)
- if relErr != nil {
- return relErr
- }
- name := filepath.ToSlash(rel)
- raw, err := os.ReadFile(path)
- if err != nil {
- return err
- }
+ for _, file := range srccensus.Tree(t, "../..", moduleGoFileFloor) {
+ name := file.Name
for _, spelling := range resolveNodeSpellings {
- for _, block := range strings.Split(string(raw), spelling.call)[1:] {
+ for _, block := range strings.Split(file.Text, spelling.call)[1:] {
checked[spelling.call]++
head := block
if len(head) > 200 {
@@ -235,10 +219,6 @@ func TestIsolatedWorldBoundaryCensus(t *testing.T) {
}
}
}
- return nil
- })
- if walkErr != nil {
- t.Fatal(walkErr)
}
// Per spelling, not in total: one spelling falling to zero sites is how a
// whole class of call site stops being scanned while the census stays green.
diff --git a/internal/srccensus/srccensus.go b/internal/srccensus/srccensus.go
index 925653c6..dd596cbf 100644
--- a/internal/srccensus/srccensus.go
+++ b/internal/srccensus/srccensus.go
@@ -11,7 +11,9 @@
// recur. Shared here, so they cannot be forgotten:
//
// 1. SCOPE IS DERIVED, NEVER HAND-LISTED. Load enumerates a package's non-test sources
-// rather than naming files, and the finders return EVERY match rather than the first.
+// and Tree a whole subtree's, rather than naming files, and the finders return EVERY
+// match rather than the first. Tree also owns the walk EXCLUSIONS, so a module-wide
+// guard inherits them instead of each author remembering them.
// Every silent narrowing found in this repo came from a hand-listed scope — a pair of
// filenames, the first match per file, a literal list of the very constants whose
// addition the guard policed. The rule was right in all three; the scope covered less
@@ -43,7 +45,10 @@ import (
"go/ast"
"go/parser"
"go/token"
+ "io/fs"
+ "os"
"path/filepath"
+ "sort"
"strings"
"testing"
)
@@ -98,6 +103,89 @@ func Load(t testing.TB, dir string, minFiles int) *Package {
return pkg
}
+// SourceFile is one non-test Go source found by a recursive walk, named the way a
+// module-wide rule table is keyed: module-relative and slash-separated, so an exemption
+// entry written on one machine matches on every other.
+type SourceFile struct {
+ Name string
+ Path string
+ Text string
+}
+
+// treeSkipDirs are excluded by NAME because they hold no module source: dependency and
+// build output trees. A nested checkout is caught by nestedCheckout instead, since its
+// directory name is arbitrary.
+var treeSkipDirs = map[string]bool{".git": true, "node_modules": true, "dist": true, "vendor": true}
+
+// Tree enumerates every non-test .go file under root for a census whose rule is
+// module-wide rather than package-scoped, and it exists so the EXCLUSIONS are inherited
+// rather than remembered. minFiles is the vacuity floor, same contract as Load.
+//
+// A directory holding a .git entry is skipped, root excepted. That is the rule rather
+// than a name list because the hazard it closes is a git worktree created inside the repo
+// — routine when copying a diff somewhere safe to mutate — whose directory name is
+// arbitrary. Its copies are walked as module source, and since keys are module-relative,
+// a nested copy of an exempt file cannot match the exemption and is reported as a
+// violation; a census keyed on counts instead silently doubles them. Either way the
+// remedy the failure suggests is a duplicate entry for a path that vanishes with the
+// worktree, so the guard's own advice makes the tree worse.
+//
+// The .git entry must be matched as EITHER kind: a nested clone carries a .git directory,
+// a nested worktree carries a .git FILE. A check written as d.IsDir() && name == ".git"
+// misses the worktree, which is the case that actually occurs.
+func Tree(t testing.TB, root string, minFiles int) []SourceFile {
+ t.Helper()
+
+ abs, err := filepath.Abs(root)
+ if err != nil {
+ t.Fatalf("cannot resolve %s, so this census would check nothing: %v", root, err)
+ }
+
+ var files []SourceFile
+ walkErr := filepath.WalkDir(abs, func(path string, entry fs.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+ if entry.IsDir() {
+ if path == abs {
+ return nil
+ }
+ if treeSkipDirs[entry.Name()] || nestedCheckout(path) {
+ return fs.SkipDir
+ }
+ return nil
+ }
+ if !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") {
+ return nil
+ }
+ rel, relErr := filepath.Rel(abs, path)
+ if relErr != nil {
+ return relErr
+ }
+ raw, readErr := os.ReadFile(path)
+ if readErr != nil {
+ return readErr
+ }
+ files = append(files, SourceFile{Name: filepath.ToSlash(rel), Path: path, Text: string(raw)})
+ return nil
+ })
+ if walkErr != nil {
+ t.Fatalf("cannot walk %s, so this census would check nothing: %v", abs, walkErr)
+ }
+ if len(files) < minFiles {
+ t.Fatalf("walked %d non-test files under %s, want at least %d; the census matched almost nothing and would pass vacuously", len(files), abs, minFiles)
+ }
+ sort.Slice(files, func(i, j int) bool { return files[i].Name < files[j].Name })
+ return files
+}
+
+// nestedCheckout reports whether dir is the root of its own checkout, by the presence of a
+// .git entry of either kind. See Tree for why the kind matters.
+func nestedCheckout(dir string) bool {
+ _, err := os.Lstat(filepath.Join(dir, ".git"))
+ return err == nil
+}
+
// Files reports the base names parsed, for a guard that needs to name one.
func (p *Package) Files() []string {
names := make([]string, 0, len(p.files))
diff --git a/internal/srccensus/srccensus_test.go b/internal/srccensus/srccensus_test.go
index cb2e3d06..840b327d 100644
--- a/internal/srccensus/srccensus_test.go
+++ b/internal/srccensus/srccensus_test.go
@@ -237,3 +237,157 @@ func f(cfg *C, other *C) {
t.Errorf("found %d Port assignments, want 1", len(got))
}
}
+
+// writeTree lays out files at paths relative to one root, creating parent directories, so
+// a walk test can describe a whole shape in one literal.
+func writeTree(t *testing.T, files map[string]string) string {
+ t.Helper()
+
+ root := t.TempDir()
+ for rel, body := range files {
+ path := filepath.Join(root, filepath.FromSlash(rel))
+ if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ return root
+}
+
+func treeNames(files []SourceFile) []string {
+ names := make([]string, 0, len(files))
+ for _, file := range files {
+ names = append(names, file.Name)
+ }
+ return names
+}
+
+// The hazard this closes: a git worktree created INSIDE the repo — routine when copying a
+// diff somewhere safe to mutate — is otherwise walked as module source. Its .git is a FILE,
+// not a directory, so the obvious `IsDir() && name == ".git"` check misses exactly the case
+// that occurs; and the nested directory's name is arbitrary, so no name list catches it.
+func TestTreeSkipsANestedCheckoutWhicheverKindOfGitEntryItHas(t *testing.T) {
+ // dir and gitEntry are separate because deriving the nested root from the .git path
+ // puts the clone's sources INSIDE .git, where the name skip excludes them and the
+ // subtest passes without ever testing a nested clone.
+ for _, tc := range []struct {
+ name string
+ dir string
+ gitEntry string
+ body string
+ }{
+ {name: "worktree carries a .git file", dir: "scratch-7f3a", gitEntry: ".git", body: "gitdir: /elsewhere/.git/worktrees/scratch\n"},
+ {name: "clone carries a .git directory", dir: "vendored-copy", gitEntry: ".git/HEAD", body: "ref: refs/heads/main\n"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ root := writeTree(t, map[string]string{
+ "real.go": "package a\n",
+ "pkg/deep.go": "package b\n",
+ tc.dir + "/" + tc.gitEntry: tc.body,
+ tc.dir + "/copy.go": "package a\n",
+ tc.dir + "/pkg/sub.go": "package b\n",
+ })
+
+ // The nested sources must exist where the walk would find them, or this
+ // subtest cannot distinguish an exclusion from a fixture that planted nothing.
+ for _, rel := range []string{tc.dir + "/copy.go", tc.dir + "/pkg/sub.go"} {
+ if _, err := os.Stat(filepath.Join(root, filepath.FromSlash(rel))); err != nil {
+ t.Fatalf("fixture did not plant %s, so the exclusion would pass vacuously: %v", rel, err)
+ }
+ }
+
+ got := treeNames(Tree(t, root, 2))
+
+ want := []string{"pkg/deep.go", "real.go"}
+ if strings.Join(got, ",") != strings.Join(want, ",") {
+ t.Errorf("Tree = %v, want %v; a nested checkout's copies are walked as module source, and since rule tables are keyed module-relative, a copy of an exempt file cannot match its exemption", got, want)
+ }
+ })
+ }
+}
+
+// The root itself holds a .git entry, so the skip cannot be unconditional or a census run
+// from a real checkout enumerates nothing.
+func TestTreeStillWalksARootThatIsItselfACheckout(t *testing.T) {
+ root := writeTree(t, map[string]string{
+ ".git/HEAD": "ref: refs/heads/main\n",
+ "real.go": "package a\n",
+ "pkg/one.go": "package b\n",
+ })
+
+ if got := treeNames(Tree(t, root, 2)); len(got) != 2 {
+ t.Errorf("Tree = %v, want both files; the root's own .git must not exclude the module", got)
+ }
+}
+
+func TestTreeSkipsDependencyAndBuildTreesByName(t *testing.T) {
+ root := writeTree(t, map[string]string{
+ "real.go": "package a\n",
+ "pkg/one.go": "package b\n",
+ "node_modules/dep.go": "package c\n",
+ "dist/built.go": "package d\n",
+ "vendor/vendored.go": "package e\n",
+ "dist/nested/deeper.go": "package f\n",
+ })
+
+ got := treeNames(Tree(t, root, 2))
+
+ want := []string{"pkg/one.go", "real.go"}
+ if strings.Join(got, ",") != strings.Join(want, ",") {
+ t.Errorf("Tree = %v, want %v", got, want)
+ }
+}
+
+func TestTreeExcludesTestFilesAndNonGoFiles(t *testing.T) {
+ root := writeTree(t, map[string]string{
+ "real.go": "package a\n",
+ "pkg/one.go": "package b\n",
+ "real_test.go": "package a\n",
+ "notes.md": "# no\n",
+ "pkg/two.json": "{}\n",
+ })
+
+ got := treeNames(Tree(t, root, 2))
+
+ want := []string{"pkg/one.go", "real.go"}
+ if strings.Join(got, ",") != strings.Join(want, ",") {
+ t.Errorf("Tree = %v, want %v", got, want)
+ }
+}
+
+// Tree carries Load's vacuity floor for the same reason: a walk that lost most of the tree
+// — an exclusion widened by mistake, a root pointed one level too deep — must fail rather
+// than report a clean census over almost nothing.
+func TestTreeFailsBelowItsFileFloor(t *testing.T) {
+ root := writeTree(t, map[string]string{"only.go": "package a\n"})
+
+ got := mustFatal(t, func(tb testing.TB) { Tree(tb, root, 5) })
+
+ for _, want := range []string{"walked 1 non-test files", "want at least 5", "pass vacuously"} {
+ if !strings.Contains(got, want) {
+ t.Errorf("Fatalf = %q, want it to mention %q", got, want)
+ }
+ }
+}
+
+// The file contents are what every module-wide census actually reads, so a walk returning
+// names with empty bodies would let each one silently match nothing.
+func TestTreeCarriesEachFilesTextAndAModuleRelativeName(t *testing.T) {
+ root := writeTree(t, map[string]string{
+ "a.go": "package a\n// marker-alpha\n",
+ "nested/pkg/b.go": "package b\n// marker-beta\n",
+ })
+
+ files := Tree(t, root, 2)
+ if len(files) != 2 {
+ t.Fatalf("Tree returned %d files, want 2", len(files))
+ }
+ if files[0].Name != "a.go" || !strings.Contains(files[0].Text, "marker-alpha") {
+ t.Errorf("first file = %+v, want a.go carrying its text", files[0])
+ }
+ if files[1].Name != "nested/pkg/b.go" || !strings.Contains(files[1].Text, "marker-beta") {
+ t.Errorf("second file = %+v, want a slash-separated relative name and its text", files[1])
+ }
+}