From a43c7345466c4dad9f988944b573d2f597f1087d Mon Sep 17 00:00:00 2001 From: Jakub Zych Date: Wed, 16 Sep 2026 14:08:17 +0200 Subject: [PATCH 1/4] test(01-04): cover config, lifecycle, services, events and context - Table-driven compass precedence, malformed YAML, snake_case env and concurrent reads - Party duplicate/missing/cycle, reordered manifest, HasConfig/HasCommands discovery - Isolated backpack services, festival panic payload omission, towel nested isolation --- backpack/services_test.go | 89 ++++++++++++ compass/config_test.go | 297 ++++++++++++++++++++++++++++++++++++++ festival/bus_test.go | 108 ++++++++++++++ pact/capabilities_test.go | 97 +++++++++++++ party/registry_test.go | 169 ++++++++++++++++++++++ towel/context_test.go | 80 ++++++++++ 6 files changed, 840 insertions(+) create mode 100644 pact/capabilities_test.go diff --git a/backpack/services_test.go b/backpack/services_test.go index 9daa5be..4515a13 100644 --- a/backpack/services_test.go +++ b/backpack/services_test.go @@ -1,9 +1,11 @@ package backpack import ( + "sync" "testing" "git.golem15.com/golem15/summercms/compass" + "git.golem15.com/golem15/summercms/pact" ) type ping interface { @@ -70,3 +72,90 @@ func TestHasPluginUsesCompleteSet(t *testing.T) { t.Fatal("HasPlugin(golem15.missing) = true") } } + +func TestTwoAppsIsolateHasPluginAndServices(t *testing.T) { + a := New(&compass.Config{}) + b := New(&compass.Config{}) + a.SetPlugins([]string{"golem15.optional"}) + b.SetPlugins([]string{"golem15.hello"}) + if err := a.Publish[pact.OptionalMessage](msgService{s: "from-a"}); err != nil { + t.Fatalf("Publish A: %v", err) + } + + if !a.HasPlugin("golem15.optional") { + t.Fatal("app A should see optional") + } + if a.HasPlugin("golem15.hello") { + t.Fatal("app A should not see hello") + } + if !b.HasPlugin("golem15.hello") { + t.Fatal("app B should see hello") + } + if b.HasPlugin("golem15.optional") { + t.Fatal("app B should not see optional") + } + + got, ok := a.Lookup[pact.OptionalMessage]() + if !ok || got.Message() != "from-a" { + t.Fatalf("app A lookup = (%v, %v)", got, ok) + } + if _, ok := b.Lookup[pact.OptionalMessage](); ok { + t.Fatal("app B must not see app A's OptionalMessage") + } +} + +func TestPublishNilRejectedAndLookupStaysAbsent(t *testing.T) { + app := New(&compass.Config{}) + var nilPing ping + if err := app.Publish[ping](nilPing); err == nil { + t.Fatal("expected nil publish error") + } + if _, ok := app.Lookup[ping](); ok { + t.Fatal("nil publish must not store a value") + } +} + +func TestDuplicatePublishKeepsFirstValue(t *testing.T) { + app := New(&compass.Config{}) + if err := app.Publish[ping](pingImpl{s: "first"}); err != nil { + t.Fatalf("Publish: %v", err) + } + if err := app.Publish[ping](pingImpl{s: "second"}); err == nil { + t.Fatal("expected duplicate error") + } + got, ok := app.Lookup[ping]() + if !ok || got.Ping() != "first" { + t.Fatalf("Lookup = (%v, %v), want first", got, ok) + } +} + +func TestConcurrentLookupAndHasPlugin(t *testing.T) { + app := New(&compass.Config{}) + app.SetPlugins([]string{"golem15.hello"}) + if err := app.Publish[ping](pingImpl{s: "pong"}); err != nil { + t.Fatal(err) + } + var wg sync.WaitGroup + for i := 0; i < 16; i++ { + wg.Add(1) + go func() { + defer wg.Done() + for j := 0; j < 80; j++ { + got, ok := app.Lookup[ping]() + if !ok || got.Ping() != "pong" { + t.Errorf("Lookup = (%v, %v)", got, ok) + return + } + if !app.HasPlugin("golem15.hello") || app.HasPlugin("golem15.missing") { + t.Error("HasPlugin concurrent mismatch") + return + } + } + }() + } + wg.Wait() +} + +type msgService struct{ s string } + +func (m msgService) Message() string { return m.s } diff --git a/compass/config_test.go b/compass/config_test.go index d956498..6b6b3c2 100644 --- a/compass/config_test.go +++ b/compass/config_test.go @@ -3,6 +3,8 @@ package compass import ( "os" "path/filepath" + "strings" + "sync" "testing" "testing/fstest" ) @@ -241,3 +243,298 @@ func writeConfigTree(t *testing.T, files map[string]string) string { } return dir } + +func TestPrecedenceIsolatesEachLayer(t *testing.T) { + pluginFS := fstest.MapFS{ + "config/config.yaml": {Data: []byte("name: plugin\n")}, + } + tests := []struct { + name string + plugin bool + base bool + overlay bool + env bool + persist bool + set bool + want string + }{ + {name: "plugin default", plugin: true, want: "plugin"}, + {name: "base over plugin", plugin: true, base: true, want: "base"}, + {name: "overlay over base", plugin: true, base: true, overlay: true, want: "overlay"}, + {name: "env over overlay", plugin: true, base: true, overlay: true, env: true, want: "env"}, + {name: "persist over env", plugin: true, base: true, overlay: true, env: true, persist: true, want: "persist"}, + {name: "set over persist", plugin: true, base: true, overlay: true, env: true, persist: true, set: true, want: "set"}, + {name: "env over base without overlay", plugin: true, base: true, env: true, want: "env"}, + {name: "persist over overlay without env", plugin: true, base: true, overlay: true, persist: true, want: "persist"}, + {name: "set only", set: true, want: "set"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + files := map[string]string{} + if tt.base { + files["app.yaml"] = "name: base\n" + } else { + files["app.yaml"] = "other: 1\n" + } + if tt.overlay { + files["env/development/app.yaml"] = "name: overlay\n" + } + if tt.persist { + files["env/development/overrides.yaml"] = "app:\n name: persist\n" + } + dir := writeConfigTree(t, files) + environ := []string{} + if tt.env { + environ = []string{"SUMMER_APP__NAME=env"} + } + cfg, err := Open(Options{Dir: dir, Env: "development", Environ: environ}) + if err != nil { + t.Fatalf("Open: %v", err) + } + if tt.plugin { + if err := cfg.MergePlugin("app", pluginFS); err != nil { + t.Fatalf("MergePlugin: %v", err) + } + } + if tt.set { + if err := cfg.Set("app.name", "set"); err != nil { + t.Fatalf("Set: %v", err) + } + } + if got := cfg.String("app.name"); got != tt.want { + t.Fatalf("app.name = %q, want %q", got, tt.want) + } + }) + } +} + +func TestMalformedYAMLIsRejectedByName(t *testing.T) { + tests := []struct { + name string + file string + body string + want string + }{ + {name: "base section", file: "app.yaml", body: "name: [unterminated\n", want: "app.yaml"}, + {name: "env overlay", file: "env/development/app.yaml", body: "name: : :\n[", want: "app.yaml"}, + {name: "overrides", file: "env/development/overrides.yaml", body: "app: [\n", want: "overrides"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + files := map[string]string{"app.yaml": "name: base\n"} + files[tt.file] = tt.body + dir := writeConfigTree(t, files) + _, err := Open(Options{Dir: dir, Env: "development", Environ: []string{}}) + if err == nil { + t.Fatal("expected malformed YAML error") + } + if !strings.Contains(err.Error(), tt.want) { + t.Fatalf("error %q should name %q", err, tt.want) + } + }) + } +} + +func TestMalformedPluginYAMLIsRejected(t *testing.T) { + dir := writeConfigTree(t, map[string]string{"app.yaml": "name: base\n"}) + cfg, err := Open(Options{Dir: dir, Environ: []string{}}) + if err != nil { + t.Fatalf("Open: %v", err) + } + fsys := fstest.MapFS{ + "config/config.yaml": {Data: []byte("posts_per_page: [\n")}, + } + err = cfg.MergePlugin("golem15.hello", fsys) + if err == nil { + t.Fatal("expected plugin YAML parse error") + } + if !strings.Contains(err.Error(), "golem15.hello") { + t.Fatalf("error should name plugin id, got %v", err) + } +} + +func TestSnakeCaseEnvKeysStayLiteral(t *testing.T) { + dir := writeConfigTree(t, map[string]string{"app.yaml": "name: base\n"}) + cfg, err := Open(Options{ + Dir: dir, + Environ: []string{ + "SUMMER_APP__FEATURE_FLAG=on", + "SUMMER_GOLEM15__HELLO__POSTS_PER_PAGE=7", + }, + }) + if err != nil { + t.Fatalf("Open: %v", err) + } + if got := cfg.String("app.feature_flag"); got != "on" { + t.Fatalf("feature_flag = %q, want on", got) + } + if cfg.Has("app.feature.flag") { + t.Fatal("single underscore must not split the leaf") + } + if got := cfg.Int("golem15.hello.posts_per_page"); got != 7 { + t.Fatalf("posts_per_page = %d, want 7", got) + } + if cfg.Has("golem15.hello.posts.per.page") { + t.Fatal("snake_case plugin key must stay one leaf") + } +} + +func TestDotEnvDoesNotOverrideRealEnviron(t *testing.T) { + root := t.TempDir() + dir := filepath.Join(root, "config") + if err := os.Mkdir(dir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "app.yaml"), []byte("name: base\n"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(root, ".env"), []byte("SUMMER_APP__NAME=from-dotenv\nSUMMER_APP__TITLE=dotenv-title\n"), 0o600); err != nil { + t.Fatal(err) + } + cfg, err := Open(Options{ + Dir: dir, + Environ: []string{"SUMMER_APP__NAME=from-real"}, + }) + if err != nil { + t.Fatalf("Open: %v", err) + } + if got := cfg.String("app.name"); got != "from-real" { + t.Fatalf("name = %q, want from-real", got) + } + if got := cfg.String("app.title"); got != "dotenv-title" { + t.Fatalf("title = %q, want dotenv-title", got) + } +} + +func TestDottedPluginNamespaceAndTypedSection(t *testing.T) { + dir := writeConfigTree(t, map[string]string{ + "app.yaml": "name: hello-app\n", + "golem15.hello.yaml": "from_app: true\n", + }) + cfg, err := Open(Options{Dir: dir, Environ: []string{}}) + if err != nil { + t.Fatalf("Open: %v", err) + } + fsys := fstest.MapFS{ + "config/config.yaml": {Data: []byte("posts_per_page: 10\nshow_author: true\n")}, + "config/settings.yaml": {Data: []byte("theme: dark\n")}, + } + if err := cfg.MergePlugin("golem15.hello", fsys); err != nil { + t.Fatalf("MergePlugin: %v", err) + } + if got := cfg.Int("golem15.hello.posts_per_page"); got != 10 { + t.Fatalf("posts_per_page = %d, want 10", got) + } + if got := cfg.String("golem15.hello.settings.theme"); got != "dark" { + t.Fatalf("settings.theme = %q, want dark", got) + } + if !cfg.Bool("golem15.hello.from_app") { + t.Fatal("app-level dotted plugin namespace file should merge at golem15.hello") + } + + var section struct { + PostsPerPage int `koanf:"posts_per_page"` + ShowAuthor bool `koanf:"show_author"` + FromApp bool `koanf:"from_app"` + } + if err := cfg.LoadSection("golem15.hello", §ion); err != nil { + t.Fatalf("LoadSection: %v", err) + } + if section.PostsPerPage != 10 || !section.ShowAuthor || !section.FromApp { + t.Fatalf("LoadSection = %+v", section) + } +} + +func TestSetPersistReloadRoundTrip(t *testing.T) { + dir := writeConfigTree(t, map[string]string{"app.yaml": "name: base\n"}) + cfg, err := Open(Options{Dir: dir, Env: "development", Environ: []string{}}) + if err != nil { + t.Fatalf("Open: %v", err) + } + if err := cfg.Set("app.name", "runtime"); err != nil { + t.Fatalf("Set: %v", err) + } + if err := cfg.Persist(); err != nil { + t.Fatalf("Persist: %v", err) + } + body, err := os.ReadFile(filepath.Join(dir, "env", "development", "overrides.yaml")) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(body), "runtime") { + t.Fatalf("overrides missing runtime value: %s", body) + } + if err := cfg.Set("app.name", "unsaved"); err != nil { + t.Fatalf("Set unsaved: %v", err) + } + if err := cfg.Reload(); err != nil { + t.Fatalf("Reload: %v", err) + } + if got := cfg.String("app.name"); got != "runtime" { + t.Fatalf("after Reload, name = %q, want persisted runtime", got) + } +} + +func TestConcurrentReadsWhileSet(t *testing.T) { + dir := writeConfigTree(t, map[string]string{"app.yaml": "name: base\ncount: 1\n"}) + cfg, err := Open(Options{Dir: dir, Environ: []string{}}) + if err != nil { + t.Fatalf("Open: %v", err) + } + var wg sync.WaitGroup + for i := 0; i < 16; i++ { + wg.Add(1) + go func() { + defer wg.Done() + for j := 0; j < 80; j++ { + _ = cfg.String("app.name") + _ = cfg.Int("app.count") + _ = cfg.Bool("app.debug") + _ = cfg.Has("app.name") + _, _ = cfg.Lookup("app.name") + var section struct { + Name string `koanf:"name"` + } + _ = cfg.LoadSection("app", §ion) + } + }() + } + wg.Add(1) + go func() { + defer wg.Done() + for j := 0; j < 80; j++ { + if err := cfg.Set("app.count", j); err != nil { + t.Errorf("Set: %v", err) + return + } + } + }() + wg.Wait() + if !cfg.Has("app.name") { + t.Fatal("app.name missing after concurrent access") + } +} + +func TestOpenRejectsEmptyDir(t *testing.T) { + _, err := Open(Options{}) + if err == nil { + t.Fatal("expected empty dir error") + } +} + +func TestSUMMER_ENVDoesNotEnterConfigTree(t *testing.T) { + dir := writeConfigTree(t, map[string]string{ + "app.yaml": "name: base\n", + "env/development/app.yaml": "name: dev\n", + }) + cfg, err := Open(Options{Dir: dir, Environ: []string{"SUMMER_ENV=development"}}) + if err != nil { + t.Fatalf("Open: %v", err) + } + if cfg.Has("env") || cfg.Has("SUMMER_ENV") { + t.Fatal("SUMMER_ENV must not become a config key") + } + if cfg.String("app.name") != "dev" { + t.Fatalf("name = %q, want dev", cfg.String("app.name")) + } +} diff --git a/festival/bus_test.go b/festival/bus_test.go index 81cb61c..fc82bcc 100644 --- a/festival/bus_test.go +++ b/festival/bus_test.go @@ -4,6 +4,8 @@ import ( "context" "errors" "strings" + "sync" + "sync/atomic" "testing" ) @@ -164,3 +166,109 @@ func TestBusesAreIsolated(t *testing.T) { t.Fatal("bus B should not invoke bus A's listeners") } } + +func TestConcurrentIndependentAppBuses(t *testing.T) { + a := New() + b := New() + var aCount, bCount atomic.Int64 + a.Listen[*evt]("golem15.a", func(ctx context.Context, e *evt) error { + aCount.Add(1) + return nil + }) + b.Listen[*evt]("golem15.b", func(ctx context.Context, e *evt) error { + bCount.Add(1) + return nil + }) + var wg sync.WaitGroup + const n = 40 + for i := 0; i < n; i++ { + wg.Add(2) + go func() { + defer wg.Done() + if err := a.Fire(context.Background(), &evt{}); err != nil { + t.Errorf("bus A: %v", err) + } + }() + go func() { + defer wg.Done() + if err := b.Fire(context.Background(), &evt{}); err != nil { + t.Errorf("bus B: %v", err) + } + }() + } + wg.Wait() + if aCount.Load() != n || bCount.Load() != n { + t.Fatalf("counts a=%d b=%d, want %d each", aCount.Load(), bCount.Load(), n) + } +} + +func TestPanicRecoveryOmitsEventPayload(t *testing.T) { + bus := New() + bus.Listen[*evt]("golem15.boom", func(ctx context.Context, e *evt) error { + panic("secret-payload-xyz") + }) + event := &evt{data: map[string]any{"secret": "classified"}} + err := bus.Fire(context.Background(), event) + if err == nil { + t.Fatal("expected panic error") + } + msg := err.Error() + if !strings.Contains(msg, "golem15.boom") { + t.Fatalf("error should name owner plugin, got %v", err) + } + if strings.Contains(msg, "secret-payload-xyz") || strings.Contains(msg, "classified") { + t.Fatalf("panic recovery leaked payload: %v", err) + } +} + +func TestFireWithNoListeners(t *testing.T) { + bus := New() + if err := bus.Fire(context.Background(), &evt{}); err != nil { + t.Fatalf("Fire with no listeners: %v", err) + } +} + +func TestCollectWithoutCollectableReturnsEmptyMap(t *testing.T) { + type plain struct{ n int } + bus := New() + bus.Listen[plain]("golem15.a", func(ctx context.Context, e plain) error { return nil }) + got, err := bus.Collect(context.Background(), plain{n: 1}) + if err != nil { + t.Fatal(err) + } + if len(got) != 0 { + t.Fatalf("payload = %v, want empty", got) + } +} + +func TestUntilHandledNeverHandled(t *testing.T) { + bus := New() + var order []string + bus.Listen[*evt]("golem15.a", func(ctx context.Context, e *evt) error { + order = append(order, "a") + return nil + }) + ok, err := bus.UntilHandled(context.Background(), &evt{}) + if err != nil { + t.Fatal(err) + } + if ok { + t.Fatal("expected unhandled") + } + if strings.Join(order, ",") != "a" { + t.Fatalf("order = %v, want a", order) + } +} + +func TestListenNilBusOrFnIsNoop(t *testing.T) { + var bus *Bus + bus.Listen[*evt]("golem15.a", func(ctx context.Context, e *evt) error { return errors.New("should not run") }) + if err := bus.Fire(context.Background(), &evt{}); err != nil { + t.Fatalf("nil bus Fire: %v", err) + } + live := New() + live.Listen[*evt]("golem15.a", nil) + if err := live.Fire(context.Background(), &evt{}); err != nil { + t.Fatalf("nil fn Fire: %v", err) + } +} diff --git a/pact/capabilities_test.go b/pact/capabilities_test.go new file mode 100644 index 0000000..812a2ba --- /dev/null +++ b/pact/capabilities_test.go @@ -0,0 +1,97 @@ +package pact + +import ( + "io/fs" + "testing" + "testing/fstest" + + "git.golem15.com/golem15/summercms/bonfire" +) + +type configOnly struct{} + +func (configOnly) ConfigFS() fs.FS { + return fstest.MapFS{"config/config.yaml": {Data: []byte("k: 1\n")}} +} + +type commandsOnly struct{} + +func (commandsOnly) Commands() []bonfire.Command { + return []bonfire.Command{{Name: "demo:run"}} +} + +type bothCaps struct { + configOnly + commandsOnly +} + +type neither struct{} + +func TestOptionalCapabilitiesDiscoveredByTypeAssertion(t *testing.T) { + plugins := []any{configOnly{}, commandsOnly{}, bothCaps{}, neither{}, extraMessage{}} + + var configs, commands, messages, none int + for _, p := range plugins { + _, hasCfg := p.(HasConfig) + _, hasCmd := p.(HasCommands) + _, hasMsg := p.(OptionalMessage) + if hasCfg { + configs++ + } + if hasCmd { + commands++ + } + if hasMsg { + messages++ + } + if !hasCfg && !hasCmd && !hasMsg { + none++ + } + } + if configs != 2 { + t.Fatalf("HasConfig count = %d, want 2", configs) + } + if commands != 2 { + t.Fatalf("HasCommands count = %d, want 2", commands) + } + if messages != 1 { + t.Fatalf("OptionalMessage count = %d, want 1", messages) + } + if none != 1 { + t.Fatalf("neither count = %d, want 1", none) + } +} + +func TestHasConfigReturnsFilesystem(t *testing.T) { + var p HasConfig = configOnly{} + fsys := p.ConfigFS() + if fsys == nil { + t.Fatal("ConfigFS returned nil") + } + raw, err := fs.ReadFile(fsys, "config/config.yaml") + if err != nil { + t.Fatal(err) + } + if string(raw) != "k: 1\n" { + t.Fatalf("ConfigFS body = %q", raw) + } +} + +func TestHasCommandsReturnsNamespacedCommand(t *testing.T) { + var p HasCommands = commandsOnly{} + cmds := p.Commands() + if len(cmds) != 1 || cmds[0].Name != "demo:run" { + t.Fatalf("Commands = %+v", cmds) + } +} + +func TestOptionalMessageContract(t *testing.T) { + var msg OptionalMessage = extraMessage{s: "hello-from-optional"} + if msg.Message() != "hello-from-optional" { + t.Fatalf("Message = %q", msg.Message()) + } +} + +type extraMessage struct{ s string } + +func (e extraMessage) Message() string { return e.s } diff --git a/party/registry_test.go b/party/registry_test.go index f9a915e..cb25ea8 100644 --- a/party/registry_test.go +++ b/party/registry_test.go @@ -9,7 +9,9 @@ import ( "testing/fstest" "git.golem15.com/golem15/summercms/backpack" + "git.golem15.com/golem15/summercms/bonfire" "git.golem15.com/golem15/summercms/compass" + "git.golem15.com/golem15/summercms/pact" ) type tracePlugin struct { @@ -225,3 +227,170 @@ func TestActivateRunsAllRegisterBeforeAnyBoot(t *testing.T) { t.Fatalf("lifecycle = %v, want %v", log, want) } } + +func TestActivateReorderedManifestStillTopoSorts(t *testing.T) { + var log []string + hello := &tracePlugin{id: "golem15.hello", log: &log} + greeter := &tracePlugin{id: "golem15.greeter", req: []string{"golem15.hello"}, log: &log} + extra := &tracePlugin{id: "golem15.extra", req: []string{"golem15.greeter"}, log: &log} + app := backpack.New(&compass.Config{}) + got, err := activate( + []Plugin{extra, greeter, hello}, + app, + []string{"golem15.extra", "golem15.hello", "golem15.greeter"}, + ) + if err != nil { + t.Fatalf("activate: %v", err) + } + if len(got) != 3 || got[0].ID() != "golem15.hello" || got[1].ID() != "golem15.greeter" || got[2].ID() != "golem15.extra" { + t.Fatalf("order = %v, want hello, greeter, extra", idsOf(got)) + } + want := []string{ + "golem15.hello:register", + "golem15.greeter:register", + "golem15.extra:register", + "golem15.hello:boot", + "golem15.greeter:boot", + "golem15.extra:boot", + } + if strings.Join(log, ",") != strings.Join(want, ",") { + t.Fatalf("lifecycle = %v, want %v", log, want) + } +} + +func TestActivateDuplicateManifestIDRejected(t *testing.T) { + var log []string + p := &tracePlugin{id: "golem15.hello", log: &log} + app := backpack.New(&compass.Config{}) + _, err := activate([]Plugin{p}, app, []string{"golem15.hello", "golem15.hello"}) + if err == nil { + t.Fatal("expected duplicate manifest id error") + } + if !strings.Contains(err.Error(), "golem15.hello") { + t.Fatalf("error %q should name the duplicate id", err) + } + if len(log) != 0 { + t.Fatalf("lifecycle ran despite duplicate manifest: %v", log) + } +} + +func TestActivateUnregisteredPluginNamesID(t *testing.T) { + app := backpack.New(&compass.Config{}) + _, err := activate(nil, app, []string{"golem15.missing"}) + if err == nil { + t.Fatal("expected missing registered plugin error") + } + if !strings.Contains(err.Error(), "golem15.missing") { + t.Fatalf("error %q should name the missing id", err) + } +} + +func TestActivateEmptyManifestIDRejected(t *testing.T) { + var log []string + p := &tracePlugin{id: "golem15.hello", log: &log} + app := backpack.New(&compass.Config{}) + _, err := activate([]Plugin{p}, app, []string{""}) + if err == nil { + t.Fatal("expected empty plugin id error") + } +} + +func TestActivateNilAppRejected(t *testing.T) { + _, err := Activate(nil, []string{"golem15.hello"}) + if err == nil { + t.Fatal("expected nil app error") + } +} + +func TestRegisterNilIsNoop(t *testing.T) { + Register(nil) +} + +func TestActivateHasPluginFalseForUnselected(t *testing.T) { + var log []string + hello := &tracePlugin{id: "golem15.hello", log: &log} + opt := &tracePlugin{id: "golem15.optional", log: &log} + app := backpack.New(&compass.Config{}) + if _, err := activate([]Plugin{hello, opt}, app, []string{"golem15.hello"}); err != nil { + t.Fatalf("activate: %v", err) + } + if !app.HasPlugin("golem15.hello") { + t.Fatal("selected plugin must be present") + } + if app.HasPlugin("golem15.optional") { + t.Fatal("unselected registered plugin must not appear in HasPlugin") + } +} + +type commandsPlugin struct { + tracePlugin +} + +func (p *commandsPlugin) Commands() []bonfire.Command { + return []bonfire.Command{{ + Name: "demo:run", + Description: "demo command", + }} +} + +func TestActivateDiscoversHasConfigAndHasCommands(t *testing.T) { + var log []string + var got int + cfgPlugin := &configPlugin{ + id: "golem15.hello", + got: &got, + fsys: fstest.MapFS{ + "config/config.yaml": {Data: []byte("posts_per_page: 4\n")}, + }, + } + cmdPlugin := &commandsPlugin{tracePlugin: tracePlugin{id: "golem15.demo", log: &log}} + plain := &tracePlugin{id: "golem15.plain", log: &log} + + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "app.yaml"), []byte("name: app\n"), 0o644); err != nil { + t.Fatal(err) + } + cfg, err := compass.Load(dir) + if err != nil { + t.Fatalf("Load: %v", err) + } + app := backpack.New(cfg) + gotPlugins, err := activate([]Plugin{cfgPlugin, cmdPlugin, plain}, app, []string{"golem15.hello", "golem15.demo", "golem15.plain"}) + if err != nil { + t.Fatalf("activate: %v", err) + } + if got != 4 { + t.Fatalf("HasConfig value during Register = %d, want 4", got) + } + + var sawConfig, sawCommands, sawPlainCommands bool + for _, p := range gotPlugins { + if _, ok := p.(pact.HasConfig); ok && p.ID() == "golem15.hello" { + sawConfig = true + } + if hc, ok := p.(pact.HasCommands); ok { + if p.ID() == "golem15.demo" { + cmds := hc.Commands() + if len(cmds) != 1 || cmds[0].Name != "demo:run" { + t.Fatalf("HasCommands commands = %+v", cmds) + } + sawCommands = true + } + if p.ID() == "golem15.plain" { + sawPlainCommands = true + } + } + } + if !sawConfig { + t.Fatal("golem15.hello should satisfy HasConfig") + } + if !sawCommands { + t.Fatal("golem15.demo should satisfy HasCommands") + } + if sawPlainCommands { + t.Fatal("plain plugin must not satisfy HasCommands") + } + if _, ok := any(plain).(pact.HasConfig); ok { + t.Fatal("plain plugin must not satisfy HasConfig") + } +} diff --git a/towel/context_test.go b/towel/context_test.go index 42976bf..3b478cb 100644 --- a/towel/context_test.go +++ b/towel/context_test.go @@ -4,6 +4,7 @@ import ( "context" "os" "strings" + "sync" "testing" ) @@ -33,6 +34,85 @@ func TestContextAccessorsRoundTrip(t *testing.T) { } } +func TestNestedContextIsolation(t *testing.T) { + parent := WithActor(context.Background(), "parent") + parent = WithOrganization(parent, "org-parent") + child := WithActor(parent, "child") + child = WithCollection(child, "col-child") + child = WithLocale(child, "pl") + + if got, ok := Actor(parent); !ok || got != "parent" { + t.Fatalf("parent Actor mutated: (%q, %v)", got, ok) + } + if got, ok := Actor(child); !ok || got != "child" { + t.Fatalf("child Actor = (%q, %v)", got, ok) + } + if got, ok := Organization(child); !ok || got != "org-parent" { + t.Fatalf("child should inherit organization, got (%q, %v)", got, ok) + } + if _, ok := Collection(parent); ok { + t.Fatal("collection leaked to parent") + } + if _, ok := Locale(parent); ok { + t.Fatal("locale leaked to parent") + } + if got, ok := Collection(child); !ok || got != "col-child" { + t.Fatalf("child Collection = (%q, %v)", got, ok) + } +} + +func TestNilContextAccessors(t *testing.T) { + if _, ok := Actor(nil); ok { + t.Fatal("Actor(nil) should be absent") + } + if _, ok := Organization(nil); ok { + t.Fatal("Organization(nil) should be absent") + } + if _, ok := Collection(nil); ok { + t.Fatal("Collection(nil) should be absent") + } + if _, ok := Locale(nil); ok { + t.Fatal("Locale(nil) should be absent") + } + ctx := WithActor(nil, "user-1") + if got, ok := Actor(ctx); !ok || got != "user-1" { + t.Fatalf("WithActor(nil) = (%q, %v)", got, ok) + } +} + +func TestConcurrentContextAccessors(t *testing.T) { + ctx := WithActor(context.Background(), "user-1") + ctx = WithOrganization(ctx, "org-9") + ctx = WithCollection(ctx, "col-3") + ctx = WithLocale(ctx, "pl") + var wg sync.WaitGroup + for i := 0; i < 16; i++ { + wg.Add(1) + go func() { + defer wg.Done() + for j := 0; j < 80; j++ { + if got, ok := Actor(ctx); !ok || got != "user-1" { + t.Errorf("Actor = (%q, %v)", got, ok) + return + } + if got, ok := Organization(ctx); !ok || got != "org-9" { + t.Errorf("Organization = (%q, %v)", got, ok) + return + } + if got, ok := Collection(ctx); !ok || got != "col-3" { + t.Errorf("Collection = (%q, %v)", got, ok) + return + } + if got, ok := Locale(ctx); !ok || got != "pl" { + t.Errorf("Locale = (%q, %v)", got, ok) + return + } + } + }() + } + wg.Wait() +} + func TestNoPackageGlobalRequestState(t *testing.T) { entries, err := os.ReadDir(".") if err != nil { From dc7997e45c8c4768f8dcd63ab7e7fa9c2ed294b5 Mon Sep 17 00:00:00 2001 From: Jakub Zych Date: Wed, 16 Sep 2026 14:14:05 +0200 Subject: [PATCH 2/4] test(01-04): cover tool, output, watch loop and workspace modules - Non-TTY widgets/prompts, flag parsing, secret non-leak and malicious IDs - Real hello workspace rebuild latency line, debounce and ignored bin/tmp - scripts/check-phase1.sh runs vet/test/race across root, hello, base, greeter, optional --- bonfire/output_test.go | 107 +++++++++++++ bonfire/prompts_test.go | 54 +++++++ examples/hello/hello_test.go | 9 ++ internal/build/build_test.go | 59 ++++++++ internal/dev/watch_test.go | 281 ++++++++++++++++++++++++++++++++++- scripts/check-phase1.sh | 34 +++++ 6 files changed, 542 insertions(+), 2 deletions(-) create mode 100755 scripts/check-phase1.sh diff --git a/bonfire/output_test.go b/bonfire/output_test.go index 18f964d..8a08a19 100644 --- a/bonfire/output_test.go +++ b/bonfire/output_test.go @@ -2,6 +2,7 @@ package bonfire import ( "bytes" + "context" "errors" "strings" "testing" @@ -137,6 +138,112 @@ func TestKernelAndNamespacedCommands(t *testing.T) { } } +func TestFlagAndArgumentParsing(t *testing.T) { + var buf bytes.Buffer + var gotArgs []string + var gotTarget, gotMode, gotUnset string + var gotTargetOK, gotModeOK, gotUnsetOK bool + root, err := NewRootIO("app", []Command{{ + Name: "demo:run", + Description: "Run a demo", + Args: []Arg{ + {Name: "target", Description: "who", Required: true}, + {Name: "extra", Description: "optional"}, + }, + Flags: []Flag{ + {Name: "mode", Shorthand: "m", Default: "slow", Description: "speed"}, + {Name: "unused", Default: "", Description: "empty default"}, + }, + Run: func(ctx context.Context, in Input, out Output) error { + gotArgs = append([]string(nil), in.Args()...) + gotTarget, gotTargetOK = in.Argument("target") + gotMode, gotModeOK = in.Flag("mode") + gotUnset, gotUnsetOK = in.Flag("unused") + out.Println("ran " + gotTarget) + return nil + }, + }}, strings.NewReader(""), &buf, &buf) + if err != nil { + t.Fatal(err) + } + root.SetArgs([]string{"demo:run", "-m", "fast", "world"}) + if err := root.Execute(); err != nil { + t.Fatal(err) + } + if !strings.Contains(buf.String(), "ran world") { + t.Fatalf("captured output = %q", buf.String()) + } + if strings.Join(gotArgs, ",") != "world" { + t.Fatalf("Args = %v", gotArgs) + } + if !gotTargetOK || gotTarget != "world" { + t.Fatalf("Argument(target) = (%q, %v)", gotTarget, gotTargetOK) + } + if !gotModeOK || gotMode != "fast" { + t.Fatalf("Flag(mode) = (%q, %v)", gotMode, gotModeOK) + } + if gotUnsetOK || gotUnset != "" { + t.Fatalf("unset flag = (%q, %v)", gotUnset, gotUnsetOK) + } +} + +func TestInjectedOutputCapture(t *testing.T) { + var stdout, stderr bytes.Buffer + out := NewOutput(strings.NewReader(""), &stdout, &stderr) + out.Info("heads up") + out.Success("done") + out.Warning("careful") + out.Error("boom") + out.Printf("plain %s\n", "line") + if !strings.Contains(stdout.String(), "heads up") || !strings.Contains(stdout.String(), "done") || !strings.Contains(stdout.String(), "careful") { + t.Fatalf("stdout = %q", stdout.String()) + } + if !strings.Contains(stdout.String(), "plain line") { + t.Fatalf("Printf missing from stdout: %q", stdout.String()) + } + if !strings.Contains(stderr.String(), "boom") { + t.Fatalf("Error should go to stderr, got %q", stderr.String()) + } + if strings.Contains(stdout.String(), "boom") { + t.Fatalf("Error leaked to stdout: %q", stdout.String()) + } + if strings.Contains(stdout.String()+stderr.String(), "\x1b[") { + t.Fatalf("non-tty messages have ansi: stdout=%q stderr=%q", stdout.String(), stderr.String()) + } +} + +func TestNonTTYSpinnerError(t *testing.T) { + var buf bytes.Buffer + out := NewOutput(strings.NewReader(""), &buf, &buf) + err := out.Spinner("building", func() error { return errors.New("compile failed") }) + if err == nil || err.Error() != "compile failed" { + t.Fatalf("spinner err = %v", err) + } + if got := buf.String(); got != "[...] building\n" { + t.Fatalf("spinner = %q", got) + } +} + +func TestNonTTYProgressSkipsIntraDecile(t *testing.T) { + var buf bytes.Buffer + out := NewOutput(strings.NewReader(""), &buf, &buf) + if err := out.Progress(20, func(p Progress) error { + p.Advance(1) // 5% + p.Advance(1) // 10% + p.Advance(1) // 15% + return nil + }); err != nil { + t.Fatal(err) + } + got := buf.String() + if !strings.Contains(got, "[2/20] 10%") { + t.Fatalf("missing 10%% step in %q", got) + } + if strings.Contains(got, "[1/20]") || strings.Contains(got, "[3/20]") { + t.Fatalf("intra-decile progress leaked: %q", got) + } +} + func TestHelpUsesSharedAdapter(t *testing.T) { var buf bytes.Buffer root, err := NewRoot("hello", []Command{{ diff --git a/bonfire/prompts_test.go b/bonfire/prompts_test.go index 733a247..e4f6009 100644 --- a/bonfire/prompts_test.go +++ b/bonfire/prompts_test.go @@ -2,6 +2,8 @@ package bonfire import ( "bytes" + "context" + "errors" "io" "strings" "testing" @@ -73,6 +75,58 @@ func TestSecretReadsPlainStdinLine(t *testing.T) { } } +func TestChoiceEOFUsesDefault(t *testing.T) { + var buf bytes.Buffer + out := NewOutput(strings.NewReader(""), &buf, &buf) + got, err := out.Choice("pick", []string{"a", "b", "c"}, 2) + if err != nil { + t.Fatal(err) + } + if got != "c" { + t.Fatalf("choice eof = %q", got) + } +} + +func TestChoiceEmptyOptionsError(t *testing.T) { + var buf bytes.Buffer + out := NewOutput(strings.NewReader("1\n"), &buf, &buf) + _, err := out.Choice("pick", nil, 0) + if err == nil { + t.Fatal("expected empty choice error") + } +} + +func TestSecretNotLeakedOnCommandError(t *testing.T) { + var stdout, stderr bytes.Buffer + root, err := NewRootIO("app", []Command{{ + Name: "auth:login", + Description: "login", + Run: func(ctx context.Context, in Input, out Output) error { + secret, err := out.Secret("token") + if err != nil { + return err + } + if secret == "" { + return errors.New("empty token") + } + out.Error("login failed") + return errors.New("login failed") + }, + }}, strings.NewReader("s3cret\n"), &stdout, &stderr) + if err != nil { + t.Fatal(err) + } + root.SetArgs([]string{"auth:login"}) + runErr := root.Execute() + if runErr == nil { + t.Fatal("expected command error") + } + combined := stdout.String() + stderr.String() + runErr.Error() + if strings.Contains(combined, "s3cret") { + t.Fatalf("secret leaked into streams: stdout=%q stderr=%q err=%v", stdout.String(), stderr.String(), runErr) + } +} + func TestClosedStdinDoesNotHang(t *testing.T) { var buf bytes.Buffer out := NewOutput(io.NopCloser(strings.NewReader("")), &buf, &buf) diff --git a/examples/hello/hello_test.go b/examples/hello/hello_test.go index ae4f9da..007ff0e 100644 --- a/examples/hello/hello_test.go +++ b/examples/hello/hello_test.go @@ -104,6 +104,15 @@ func TestBuiltBinaryGreeterHello(t *testing.T) { assertGreeting(t, got, want) } +func TestBuiltBinaryUnknownCommandExitsNonZero(t *testing.T) { + runSummerBuild(t) + cmd := exec.Command("./bin/hello", "does:not-exist") + out, err := cmd.CombinedOutput() + if err == nil { + t.Fatalf("expected non-zero exit, output:\n%s", out) + } +} + func assertGreeting(t *testing.T, got, want string) { t.Helper() if !strings.Contains(got, "plugin\tstatus") || !strings.Contains(got, "golem15.greeter\tactive") { diff --git a/internal/build/build_test.go b/internal/build/build_test.go index 261de99..761800f 100644 --- a/internal/build/build_test.go +++ b/internal/build/build_test.go @@ -263,6 +263,65 @@ func TestAddPluginRejectsPathTraversal(t *testing.T) { } } +func TestParseManifestRejectsDuplicateModule(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "dupmod.yaml") + write(t, path, "module: example.com/app\nbinary: app\nplugins:\n - id: a.b\n module: example.com/one\n - id: a.c\n module: example.com/one\n") + if _, err := LoadManifest(path); err == nil || !strings.Contains(err.Error(), "example.com/one") { + t.Fatalf("want duplicate module error, got %v", err) + } +} + +func TestMakePluginRejectsPathTraversalAndShellMeta(t *testing.T) { + dir := t.TempDir() + write(t, filepath.Join(dir, "summer.yaml"), "module: example.com/app\nbinary: app\nplugins:\n") + write(t, filepath.Join(dir, "go.mod"), "module example.com/app\n\ngo 1.27.0\n") + for _, id := range []string{ + "golem15.demo/../tmp", + "golem15.demo;rm", + `golem15.demo$(x)`, + "golem15.demo`x`", + "/tmp.evil", + "..evil.plugin", + } { + if _, err := MakePlugin(t.Context(), dir, id); err == nil { + t.Fatalf("id %q: want error", id) + } + } +} + +func TestBuiltHelloFailsOnInvalidRequires(t *testing.T) { + dir := copyHelloApp(t) + path := filepath.Join(dir, "plugins", "greeter", "plugin.go") + src, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + patched := bytes.ReplaceAll(src, []byte(`return []string{"golem15.hello"}`), []byte(`return []string{"golem15.hello", "golem15.missing"}`)) + if bytes.Equal(src, patched) { + t.Fatal("failed to patch greeter Requires") + } + if err := os.WriteFile(path, patched, 0o644); err != nil { + t.Fatal(err) + } + + var buf bytes.Buffer + if err := App(t.Context(), dir, &buf); err != nil { + t.Fatalf("build should succeed, got %v\n%s", err, buf.String()) + } + bin := filepath.Join(dir, "bin", "hello") + cmd := exec.CommandContext(t.Context(), bin, "greeter:hello") + cmd.Dir = dir + out, err := cmd.CombinedOutput() + if err == nil { + t.Fatalf("expected non-zero exit for missing Requires, output:\n%s", out) + } + msg := string(out) + if !strings.Contains(msg, "golem15.greeter") || !strings.Contains(msg, "golem15.missing") { + t.Fatalf("error should name both plugin IDs, got %q", msg) + } +} + func TestParseManifestRejectsUppercaseID(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "bad.yaml") diff --git a/internal/dev/watch_test.go b/internal/dev/watch_test.go index 44ab3d7..f09221a 100644 --- a/internal/dev/watch_test.go +++ b/internal/dev/watch_test.go @@ -9,17 +9,37 @@ import ( "os/exec" "path/filepath" "strings" + "sync" "sync/atomic" "syscall" "testing" "time" + + "git.golem15.com/golem15/summercms/internal/build" ) +type safeBuffer struct { + mu sync.Mutex + b bytes.Buffer +} + +func (s *safeBuffer) Write(p []byte) (int, error) { + s.mu.Lock() + defer s.mu.Unlock() + return s.b.Write(p) +} + +func (s *safeBuffer) String() string { + s.mu.Lock() + defer s.mu.Unlock() + return s.b.String() +} + func TestWatchRebuildsOnSourceEdit(t *testing.T) { dir := t.TempDir() writeWatchApp(t, dir) - var out bytes.Buffer + var out safeBuffer var builds atomic.Int32 var starts atomic.Int32 @@ -90,7 +110,7 @@ func TestWatchKeepsChildOnBuildFailure(t *testing.T) { dir := t.TempDir() writeWatchApp(t, dir) - var out bytes.Buffer + var out safeBuffer var builds atomic.Int32 var starts atomic.Int32 var pid atomic.Int32 @@ -157,6 +177,263 @@ func TestWatchKeepsChildOnBuildFailure(t *testing.T) { t.Fatal("child still running after cancel") } +func TestWatchDebouncesRapidEdits(t *testing.T) { + dir := t.TempDir() + writeWatchApp(t, dir) + + var out safeBuffer + var builds atomic.Int32 + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + + opts := Options{ + Debounce: 80 * time.Millisecond, + Build: func(ctx context.Context, appDir string, w io.Writer) error { + builds.Add(1) + return nil + }, + Start: func(ctx context.Context, binPath string, stdout, stderr io.Writer) (*exec.Cmd, error) { + cmd := exec.Command("sleep", "30") + if err := cmd.Start(); err != nil { + return nil, err + } + return cmd, nil + }, + } + done := make(chan error, 1) + go func() { done <- watch(ctx, dir, &out, opts) }() + waitUntil(t, "initial build", func() bool { return builds.Load() == 1 }) + + for i := 0; i < 5; i++ { + if err := os.WriteFile(filepath.Join(dir, "plugin.go"), []byte(fmt.Sprintf("package p\n// %d\n", i)), 0o644); err != nil { + t.Fatal(err) + } + time.Sleep(10 * time.Millisecond) + } + waitUntil(t, "debounced rebuild", func() bool { return builds.Load() >= 2 }) + time.Sleep(150 * time.Millisecond) + if builds.Load() != 2 { + t.Fatalf("rapid edits should coalesce, builds=%d", builds.Load()) + } + cancel() + select { + case <-done: + case <-time.After(3 * time.Second): + t.Fatal("watch did not exit") + } +} + +func TestWatchIgnoresBinAndTmp(t *testing.T) { + dir := t.TempDir() + writeWatchApp(t, dir) + if err := os.MkdirAll(filepath.Join(dir, "bin"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(filepath.Join(dir, "tmp"), 0o755); err != nil { + t.Fatal(err) + } + + var out safeBuffer + var builds atomic.Int32 + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + opts := Options{ + Debounce: 40 * time.Millisecond, + Build: func(ctx context.Context, appDir string, w io.Writer) error { + builds.Add(1) + return nil + }, + Start: func(ctx context.Context, binPath string, stdout, stderr io.Writer) (*exec.Cmd, error) { + cmd := exec.Command("sleep", "30") + if err := cmd.Start(); err != nil { + return nil, err + } + return cmd, nil + }, + } + done := make(chan error, 1) + go func() { done <- watch(ctx, dir, &out, opts) }() + waitUntil(t, "initial build", func() bool { return builds.Load() == 1 }) + + if err := os.WriteFile(filepath.Join(dir, "bin", "hello.go"), []byte("package main\n"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "tmp", "scratch.go"), []byte("package tmp\n"), 0o644); err != nil { + t.Fatal(err) + } + time.Sleep(200 * time.Millisecond) + if builds.Load() != 1 { + t.Fatalf("bin/tmp edits triggered rebuild: builds=%d", builds.Load()) + } + cancel() + select { + case <-done: + case <-time.After(3 * time.Second): + t.Fatal("watch did not exit") + } +} + +func TestWatchHelloWorkspaceRebuildLatency(t *testing.T) { + dir := copyHelloApp(t) + var out safeBuffer + var builds atomic.Int32 + var starts atomic.Int32 + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + + opts := Options{ + Debounce: 80 * time.Millisecond, + Build: func(ctx context.Context, appDir string, w io.Writer) error { + builds.Add(1) + if err := build.App(ctx, appDir, w); err != nil { + return err + } + return nil + }, + Start: func(ctx context.Context, binPath string, stdout, stderr io.Writer) (*exec.Cmd, error) { + starts.Add(1) + cmd := exec.Command("sleep", "30") + if err := cmd.Start(); err != nil { + return nil, err + } + return cmd, nil + }, + } + + done := make(chan error, 1) + go func() { done <- watch(ctx, dir, &out, opts) }() + waitUntilTimeout(t, 60*time.Second, "initial real rebuild", func() bool { return starts.Load() == 1 }) + if builds.Load() != 1 { + t.Fatalf("initial builds = %d", builds.Load()) + } + if !rebuildLinePresent(out.String()) { + t.Fatalf("missing rebuild latency line after initial build:\n%s", out.String()) + } + + plugin := filepath.Join(dir, "plugins", "greeter", "plugin.go") + src, err := os.ReadFile(plugin) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(plugin, append(src, []byte("\n// watch-edit\n")...), 0o644); err != nil { + t.Fatal(err) + } + waitUntilTimeout(t, 60*time.Second, "rebuild after source edit", func() bool { return starts.Load() == 2 }) + got := out.String() + if strings.Count(got, "rebuild:") < 2 { + t.Fatalf("want rebuild latency lines after restart, got %q", got) + } + if !rebuildLinePresent(got) { + t.Fatalf("rebuild line missing duration:\n%s", got) + } + + if err := os.WriteFile(filepath.Join(dir, "main.go"), []byte("package main\n// generated\n"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "plugins.gen.go"), []byte("package main\n// generated\n"), 0o644); err != nil { + t.Fatal(err) + } + time.Sleep(400 * time.Millisecond) + if starts.Load() != 2 || builds.Load() != 2 { + t.Fatalf("generated-file edits looped: starts=%d builds=%d", starts.Load(), builds.Load()) + } + + cancel() + select { + case err := <-done: + if err != nil && err != context.Canceled { + t.Fatalf("watch exit: %v", err) + } + case <-time.After(5 * time.Second): + t.Fatal("watch did not exit on cancel") + } +} + +func rebuildLinePresent(s string) bool { + for _, line := range strings.Split(s, "\n") { + line = strings.TrimSpace(line) + if strings.HasPrefix(line, "rebuild:") && len(strings.TrimSpace(strings.TrimPrefix(line, "rebuild:"))) > 0 { + return true + } + } + return false +} + +func waitUntilTimeout(t *testing.T, d time.Duration, name string, ok func() bool) { + t.Helper() + deadline := time.Now().Add(d) + for time.Now().Before(deadline) { + if ok() { + return + } + time.Sleep(25 * time.Millisecond) + } + t.Fatalf("timed out waiting for %s", name) +} + +func copyHelloApp(t *testing.T) string { + t.Helper() + src, err := filepath.Abs(filepath.Join("..", "..", "examples", "hello")) + if err != nil { + t.Fatal(err) + } + framework, err := filepath.Abs(filepath.Join("..", "..")) + if err != nil { + t.Fatal(err) + } + dst := t.TempDir() + if err := filepath.WalkDir(src, func(path string, d os.DirEntry, err error) error { + if err != nil { + return err + } + rel, err := filepath.Rel(src, path) + if err != nil { + return err + } + if rel == "bin" || strings.HasPrefix(rel, "bin"+string(os.PathSeparator)) { + if d.IsDir() { + return filepath.SkipDir + } + return nil + } + target := filepath.Join(dst, rel) + if d.IsDir() { + return os.MkdirAll(target, 0o755) + } + data, err := os.ReadFile(path) + if err != nil { + return err + } + if filepath.Base(path) == "go.mod" { + data = rewriteFrameworkReplace(data, framework) + } + if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil { + return err + } + return os.WriteFile(target, data, 0o644) + }); err != nil { + t.Fatal(err) + } + return dst +} + +func rewriteFrameworkReplace(data []byte, framework string) []byte { + const module = "git.golem15.com/golem15/summercms" + lines := strings.Split(string(data), "\n") + for i, line := range lines { + trimmed := strings.TrimSpace(line) + switch { + case strings.HasPrefix(trimmed, "replace "+module+" =>"): + indent := line[:len(line)-len(strings.TrimLeft(line, " \t"))] + lines[i] = indent + "replace " + module + " => " + framework + case strings.HasPrefix(trimmed, module+" =>"): + indent := line[:len(line)-len(strings.TrimLeft(line, " \t"))] + lines[i] = indent + module + " => " + framework + } + } + return []byte(strings.Join(lines, "\n")) +} + func writeWatchApp(t *testing.T, dir string) { t.Helper() write(t, filepath.Join(dir, "summer.yaml"), "module: example.com/app\nbinary: hello\nplugins:\n - id: a.b\n module: example.com/app/plugins/demo\n") diff --git a/scripts/check-phase1.sh b/scripts/check-phase1.sh new file mode 100755 index 0000000..0c71df2 --- /dev/null +++ b/scripts/check-phase1.sh @@ -0,0 +1,34 @@ +#!/usr/bin/env bash +# Repeatable Phase 1 verification: vet, test, and race across every workspace module, +# plus a built-binary integration check of examples/hello. +set -euo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$ROOT" + +run_module() { + local name="$1" + local dir="$2" + echo "==> ${name} (${dir})" + ( + cd "$dir" + go vet ./... + go test ./... + go test -race ./... + ) +} + +run_module "root" "." +run_module "hello app" "examples/hello" +run_module "base plugin" "examples/hello/plugins/base" +run_module "greeter plugin" "examples/hello/plugins/greeter" +run_module "optional plugin" "examples/hello/plugins/optional" + +echo "==> built-binary integration (examples/hello)" +( + cd examples/hello + go run ../../cmd/summer build + ./bin/hello greeter:hello +) + +echo "phase1 check passed" From bee03bd54cdd70b35f0042de603a0192c641a40a Mon Sep 17 00:00:00 2001 From: Jakub Zych Date: Wed, 16 Sep 2026 14:14:05 +0200 Subject: [PATCH 3/4] docs(01-04): record phase 1 validation evidence - Mark KERN-01..09 and CLI-01 automated checks passed - Set nyquist_compliant after scripts/check-phase1.sh succeeded --- .../01-VALIDATION.md | 64 +++++++++---------- 1 file changed, 32 insertions(+), 32 deletions(-) diff --git a/.planning/phases/01-framework-kernel-foundation/01-VALIDATION.md b/.planning/phases/01-framework-kernel-foundation/01-VALIDATION.md index 4839e18..3ef6f76 100644 --- a/.planning/phases/01-framework-kernel-foundation/01-VALIDATION.md +++ b/.planning/phases/01-framework-kernel-foundation/01-VALIDATION.md @@ -1,9 +1,9 @@ --- phase: 01 slug: framework-kernel-foundation -status: draft -nyquist_compliant: false -wave_0_complete: false +status: passing +nyquist_compliant: true +wave_0_complete: true created: 2026-09-16 --- @@ -30,37 +30,37 @@ created: 2026-09-16 | Requirement | Test type | Automated command or assertion | Initial status | |---|---|---|---| -| KERN-01 | unit + integration | Config precedence and typed decode tests; hello binary prints env-overlay value | Pending | -| KERN-02 | unit + integration | Reordered Register/Boot trace, missing dependency, cycle and duplicate tests | Pending | -| KERN-03 | compile + unit | Hello plugins satisfy optional interfaces; type-assertion discovery | Pending | -| KERN-04 | integration | Stable codegen, `plugin:add`, `go.work`, built hello app boot | Pending | -| KERN-05 | unit | Absent optional plugin returns false; present service lookup returns typed value | Pending | -| KERN-06 | unit + race | Three dispatch modes, priority, stable ties, errors and panic recovery | Pending | -| KERN-07 | unit + race | Two app contexts remain isolated; request values passed only via `context.Context` | Pending | -| KERN-08 | unit | Interface service publish and typed lookup `(value, ok)` | Pending | -| KERN-09 | integration | Temp app source edit triggers one debounced rebuild and restart, latency line captured | Pending | -| CLI-01 | unit + integration | Plugin command discovery, injected output, non-TTY spinner/progress/table/prompt behavior | Pending | +| KERN-01 | unit + integration | Config precedence and typed decode tests; hello binary prints env-overlay value | Passed | +| KERN-02 | unit + integration | Reordered Register/Boot trace, missing dependency, cycle and duplicate tests | Passed | +| KERN-03 | compile + unit | Hello plugins satisfy optional interfaces; type-assertion discovery | Passed | +| KERN-04 | integration | Stable codegen, `plugin:add`, `go.work`, built hello app boot | Passed | +| KERN-05 | unit | Absent optional plugin returns false; present service lookup returns typed value | Passed | +| KERN-06 | unit + race | Three dispatch modes, priority, stable ties, errors and panic recovery | Passed | +| KERN-07 | unit + race | Two app contexts remain isolated; request values passed only via `context.Context` | Passed | +| KERN-08 | unit | Interface service publish and typed lookup `(value, ok)` | Passed | +| KERN-09 | integration | Temp app source edit triggers one debounced rebuild and restart, latency line captured | Passed | +| CLI-01 | unit + integration | Plugin command discovery, injected output, non-TTY spinner/progress/table/prompt behavior | Passed | ## Per-Task Verification Map | Task ID | Plan | Wave | Requirements | Automated check | Status | |---|---|---|---|---|---| -| 01-01-01 | 01 | 1 | KERN-01/02/03/04, CLI-01 | Root and hello `go vet ./...` + `go test ./...` | Pending | -| 01-01-02 | 01 | 1 | KERN-04, CLI-01 | Same checks plus `summer build` and built hello command | Pending | -| 01-02-01 | 02 | 2 | KERN-01/03 | `go test ./compass ./pact`; hello tests | Pending | -| 01-02-02 | 02 | 2 | KERN-02/03/05/08 | `go test ./party ./backpack ./pact`; hello tests | Pending | -| 01-02-03 | 02 | 2 | KERN-06/07 | `go test ./festival ./towel ./backpack`; hello tests | Pending | -| 01-03-01 | 03 | 3 | KERN-04 | `go test ./internal/build ./cmd/summer`; hello tests | Pending | -| 01-03-02 | 03 | 3 | CLI-01 | `go test ./bonfire ./cmd/summer`; hello tests | Pending | -| 01-03-03 | 03 | 3 | KERN-09 | `go test ./internal/dev ./internal/build ./cmd/summer`; hello tests | Pending | -| 01-04-01 | 04 | 4 | KERN-01/02/03/05/06/07/08 | `go test -race ./compass ./party ./backpack ./festival ./towel ./pact` | Pending | -| 01-04-02 | 04 | 4 | KERN-04/09, CLI-01 | `bash scripts/check-phase1.sh` | Pending | +| 01-01-01 | 01 | 1 | KERN-01/02/03/04, CLI-01 | Root and hello `go vet ./...` + `go test ./...` | Passed | +| 01-01-02 | 01 | 1 | KERN-04, CLI-01 | Same checks plus `summer build` and built hello command | Passed | +| 01-02-01 | 02 | 2 | KERN-01/03 | `go test ./compass ./pact`; hello tests | Passed | +| 01-02-02 | 02 | 2 | KERN-02/03/05/08 | `go test ./party ./backpack ./pact`; hello tests | Passed | +| 01-02-03 | 02 | 2 | KERN-06/07 | `go test ./festival ./towel ./backpack`; hello tests | Passed | +| 01-03-01 | 03 | 3 | KERN-04 | `go test ./internal/build ./cmd/summer`; hello tests | Passed | +| 01-03-02 | 03 | 3 | CLI-01 | `go test ./bonfire ./cmd/summer`; hello tests | Passed | +| 01-03-03 | 03 | 3 | KERN-09 | `go test ./internal/dev ./internal/build ./cmd/summer`; hello tests | Passed | +| 01-04-01 | 04 | 4 | KERN-01/02/03/05/06/07/08 | `go test -race ./compass ./party ./backpack ./festival ./towel ./pact` | Passed | +| 01-04-02 | 04 | 4 | KERN-04/09, CLI-01 | `bash scripts/check-phase1.sh` | Passed | ## Wave 0 Requirements -- [ ] First implementation slice creates `examples/hello`, its `go.mod`, and a root `go.work` that names every example module. -- [ ] First implementation slice adds smoke tests for generated app boot and the initial plugin command. -- [ ] Final plan expands unit coverage; it does not substitute for executable checks during earlier work. +- [x] First implementation slice creates `examples/hello`, its `go.mod`, and a root `go.work` that names every example module. +- [x] First implementation slice adds smoke tests for generated app boot and the initial plugin command. +- [x] Final plan expands unit coverage; it does not substitute for executable checks during earlier work. ## Manual-Only Verifications @@ -71,10 +71,10 @@ created: 2026-09-16 ## Validation Sign-Off -- [ ] Every plan task has an automated verification or an explicit Wave 0 dependency. -- [ ] No three consecutive implementation tasks lack automated feedback. -- [ ] Root, hello app and three plugin modules run `go vet`, tests and race tests. -- [ ] No watch-mode flags in CI commands. -- [ ] Set `nyquist_compliant: true` after all mapped checks exist and pass. +- [x] Every plan task has an automated verification or an explicit Wave 0 dependency. +- [x] No three consecutive implementation tasks lack automated feedback. +- [x] Root, hello app and three plugin modules run `go vet`, tests and race tests. +- [x] No watch-mode flags in CI commands. +- [x] Set `nyquist_compliant: true` after all mapped checks exist and pass. -**Approval:** pending plan verification +**Approval:** `bash scripts/check-phase1.sh` passed 2026-09-16 (root, hello app, base, greeter, optional; built `./bin/hello greeter:hello`). Manual TTY rendering remains optional. From d0ed25cd372744a5afa65f0bafb66deb7727c30a Mon Sep 17 00:00:00 2001 From: Jakub Zych Date: Wed, 16 Sep 2026 14:15:09 +0200 Subject: [PATCH 4/4] docs(01-04): complete kernel unit and integration test plan - Record coverage, check-phase1.sh result, and measured hello rebuild - Document race-buffer and pact-test deviations --- .../01-04-SUMMARY.md | 179 ++++++++++++++++++ 1 file changed, 179 insertions(+) create mode 100644 .planning/phases/01-framework-kernel-foundation/01-04-SUMMARY.md diff --git a/.planning/phases/01-framework-kernel-foundation/01-04-SUMMARY.md b/.planning/phases/01-framework-kernel-foundation/01-04-SUMMARY.md new file mode 100644 index 0000000..3d50757 --- /dev/null +++ b/.planning/phases/01-framework-kernel-foundation/01-04-SUMMARY.md @@ -0,0 +1,179 @@ +--- +phase: 01-framework-kernel-foundation +plan: 04 +subsystem: testing +tags: [go, unit-tests, race, watch, cli, validation] + +requires: + - phase: 01-framework-kernel-foundation + provides: Kernel packages, hello workspace, summer build/dev, bonfire output +provides: + - Behavioral unit and race coverage for KERN-01 through KERN-09 and CLI-01 + - Repeatable scripts/check-phase1.sh across root, hello, base, greeter, optional + - Nyquist-compliant VALIDATION.md with passing automated checks +affects: [02, 03, verify-work] + +tech-stack: + added: [] + patterns: + - Table-driven contract tests over implementation-structure asserts + - Nested-module check script runs vet/test/race per go.work member + - Watch tests inject Build/Start plus one real hello workspace rebuild + +key-files: + created: + - pact/capabilities_test.go + - scripts/check-phase1.sh + modified: + - compass/config_test.go + - party/registry_test.go + - backpack/services_test.go + - festival/bus_test.go + - towel/context_test.go + - bonfire/output_test.go + - bonfire/prompts_test.go + - internal/build/build_test.go + - internal/dev/watch_test.go + - examples/hello/hello_test.go + - .planning/phases/01-framework-kernel-foundation/01-VALIDATION.md + +key-decisions: + - "Cover contract branches rather than an arbitrary coverage percentage" + - "Watch tests use a mutex-safe buffer so go test -race can read captured output" + - "VALIDATION.md is a docs commit separate from test code per CLAUDE.md" + +patterns-established: + - "Pattern: scripts/check-phase1.sh is the phase-wide verification command" + - "Pattern: hello copies rewrite framework replace to an absolute path for temp-dir builds" + +requirements-completed: [KERN-01, KERN-02, KERN-03, KERN-04, KERN-05, KERN-06, KERN-07, KERN-08, KERN-09, CLI-01] + +duration: 11min +completed: 2026-09-16 +--- + +# Phase 1 Plan 4: Kernel Unit and Integration Tests Summary + +**Phase-wide `scripts/check-phase1.sh` with race-enabled contract tests for config precedence, plugin lifecycle, typed events, non-TTY CLI, and a measured hello workspace rebuild** + +## Performance + +- **Duration:** 11 min +- **Started:** 2026-09-16T12:03:03Z +- **Completed:** 2026-09-16T12:14:21Z +- **Tasks:** 2 +- **Files modified:** 13 + +## Accomplishments + +- Expanded kernel smoke tests into source-to-observable assertions for all six compass layers, malformed YAML, snake_case env keys, `.env` non-override, Set/Persist/Reload, concurrent reads, plugin duplicate/missing/cycle, HasConfig/HasCommands discovery, isolated backpack services, three festival dispatch modes, and nested towel context +- Covered namespaced command flags/args, injected output, non-TTY spinner/progress/table/prompts, `NO_COLOR`/`FORCE_COLOR`/`TERM=dumb`, closed stdin, secret non-leak, `make:plugin`/`plugin:add`, malicious IDs, invalid Requires on a built hello binary, debounce/ignore/fail/reap watch hooks, and one real fsnotify hello rebuild that prints `rebuild: ` +- Added `scripts/check-phase1.sh` (root, hello app, base, greeter, optional) and signed VALIDATION.md `nyquist_compliant: true` after the script passed + +## Task Commits + +Each task was committed atomically: + +1. **Task 1: Cover config, lifecycle, services, events and context** - `a43c734` (test) +2. **Task 2: Cover tool, output, watch loop and every workspace module** - `dc7997e` (test) +3. **Task 2 docs: Record phase 1 validation evidence** - `bee03bd` (docs) + +**Plan metadata:** pending (this file) + +## Files Created/Modified + +- `compass/config_test.go` - table-driven precedence, malformed YAML, snake_case env, Persist/Reload, concurrent reads +- `party/registry_test.go` - reordered manifest, duplicate/missing IDs, HasConfig/HasCommands type assertions +- `backpack/services_test.go` - two-app isolation, nil publish, concurrent lookup +- `festival/bus_test.go` - concurrent buses, panic payload omission, collect/until-handled edges +- `towel/context_test.go` - nested isolation, nil context, concurrent accessors +- `pact/capabilities_test.go` - HasConfig/HasCommands/OptionalMessage discovery +- `bonfire/output_test.go` / `prompts_test.go` - flags/args, injected streams, secret non-leak, closed stdin +- `internal/build/build_test.go` - duplicate modules, path/shell-meta IDs, built hello invalid Requires +- `internal/dev/watch_test.go` - debounce, ignored bin/tmp, real hello rebuild latency line +- `examples/hello/hello_test.go` - built binary unknown-command non-zero exit +- `scripts/check-phase1.sh` - vet/test/race per workspace module plus `./bin/hello greeter:hello` +- `.planning/phases/01-framework-kernel-foundation/01-VALIDATION.md` - passing map, `nyquist_compliant: true` + +## Per-package coverage (contract branches) + +| Package | Coverage | +|---------|----------| +| compass | 80.3% | +| party | 79.3% | +| backpack | 84.0% | +| festival | 94.5% | +| towel | 100.0% | +| pact | no statements (interfaces only; tests assert type discovery) | + +## Measured rebuild + +- `scripts/check-phase1.sh` `summer build` of examples/hello: **built hello in 80ms** (warm cache). +- `TestWatchHelloWorkspaceRebuildLatency` observed `rebuild: ` after a greeter source edit and a child restart; no latency threshold was asserted. Generated `main.go` / `plugins.gen.go` edits did not loop. + +## Decisions Made + +- Cover observable contracts (precedence winners, error IDs, captured CLI bytes) rather than chasing a percentage +- Keep watch production writers as-is; serialize test buffers so `-race` can inspect output +- Split VALIDATION.md into a docs commit because CLAUDE.md forbids mixing planning docs with code + +## Deviations from Plan + +### Auto-fixed Issues + +**1. [Rule 1 - Bug] Watch tests raced on bytes.Buffer under -race** +- **Found during:** Task 2 (`go test -race ./internal/dev`) +- **Issue:** The watch loop writes captured output while the test goroutine called `Buffer.String()` +- **Fix:** Added a mutex-wrapped `safeBuffer` used by all concurrent watch tests +- **Files modified:** `internal/dev/watch_test.go` +- **Verification:** `go test -race ./internal/dev` exits 0 +- **Committed in:** `dc7997e` (Task 2) + +**2. [Rule 2 - Missing Critical] Pact capability discovery tests** +- **Found during:** Task 1 (KERN-03 HasConfig/HasCommands assertions; verify includes `./pact`) +- **Issue:** Plan file list omitted `pact/capabilities_test.go` while KERN-03 requires type-assertion discovery +- **Fix:** Added compile-time/runtime discovery tests for HasConfig, HasCommands, OptionalMessage +- **Files modified:** `pact/capabilities_test.go` +- **Verification:** `go test -race ./pact` exits 0 +- **Committed in:** `a43c734` (Task 1) + +**3. [CLAUDE.md - Commit split] VALIDATION.md committed separately from test code** +- **Found during:** Task 2 +- **Issue:** Task files mixed tests with a planning doc; CLAUDE.md requires planning docs and code in separate commits +- **Fix:** `dc7997e` for tests/script, `bee03bd` for VALIDATION.md +- **Files modified:** `.planning/phases/01-framework-kernel-foundation/01-VALIDATION.md` +- **Verification:** two commits, no co-author trailers +- **Committed in:** `bee03bd` + +--- + +**Total deviations:** 3 auto-fixed (1 bug, 1 missing critical, 1 commit-policy) +**Impact on plan:** Required for green `-race`, KERN-03 evidence, and CLAUDE.md. No production API change. + +## Issues Encountered + +- Nested plugin modules `base` and `optional` have no test files; `go test` reports `[no test files]` and still exits 0. Greeter has `plugin_test.go`. +- `go.work.sum` remains untracked in this worktree (pre-existing, not part of the plan). + +## Authentication Gates + +None. + +## User Setup Required + +None - no external service configuration required. + +## Next Phase Readiness + +Phase 1 kernel contracts have a repeatable race-enabled check. Ready for verify-work and later phases that depend on compass/party/backpack/festival/bonfire/`summer build`/`summer dev`. Do not add HTTP/DB/auth here. + +## Self-Check: PASSED + +- Created files exist: `pact/capabilities_test.go`, `scripts/check-phase1.sh`, this SUMMARY +- Commits `a43c734`, `dc7997e`, `bee03bd` exist on `worktree-agent-01-04` +- `bash scripts/check-phase1.sh` exited 0 and named root, hello app, base, greeter, optional +- STATE.md and ROADMAP.md were not updated in this worktree + +--- +*Phase: 01-framework-kernel-foundation* +*Completed: 2026-09-16*