Skip to content

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

refactor: two directory-scoped censuses guard the no-overwrite rule, so an auto-naming site in any third package is invisible to both (PIN-168)

Luigi Agostibe8c9de4ee82
diff --git a/internal/cli/actions/output_file_test.go b/internal/cli/actions/output_file_test.go
index 89ef4001..83c59872 100644
--- a/internal/cli/actions/output_file_test.go
+++ b/internal/cli/actions/output_file_test.go
@@ -148,55 +148,10 @@ func TestAnExplicitOutputPathStillOverwrites(t *testing.T) {
}
}
-// The census: every auto-naming site in this package must reach the exclusive create.
-// A survivor is either a caller-supplied path or named here as deliberate, so a sixth
-// site cannot land silently the way these five did.
-func TestNoCLIActionAutoNamesAFileItThenOverwrites(t *testing.T) {
- entries, err := os.ReadDir(".")
- if err != nil {
- t.Fatal(err)
- }
-
- // file -> the call that reserves the name it builds.
- accounted := map[string]string{
- "actions_capture.go": "writeOutputFile with autoNamed",
- "actions_pdf.go": "writeOutputFile with autoNamed",
- "actions_screenshot.go": "writeOutputFile with autoNamed",
- "actions_record.go": "fileout.ReservePath before the rename",
- }
-
- var scanned, withTimestamp int
- for _, entry := range entries {
- name := entry.Name()
- if entry.IsDir() || !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {
- continue
- }
- body, err := os.ReadFile(name) // #nosec G304 -- files listed from this package's own directory.
- if err != nil {
- t.Fatal(err)
- }
- scanned++
- if !strings.Contains(string(body), "150405") {
- continue
- }
- withTimestamp++
- if accounted[name] == "" {
- t.Errorf("%s builds a name from a second-resolution timestamp and is not accounted for; route it through writeOutputFile or fileout, or record why it cannot collide", name)
- }
- }
-
- if scanned < len(accounted) {
- t.Fatalf("scanned %d files in this package; this census would pass vacuously", scanned)
- }
- if withTimestamp != len(accounted) {
- t.Errorf("found %d auto-naming files but %d are accounted for; a stale entry hides a site that no longer reserves", withTimestamp, len(accounted))
- }
- for name := range accounted {
- if _, err := os.Stat(name); err != nil {
- t.Errorf("accounted file %s no longer exists; the census is guarding nothing", name)
- }
- }
-}
+// The module-wide census for this rule lives in internal/fileout
+// (TestNoPackageAutoNamesAFileItThenOverwrites): one accounted map for the whole module,
+// so a site in a package neither of the two old directory-scoped censuses read cannot
+// land unseen.
// printedName pulls the output filename out of whatever sentence a site wraps it in —
// each of the four phrases it differently, and the assertion is about the name.
diff --git a/internal/fileout/autonaming_census_test.go b/internal/fileout/autonaming_census_test.go
new file mode 100644
index 00000000..a1922770
--- /dev/null
+++ b/internal/fileout/autonaming_census_test.go
@@ -0,0 +1,164 @@
+package fileout
+
+import (
+ "io/fs"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+// This census lives beside the rule it defends, and it walks the MODULE. Two
+// directory-scoped censuses stood here before — one in internal/handlers, one in
+// internal/cli/actions — each reading os.ReadDir(".") with its own accounted map. Between
+// them they covered the two packages that had the defect and nothing else, so the next
+// auto-naming site, in any third package, would have shipped unseen. Walking from the
+// module root is the same fix the isolated-world boundary census in internal/bridge got
+// after the same blind spot.
+//
+// Not built on internal/srccensus deliberately: that helper reads ONE package's AST for
+// calls and assignments, and this rule is a literal scan across every package.
+
+// timestampLayouts are the second-resolution spellings this census recognises. A stamp is
+// what makes two outputs in the same second collide, so the layout is the signal.
+//
+// STATED BLIND SPOT, because a census that reads as module-wide while checking one
+// spelling is worse than one whose limits are written down: colon-bearing layouts
+// (15:04:05) and named constants (time.RFC3339, time.DateTime) are NOT scanned. Colons
+// are illegal in Windows filenames and vanishingly rare in output names, and the named
+// constants are overwhelmingly used to format timestamps for display, where they would
+// produce noise on every log line. A filename built from either is an unguarded site.
+var timestampLayouts = []string{"150405", "15-04-05", "15_04_05", "15.04.05"}
+
+// autoNamingSites maps a MODULE-RELATIVE path to why its timestamp cannot destroy an
+// earlier output. Package-qualified, so one map serves the whole module and a reader can
+// see which package each decision belongs to. Every entry is a boundary decision, which
+// is why each carries its reason rather than just a path.
+var autoNamingSites = map[string]string{
+ "internal/handlers/binary_export.go": "exportTimestamp only builds the base name; fileout reserves the path",
+ "internal/handlers/record_handlers.go": "the recording base name is reserved by " +
+ "fileout.ReserveUnique before it is returned",
+ "internal/cli/actions/actions_capture.go": "writeOutputFile with autoNamed",
+ "internal/cli/actions/actions_pdf.go": "writeOutputFile with autoNamed",
+ "internal/cli/actions/actions_screenshot.go": "writeOutputFile with autoNamed",
+ "internal/cli/actions/actions_record.go": "fileout.ReservePath before the rename",
+
+ // The two developer-tool artefact writers, accounted DELIBERATELY rather than fixed.
+ // They are benchmark outputs a human runs one at a time, their paths are also
+ // caller-specifiable, and comparison scripts glob for the exact names — so routing
+ // them through fileout would start appending -1 suffixes to filenames those scripts
+ // expect. Losing one benchmark CSV to a same-second collision is artefact loss in a
+ // tool someone is watching, which is not the same severity as a server destroying a
+ // capture it just reported to a caller. Changing that is its own card.
+ "tests/tools/runner/internal/bench/browserbench.go": "developer benchmark artefact; path is caller-specifiable and globbed by comparison scripts",
+ "tests/tools/runner/internal/bench/setup.go": "developer benchmark artefact; path is caller-specifiable and globbed by comparison scripts",
+
+ // These two do not name a file at all — the stamp is a value INSIDE the output. They
+ // are listed because the scan cannot tell a filename from a field, and saying so is
+ // the point of carrying reasons.
+ "tests/tools/runner/internal/stealth/compare.go": "the stamp is a run id printed inside a markdown report, not a filename",
+ "tests/tools/runner/internal/opt/mergereports.go": "the stamp is a JSON field value in the merged report, not a filename",
+}
+
+// The census fails BOTH ways. An unaccounted site reds, so a new one cannot land quietly;
+// and an accounted entry whose stamp is gone reds too, so the recorded boundary cannot
+// drift from the real one — a stale entry is how a site that stopped reserving hides.
+func TestNoPackageAutoNamesAFileItThenOverwrites(t *testing.T) {
+ root := moduleRoot(t)
+
+ found := map[string]bool{}
+ scanned := 0
+ err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+ if d.IsDir() {
+ if skipCensusDir(d.Name()) && path != root {
+ return fs.SkipDir
+ }
+ return nil
+ }
+ name := d.Name()
+ if !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {
+ return nil
+ }
+ body, readErr := os.ReadFile(path) // #nosec G304 -- files walked from this repo's own tree.
+ if readErr != nil {
+ return readErr
+ }
+ scanned++
+ if !buildsASecondResolutionStamp(string(body)) {
+ return nil
+ }
+ rel, relErr := filepath.Rel(root, path)
+ if relErr != nil {
+ return relErr
+ }
+ found[filepath.ToSlash(rel)] = true
+ return nil
+ })
+ if err != nil {
+ t.Fatalf("cannot walk the module, so this census checks nothing: %v", err)
+ }
+
+ if scanned < 200 {
+ t.Fatalf("scanned only %d non-test Go files under %s; the walk is not reaching the module, so this census would pass vacuously", scanned, root)
+ }
+ if len(found) == 0 {
+ t.Fatalf("found no file building a second-resolution timestamp anywhere in the module; either every auto-named output is gone or the layouts this census recognises (%s) no longer appear — re-point it at whatever replaced them rather than deleting it",
+ strings.Join(timestampLayouts, ", "))
+ }
+
+ for path := range found {
+ if autoNamingSites[path] == "" {
+ t.Errorf("%s builds a name from a second-resolution timestamp and is not accounted for; route it through fileout (WriteUnique, WriteUniquePath, ReserveUnique or ReservePath) or add it to autoNamingSites with the reason it cannot collide.\n\tRecognised layouts: %s",
+ path, strings.Join(timestampLayouts, ", "))
+ }
+ }
+ for path, reason := range autoNamingSites {
+ if reason == "" {
+ t.Errorf("%s is accounted for with no reason; every entry records a boundary decision", path)
+ }
+ if !found[path] {
+ t.Errorf("%s is accounted for but the walk found no second-resolution timestamp in it; the file moved, was renamed, or stopped building a timestamped name — drop or re-point its entry so the census keeps meaning what it says", path)
+ }
+ }
+}
+
+func buildsASecondResolutionStamp(body string) bool {
+ for _, layout := range timestampLayouts {
+ if strings.Contains(body, layout) {
+ return true
+ }
+ }
+ return false
+}
+
+func skipCensusDir(name string) bool {
+ switch name {
+ case ".git", "node_modules", "dist", "vendor", ".tools", "testdata":
+ return true
+ }
+ return false
+}
+
+// moduleRoot walks up to the directory holding go.mod rather than counting "../" hops, so
+// moving this package does not silently point the census at a subtree.
+func moduleRoot(t *testing.T) string {
+ t.Helper()
+
+ dir, err := os.Getwd()
+ if err != nil {
+ t.Fatal(err)
+ }
+ for {
+ if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil {
+ return dir
+ }
+ parent := filepath.Dir(dir)
+ if parent == dir {
+ t.Fatal("no go.mod found above the working directory; cannot locate the module root")
+ }
+ dir = parent
+ }
+}
diff --git a/internal/handlers/binary_export_test.go b/internal/handlers/binary_export_test.go
index 43e26a5e..222e4d99 100644
--- a/internal/handlers/binary_export_test.go
+++ b/internal/handlers/binary_export_test.go
@@ -292,49 +292,7 @@ func TestARefusedRecordStopLeavesNoReservedFile(t *testing.T) {
}
}
-// The census the card asks a reviewer to run. Every auto-naming site in internal/handlers
-// must reach an exclusive create; a survivor is either a caller-supplied path or is named
-// here as deliberate, so a new one cannot land silently.
-func TestNoHandlerAutoNamesAFileItThenOverwrites(t *testing.T) {
- entries, err := os.ReadDir(".")
- if err != nil {
- t.Fatal(err)
- }
-
- // file -> why its timestamp is not an overwrite risk.
- accounted := map[string]string{
- "binary_export.go": "exportTimestamp only builds the base name; createUniqueFile reserves the path",
- "record_handlers.go": "the recording base name is reserved by fileout.ReserveUnique before it is returned",
- }
-
- var scanned int
- for _, entry := range entries {
- name := entry.Name()
- if entry.IsDir() || !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {
- continue
- }
- body, err := os.ReadFile(name) // #nosec G304 -- files listed from this package's own directory.
- if err != nil {
- t.Fatal(err)
- }
- scanned++
- if !strings.Contains(string(body), "150405") {
- continue
- }
- if accounted[name] == "" {
- t.Errorf("%s builds a name from a second-resolution timestamp and is not accounted for; route it through fileout (WriteUnique or ReserveUnique) or record why it cannot collide", name)
- }
- }
- if scanned < 2 {
- t.Fatalf("scanned %d handler files; this census would pass vacuously", scanned)
- }
- for name := range accounted {
- body, err := os.ReadFile(name) // #nosec G304 -- fixed list in this package.
- if err != nil {
- t.Fatalf("%s is accounted for but unreadable: %v", name, err)
- }
- if !strings.Contains(string(body), "150405") {
- t.Errorf("%s no longer builds a timestamped name; drop its entry from this census", name)
- }
- }
-}
+// The module-wide census for this rule lives in internal/fileout
+// (TestNoPackageAutoNamesAFileItThenOverwrites), beside the owner it defends. The
+// package-scoped version that stood here could not see an auto-naming site in any third
+// package, which is the coverage the consolidation buys.