High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
refactor: the autoSolver defaults exist in three hand-maintained copies that already disagree (PIN-094)
Luigi Agosti91488228d209
diff --git a/internal/autosolver/autosolver.go b/internal/autosolver/autosolver.goindex 8f408838..2a19fd1f 100644--- a/internal/autosolver/autosolver.go+++ b/internal/autosolver/autosolver.go@@ -124,7 +124,7 @@ func (as *AutoSolver) Solve(ctx context.Context, page Page, executor ActionExecusolved, entry = as.tryLLM(ctx, page, executor, result.History)appendAttempt(result, entry)if solved {- return as.finalizeSuccess(result, page, "llm", start), nil+ return as.finalizeSuccess(result, page, llmFallbackSolverLabel, start), nil}}}@@ -745,9 +745,17 @@ func resolveSelectorCenter(ctx context.Context, executor ActionExecutor, selectoreturn coords.X, coords.Y, nil}+// llmFallbackSolverLabel names the LLM fallback stage in an AttemptEntry and in the+// success result. It is deliberately NOT one of the solver-name constants beside+// SemanticSolverName: those are config-selectable — catalog collects them, so config+// validation accepts them in autoSolver.solvers — while this is only an attempt-entry+// label. Moving it into that group would invite adding it to the catalog, at which+// point autoSolver.solvers: ["llm"] would validate and then match no solver at all.+const llmFallbackSolverLabel = "llm"+func (as *AutoSolver) tryLLM(ctx context.Context, page Page, executor ActionExecutor, history []AttemptEntry) (bool, *AttemptEntry) {llmStart := time.Now()- entry := &AttemptEntry{Solver: "llm"}+ entry := &AttemptEntry{Solver: llmFallbackSolverLabel}html, err := page.HTML()if err != nil {diff --git a/internal/autosolver/solvers/cloudflare.go b/internal/autosolver/solvers/cloudflare.goindex e0d777f0..3da5a853 100644--- a/internal/autosolver/solvers/cloudflare.go+++ b/internal/autosolver/solvers/cloudflare.go@@ -19,7 +19,7 @@ import (// zero dependency on chromedp.type Cloudflare struct{}-func (s *Cloudflare) Name() string { return "cloudflare" }+func (s *Cloudflare) Name() string { return autosolver.CloudflareSolverName }func (s *Cloudflare) Priority() int { return 10 }// CanHandle checks for Cloudflare challenge indicators in the page title.diff --git a/internal/autosolver/types.go b/internal/autosolver/types.goindex 4723dc7f..81eb57b0 100644--- a/internal/autosolver/types.go+++ b/internal/autosolver/types.go@@ -8,6 +8,13 @@ import "time"// among the names autoSolver.solvers accepts.const SemanticSolverName = "semantic"+// CloudflareSolverName is the registry name solvers.Cloudflare answers to. It+// lives beside SemanticSolverName because both are CONFIG-SELECTABLE: catalog+// collects them, so both are legal values of autoSolver.solvers. The LLM+// fallback's "llm" label is deliberately not in this group — see+// llmFallbackSolverLabel.+const CloudflareSolverName = "cloudflare"+// IntentType classifies the detected page state.type IntentType string@@ -160,13 +167,17 @@ type Config struct {Credentials Credentials `json:"-"` // Never serialised: redacted secrets}-// DefaultConfig returns a Config with sensible defaults.+// DefaultConfig returns a Config with sensible defaults. Enabled is false to match+// the config default: normalizedAutoSolverConfig overwrites Enabled unconditionally,+// so the only path where this value is observable is its h.Config == nil early+// return, and a core default of true would silently enable solving on the one+// configuration-free path while every configured path leaves it off.func DefaultConfig() Config {return Config{- Enabled: true,+ Enabled: false,MaxAttempts: 8,SolverTimeout: 30 * time.Second,- Solvers: []string{"cloudflare", SemanticSolverName},+ Solvers: []string{CloudflareSolverName, SemanticSolverName},LLMFallback: false,RetryBaseDelay: 500 * time.Millisecond,RetryMaxDelay: 10 * time.Second,diff --git a/internal/config/config_default_test.go b/internal/config/config_default_test.gonew file mode 100644index 00000000..b8832ed5--- /dev/null+++ b/internal/config/config_default_test.go@@ -0,0 +1,246 @@+package config++import (+ "os"+ "path/filepath"+ "reflect"+ "strings"+ "testing"+ "time"++ "github.com/pinchtab/pinchtab/internal/autosolver"+)++// This file guards the single-ownership of the autoSolver defaults. They used to be+// written out three times — RuntimeConfig, DefaultFileConfig and the core's+// DefaultConfig — with no test comparing them, and they had already drifted on+// Enabled. Do not "simplify" the census below into comparing two structs that happen+// to be the same type: the three copies use different types and different units, and+// the point is that every field is reached, so a newly added autoSolver default cannot+// land unguarded.++// autoSolverDefaultRow declares one field's default once, as data, and how to read it+// out of each of the three representations. want is the recorded baseline, so editing+// the shared owner reddens every row rather than passing silently.+type autoSolverDefaultRow struct {+ field string+ want any+ runtime func(AutoSolverConfig) any+ file func(AutoSolverFileConfig) any+ // core reads the same value out of autosolver.Config, converting units. nil for+ // the fields the core has no counterpart for.+ core func(autosolver.Config) any+}++var autoSolverDefaultRows = []autoSolverDefaultRow{+ {+ field: "Enabled",+ want: false,+ runtime: func(c AutoSolverConfig) any { return c.Enabled },+ file: func(c AutoSolverFileConfig) any { return derefBool(c.Enabled) },+ core: func(c autosolver.Config) any { return c.Enabled },+ },+ {+ field: "AutoTrigger",+ want: true,+ runtime: func(c AutoSolverConfig) any { return c.AutoTrigger },+ file: func(c AutoSolverFileConfig) any { return derefBool(c.AutoTrigger) },+ },+ {+ field: "TriggerOnNavigate",+ want: true,+ runtime: func(c AutoSolverConfig) any { return c.TriggerOnNavigate },+ file: func(c AutoSolverFileConfig) any { return derefBool(c.TriggerOnNavigate) },+ },+ {+ field: "TriggerOnAction",+ want: true,+ runtime: func(c AutoSolverConfig) any { return c.TriggerOnAction },+ file: func(c AutoSolverFileConfig) any { return derefBool(c.TriggerOnAction) },+ },+ {+ field: "MaxAttempts",+ want: 8,+ runtime: func(c AutoSolverConfig) any { return c.MaxAttempts },+ file: func(c AutoSolverFileConfig) any { return derefInt(c.MaxAttempts) },+ core: func(c autosolver.Config) any { return c.MaxAttempts },+ },+ {+ field: "SolverTimeoutSec",+ want: 30,+ runtime: func(c AutoSolverConfig) any { return c.SolverTimeoutSec },+ file: func(c AutoSolverFileConfig) any { return derefInt(c.SolverTimeoutSec) },+ core: func(c autosolver.Config) any { return int(c.SolverTimeout / time.Second) },+ },+ {+ field: "RetryBaseDelayMs",+ want: 500,+ runtime: func(c AutoSolverConfig) any { return c.RetryBaseDelayMs },+ file: func(c AutoSolverFileConfig) any { return derefInt(c.RetryBaseDelayMs) },+ core: func(c autosolver.Config) any { return int(c.RetryBaseDelay / time.Millisecond) },+ },+ {+ field: "RetryMaxDelayMs",+ want: 10000,+ runtime: func(c AutoSolverConfig) any { return c.RetryMaxDelayMs },+ file: func(c AutoSolverFileConfig) any { return derefInt(c.RetryMaxDelayMs) },+ core: func(c autosolver.Config) any { return int(c.RetryMaxDelay / time.Millisecond) },+ },+ {+ field: "Solvers",+ want: []string{autosolver.CloudflareSolverName, autosolver.SemanticSolverName},+ runtime: func(c AutoSolverConfig) any { return c.Solvers },+ file: func(c AutoSolverFileConfig) any { return c.Solvers },+ core: func(c autosolver.Config) any { return c.Solvers },+ },+ {+ field: "LLMFallback",+ want: false,+ runtime: func(c AutoSolverConfig) any { return c.LLMFallback },+ file: func(c AutoSolverFileConfig) any { return derefBool(c.LLMFallback) },+ core: func(c autosolver.Config) any { return c.LLMFallback },+ },+}++// autoSolverFieldsWithoutDefault are the AutoSolverConfig fields the defaults+// deliberately leave zero, each with the reason. They are listed rather than skipped+// so the census reaches every field.+var autoSolverFieldsWithoutDefault = map[string]string{+ "LLMProvider": "no provider is chosen for the operator; an empty value means the LLM fallback stays unconfigured",+ "CapsolverKey": "an external solver API key; a default would be a fabricated credential",+ "TwoCaptchaKey": "an external solver API key; a default would be a fabricated credential",+ "Credentials": "user-supplied login/signup/form values; never defaulted",+}++func derefBool(p *bool) any {+ if p == nil {+ return "<nil>"+ }+ return *p+}++func derefInt(p *int) any {+ if p == nil {+ return "<nil>"+ }+ return *p+}++// runtimeAutoSolverDefaults loads the config with a file that sets nothing in the+// autoSolver section, so the values read back are the ones LoadConfig assigns rather+// than a re-derivation of them in the test.+func runtimeAutoSolverDefaults(t *testing.T) AutoSolverConfig {+ t.Helper()+ clearConfigEnvVars(t)+ cfgPath := filepath.Join(t.TempDir(), "config.json")+ if err := os.WriteFile(cfgPath, []byte(`{"server":{"port":"9867"}}`), 0o644); err != nil {+ t.Fatal(err)+ }+ t.Setenv("PINCHTAB_CONFIG", cfgPath)+ return Load().AutoSolver+}++func TestAutoSolverDefaultsAgreeAcrossEveryCopy(t *testing.T) {+ runtime := runtimeAutoSolverDefaults(t)+ file := DefaultFileConfig().AutoSolver+ core := autosolver.DefaultConfig()++ for _, row := range autoSolverDefaultRows {+ t.Run(row.field, func(t *testing.T) {+ if got := row.runtime(runtime); !reflect.DeepEqual(got, row.want) {+ t.Errorf("RuntimeConfig default = %v, want %v", got, row.want)+ }+ if got := row.file(file); !reflect.DeepEqual(got, row.want) {+ t.Errorf("DefaultFileConfig default = %v, want %v", got, row.want)+ }+ if row.core == nil {+ return+ }+ if got := row.core(core); !reflect.DeepEqual(got, row.want) {+ t.Errorf("autosolver.DefaultConfig default = %v, want %v", got, row.want)+ }+ })+ }+}++// The census: every AutoSolverConfig field is either compared above or listed as+// deliberately undefaulted. A field in neither table fails by name, which is what+// stops a newly added default from being silently unguarded.+func TestEveryAutoSolverFieldIsAccountedFor(t *testing.T) {+ compared := make(map[string]bool, len(autoSolverDefaultRows))+ for _, row := range autoSolverDefaultRows {+ compared[row.field] = true+ }++ runtime := runtimeAutoSolverDefaults(t)+ typ := reflect.TypeOf(AutoSolverConfig{})+ value := reflect.ValueOf(runtime)+ if typ.NumField() == 0 {+ t.Fatal("AutoSolverConfig has no fields — this census would pass vacuously")+ }++ for i := 0; i < typ.NumField(); i++ {+ name := typ.Field(i).Name+ switch {+ case compared[name]:+ delete(compared, name)+ case autoSolverFieldsWithoutDefault[name] != "":+ if !value.Field(i).IsZero() {+ t.Errorf("%s is listed as having no default (%s) but the loaded default is %v",+ name, autoSolverFieldsWithoutDefault[name], value.Field(i).Interface())+ }+ default:+ t.Errorf("AutoSolverConfig.%s is in neither autoSolverDefaultRows nor autoSolverFieldsWithoutDefault; add it to one", name)+ }+ }++ for name := range compared {+ t.Errorf("autoSolverDefaultRows names %q, which is not a field of AutoSolverConfig", name)+ }+}++// The core's Enabled default used to be true while both config copies said false.+// normalizedAutoSolverConfig overwrites Enabled unconditionally, so the divergence was+// observable only on its h.Config == nil early return — the one configuration-free+// path, which would have silently enabled solving while every configured path left it+// off. Aligned to false; this records the decision so it is not "restored" later.+func TestCoreEnabledDefaultMatchesTheConfigDefault(t *testing.T) {+ if autosolver.DefaultConfig().Enabled {+ t.Error("autosolver.DefaultConfig().Enabled is true again; the only path that observes it is the config-free one, where enabling solving contradicts every configured path")+ }+}++// No solver name may be spelled as a literal in internal/config: internal/autosolver+// owns that vocabulary, and this package's default list is where two of the three+// copies used to restate it.+func TestNoSolverNameLiteralsInThisPackage(t *testing.T) {+ entries, err := os.ReadDir(".")+ if err != nil {+ t.Fatal(err)+ }++ var offenders []string+ 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)+ if err != nil {+ t.Fatal(err)+ }+ scanned+++ for _, literal := range []string{`"` + autosolver.CloudflareSolverName + `"`, `"` + autosolver.SemanticSolverName + `"`} {+ if strings.Contains(string(body), literal) {+ offenders = append(offenders, name+" contains "+literal)+ }+ }+ }+ if scanned == 0 {+ t.Fatal("no production files scanned — this census would pass vacuously")+ }+ if len(offenders) > 0 {+ t.Errorf("solver names must come from internal/autosolver's constants: %v", offenders)+ }+}diff --git a/internal/config/config_file.go b/internal/config/config_file.goindex b71956a1..e4a427d0 100644--- a/internal/config/config_file.go+++ b/internal/config/config_file.go@@ -4,8 +4,6 @@ import ("path/filepath""strconv""strings"-- "github.com/pinchtab/pinchtab/internal/autosolver")// CurrentConfigVersion is bumped when config schema changes require migration or wizard re-run.@@ -155,15 +153,9 @@ func DefaultFileConfig() FileConfig {dashboardSessionElevationWindowSec := 15 * 60dashboardSessionPersistElevationAcrossRestart := falsedashboardSessionRequireElevation := false- autoSolverEnabled := false- autoSolverAutoTrigger := true- autoSolverTriggerOnNavigate := true- autoSolverTriggerOnAction := true- autoSolverMaxAttempts := 8- autoSolverSolverTimeoutSec := 30- autoSolverRetryBaseDelayMs := 500- autoSolverRetryMaxDelayMs := 10000- autoSolverLLMFallback := false+ // Locals only so the shared defaults can be pointer-wrapped; the values come+ // from defaultAutoSolverConfig, not from a second transcription of them.+ autoSolver := defaultAutoSolverConfig()return FileConfig{Schema: CurrentConfigSchemaURL(),ConfigVersion: CurrentConfigVersion,@@ -270,16 +262,16 @@ func DefaultFileConfig() FileConfig {},},AutoSolver: AutoSolverFileConfig{- Enabled: &autoSolverEnabled,- AutoTrigger: &autoSolverAutoTrigger,- TriggerOnNavigate: &autoSolverTriggerOnNavigate,- TriggerOnAction: &autoSolverTriggerOnAction,- MaxAttempts: &autoSolverMaxAttempts,- SolverTimeoutSec: &autoSolverSolverTimeoutSec,- RetryBaseDelayMs: &autoSolverRetryBaseDelayMs,- RetryMaxDelayMs: &autoSolverRetryMaxDelayMs,- Solvers: autosolver.DefaultConfig().Solvers,- LLMFallback: &autoSolverLLMFallback,+ Enabled: &autoSolver.Enabled,+ AutoTrigger: &autoSolver.AutoTrigger,+ TriggerOnNavigate: &autoSolver.TriggerOnNavigate,+ TriggerOnAction: &autoSolver.TriggerOnAction,+ MaxAttempts: &autoSolver.MaxAttempts,+ SolverTimeoutSec: &autoSolver.SolverTimeoutSec,+ RetryBaseDelayMs: &autoSolver.RetryBaseDelayMs,+ RetryMaxDelayMs: &autoSolver.RetryMaxDelayMs,+ Solvers: autoSolver.Solvers,+ LLMFallback: &autoSolver.LLMFallback,},}}diff --git a/internal/config/config_load.go b/internal/config/config_load.goindex 3442fe98..a5079219 100644--- a/internal/config/config_load.go+++ b/internal/config/config_load.go@@ -161,6 +161,29 @@ func EmitLoadDiagnostics(diags []LoadDiagnostic) {// LoadConfig builds the RuntimeConfig (env > file > defaults) with no logging and// no os.Exit. It returns the config, ordered diagnostics for the caller to log,// and a fatal error (e.g. missing port) for the caller to act on.+// defaultAutoSolverConfig is the single owner of the autoSolver section's defaults.+// LoadConfig assigns it directly and DefaultFileConfig pointer-wraps its fields —+// the plain/pointer split stays, because pointer-wrapping is how "absent from file"+// remains distinguishable from "explicitly false", but the VALUES are written once.+// Everything the core also owns is read from autosolver.DefaultConfig() with the unit+// conversion in this one place; only the three trigger flags, which the core has no+// counterpart for, are literals here.+func defaultAutoSolverConfig() AutoSolverConfig {+ core := autosolver.DefaultConfig()+ return AutoSolverConfig{+ Enabled: core.Enabled,+ AutoTrigger: true,+ TriggerOnNavigate: true,+ TriggerOnAction: true,+ MaxAttempts: core.MaxAttempts,+ SolverTimeoutSec: int(core.SolverTimeout / time.Second),+ RetryBaseDelayMs: int(core.RetryBaseDelay / time.Millisecond),+ RetryMaxDelayMs: int(core.RetryMaxDelay / time.Millisecond),+ Solvers: core.Solvers,+ LLMFallback: core.LLMFallback,+ }+}+func LoadConfig() (*RuntimeConfig, []LoadDiagnostic, error) {cfg := &RuntimeConfig{Bind: "127.0.0.1",@@ -271,18 +294,7 @@ func LoadConfig() (*RuntimeConfig, []LoadDiagnostic, error) {},},- AutoSolver: AutoSolverConfig{- Enabled: false,- AutoTrigger: true,- TriggerOnNavigate: true,- TriggerOnAction: true,- MaxAttempts: 8,- SolverTimeoutSec: 30,- RetryBaseDelayMs: 500,- RetryMaxDelayMs: 10000,- Solvers: autosolver.DefaultConfig().Solvers,- LLMFallback: false,- },+ AutoSolver: defaultAutoSolverConfig(),}finalizeProfileConfig(cfg)