package daemon import ( "context" "log/slog" "os" "testing" "time" "github.com/jackc/pgx/v5/pgxpool" "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/domain/binding" "github.com/samcharles93/archie-core/internal/domain/eventtype" "github.com/samcharles93/archie-core/internal/domain/mapping" "github.com/samcharles93/archie-core/internal/domain/storecontract" "github.com/samcharles93/archie-core/internal/domain/workflow" "github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/infrastructure/postgres" "github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore" ) // Test 30: an armed binding + an authenticated capture creates a task // whose provenance points back at the binding (and its version), and // records a dispatch row in the dedup ledger. func TestDispatchBindingsCreatesTaskFromArmedCapture(t *testing.T) { s := openDispatchTestStore(t) mappingID := seedMapping(t, s, "sentry", mapping.Field{Name: "title", Path: "title", Type: mapping.TypeString, Required: true}) bindingID, bindingVersion := seedArmedBinding(t, s, "sentry", mappingID) seedCapture(t, s, "sentry", true, `{"title":"hello"}`) d := newDispatchDaemon(t, s) d.dispatchBindings(t.Context()) tasks, err := s.Tasks(t.Context(), 10) if err != nil { t.Fatalf("Tasks: %v", err) } if len(tasks) != 1 { t.Fatalf("Tasks len = %d, want 1", len(tasks)) } got := tasks[0] if got.BindingID != bindingID { t.Errorf("task.BindingID = %q, want %q", got.BindingID, bindingID) } if got.BindingVersion != bindingVersion { t.Errorf("task.BindingVersion = %d, want %d", got.BindingVersion, bindingVersion) } if got.Source != workflow.SourceChat { t.Errorf("task.Source = %q, want %q", got.Source, workflow.SourceChat) } if got.Status != workflow.StatusQueued { t.Errorf("task.Status = %q, want %q", got.Status, workflow.StatusQueued) } assertDispatchRecorded(t, s, bindingID) } // TestDispatchBindingsUsesBindingRepoPinWithMultipleConfiguredRepos is the // multi-repo fix: a binding that pins Owner/Repo dispatches to that // target even when the daemon has zero or several [[repos]] configured, // where resolveBindingRepo's old single-repo-only fallback would have // refused entirely. func TestDispatchBindingsUsesBindingRepoPinWithMultipleConfiguredRepos(t *testing.T) { s := openDispatchTestStore(t) mappingID := seedMapping(t, s, "sentry", mapping.Field{Name: "title", Path: "title", Type: mapping.TypeString, Required: true}) bindingID, _ := seedArmedBindingWithRepo(t, s, "sentry", mappingID, "acme", "widget") seedCapture(t, s, "sentry", true, `{"title":"hello"}`) d := newDispatchDaemonWithRepos(t, s, []config.Repo{ {Owner: "acme", Name: "widget"}, {Owner: "other-org", Name: "other-repo"}, }) d.dispatchBindings(t.Context()) tasks, err := s.Tasks(t.Context(), 10) if err != nil { t.Fatalf("Tasks: %v", err) } if len(tasks) != 1 { t.Fatalf("Tasks len = %d, want 1 (pinned binding must dispatch despite 2 configured repos)", len(tasks)) } if tasks[0].Owner != "acme" || tasks[0].Repo != "widget" { t.Fatalf("task owner/repo = %s/%s, want acme/widget (the binding's own pin, not a guess)", tasks[0].Owner, tasks[0].Repo) } assertDispatchRecorded(t, s, bindingID) } // TestDispatchBindingsRefusesUnpinnedBindingWithMultipleConfiguredRepos // pins the existing safety behaviour: a binding with no Owner/Repo pin // must still refuse to dispatch when the target repo is ambiguous, // exactly as it did before this field existed. func TestDispatchBindingsRefusesUnpinnedBindingWithMultipleConfiguredRepos(t *testing.T) { s := openDispatchTestStore(t) mappingID := seedMapping(t, s, "sentry", mapping.Field{Name: "title", Path: "title", Type: mapping.TypeString, Required: true}) seedArmedBinding(t, s, "sentry", mappingID) // no owner/repo pin seedCapture(t, s, "sentry", true, `{"title":"hello"}`) d := newDispatchDaemonWithRepos(t, s, []config.Repo{ {Owner: "acme", Name: "widget"}, {Owner: "other-org", Name: "other-repo"}, }) d.dispatchBindings(t.Context()) tasks, err := s.Tasks(t.Context(), 10) if err != nil { t.Fatalf("Tasks: %v", err) } if len(tasks) != 0 { t.Fatalf("Tasks len = %d, want 0 (an unpinned binding must still refuse an ambiguous target)", len(tasks)) } } // Test 31: the binding_dispatches ledger is the at-most-once // guarantee across cycles -- running dispatchBindings twice must // yield exactly one task even though the undispatched-captures query // keeps finding the capture on the second pass. func TestDispatchBindingsDoesNotDoubleDispatch(t *testing.T) { s := openDispatchTestStore(t) mappingID := seedMapping(t, s, "sentry", mapping.Field{Name: "title", Path: "title", Type: mapping.TypeString}) seedArmedBinding(t, s, "sentry", mappingID) seedCapture(t, s, "sentry", true, `{"title":"hello"}`) d := newDispatchDaemon(t, s) d.dispatchBindings(t.Context()) d.dispatchBindings(t.Context()) tasks, err := s.Tasks(t.Context(), 10) if err != nil { t.Fatalf("Tasks: %v", err) } if len(tasks) != 1 { t.Fatalf("after two cycles, Tasks len = %d, want 1 (ledger dedup)", len(tasks)) } } // Test 32: an unauthenticated capture can never spawn a task -- the // matcher refuses it regardless of source match (binding.Matcher.Matches // gates on authenticated, see docs/prds/webhook-intake-security.md). func TestDispatchBindingsSkipsUnauthenticatedCaptures(t *testing.T) { s := openDispatchTestStore(t) mappingID := seedMapping(t, s, "sentry", mapping.Field{Name: "title", Path: "title", Type: mapping.TypeString}) seedArmedBinding(t, s, "sentry", mappingID) seedCapture(t, s, "sentry", false, `{"title":"hello"}`) d := newDispatchDaemon(t, s) d.dispatchBindings(t.Context()) tasks, err := s.Tasks(t.Context(), 10) if err != nil { t.Fatalf("Tasks: %v", err) } if len(tasks) != 0 { t.Fatalf("unauthenticated capture spawned %d task(s), want 0", len(tasks)) } } // markUnsigned reports every undispatched capture as taken on an approved // unsigned source, which the legacy capture store cannot persist. type markUnsigned struct { storecontract.BindingDispatcher } func (m markUnsigned) ListUndispatchedCaptures(ctx context.Context, sources []string, limit int) ([]storecontract.CapturedEvent, error) { cs, err := m.BindingDispatcher.ListUndispatchedCaptures(ctx, sources, limit) for i := range cs { cs[i].Unsigned = true } return cs, err } // An event on an approved unsigned source dispatches without a signature, // and the task it starts carries an unsigned_event on its timeline. func TestDispatchBindingsDispatchesUnsignedCaptureAndMarksTimeline(t *testing.T) { s := openDispatchTestStore(t) mappingID := seedMapping(t, s, "fw", mapping.Field{Name: "title", Path: "title", Type: mapping.TypeString}) seedArmedBinding(t, s, "fw", mappingID) seedCapture(t, s, "fw", false, `{"title":"blocked"}`) d := newDispatchDaemon(t, s) d.BindingDispatcher = markUnsigned{d.BindingDispatcher} d.dispatchBindings(t.Context()) tasks, err := s.Tasks(t.Context(), 10) if err != nil || len(tasks) != 1 { t.Fatalf("Tasks = %d (err %v), want 1", len(tasks), err) } evs, err := s.TaskEvents(t.Context(), tasks[0].ID) if err != nil { t.Fatalf("TaskEvents: %v", err) } for _, e := range evs { if e.Kind == events.KindUnsignedEvent { return } } t.Fatalf("task timeline has no %s event: %+v", events.KindUnsignedEvent, evs) } // Test 33: a required field whose path is missing in the capture body // blocks the dispatch -- the failure path emits a // binding_dispatch_failure event and creates no task. func TestDispatchBindingsSkipsWhenResolveFails(t *testing.T) { s := openDispatchTestStore(t) mappingID := seedMapping(t, s, "sentry", mapping.Field{Name: "title", Path: "title", Type: mapping.TypeString, Required: true}) seedArmedBinding(t, s, "sentry", mappingID) // Body is missing the required "title" path. seedCapture(t, s, "sentry", true, `{"other":"value"}`) d := newDispatchDaemon(t, s) d.dispatchBindings(t.Context()) tasks, err := s.Tasks(t.Context(), 10) if err != nil { t.Fatalf("Tasks: %v", err) } if len(tasks) != 0 { t.Fatalf("required-field failure spawned %d task(s), want 0", len(tasks)) } events, err := s.EventsSince(t.Context(), "", 100) if err != nil { t.Fatalf("EventsSince: %v", err) } found := false for _, e := range events { if e.Kind == "binding_dispatch_failure" { found = true break } } if !found { t.Fatalf("binding_dispatch_failure event not published; got %d events", len(events)) } } // Test 34: with no armed bindings the loop is a no-op -- even with // authenticated captures sitting in the table. func TestDispatchBindingsNoOpWhenNoArmedBindings(t *testing.T) { s := openDispatchTestStore(t) // Capture is present, but no binding rows exist. seedCapture(t, s, "sentry", true, `{"title":"hello"}`) d := newDispatchDaemon(t, s) d.dispatchBindings(t.Context()) tasks, err := s.Tasks(t.Context(), 10) if err != nil { t.Fatalf("Tasks: %v", err) } if len(tasks) != 0 { t.Fatalf("no-armed-bindings loop spawned %d task(s), want 0", len(tasks)) } } // Test: dispatchBindings is a no-op when Bindings is nil -- the loop // must degrade silently rather than panic in legacy compositions. func TestDispatchBindingsNilBindingsIsNoOp(t *testing.T) { d := &Daemon{ Cfg: config.NewHolder(config.Config{}), Log: slog.New(slog.NewTextHandler(os.Stderr, nil)), } // Should not panic. d.dispatchBindings(t.Context()) } // TestDispatchBindingsNilDispatcherIsNoOp exercises the composition // gap the daemon field comments claim is safe: Bindings is set (so an // armed binding + a matching capture exist) but BindingDispatcher is // nil. Both fields are documented "optional: nil disables the // dispatch loop", so this must degrade silently rather than panic on // the nil-interface call to ListUndispatchedCaptures. func TestDispatchBindingsNilDispatcherIsNoOp(t *testing.T) { s := openDispatchTestStore(t) mappingID := seedMapping(t, s, "sentry", mapping.Field{Name: "title", Path: "title", Type: mapping.TypeString}) seedArmedBinding(t, s, "sentry", mappingID) seedCapture(t, s, "sentry", true, `{"title":"hello"}`) d := &Daemon{ Cfg: config.NewHolder(config.Config{Repos: []config.Repo{{Owner: "acme", Name: "widget"}}}), Store: s.Store, Mappings: s.EdaStore, Bindings: s.EdaStore, // BindingDispatcher and BindingTaskCreator intentionally nil. Log: slog.New(slog.NewTextHandler(os.Stderr, nil)), } // Should not panic. d.dispatchBindings(t.Context()) } // ── helpers ────────────────────────────────────────────────────── // dispatchStores pairs the two stores the dispatcher spans: the task store and // the event-capture store, so a seed helper reads as one handle. type dispatchStores struct { *pgstore.TaskDB EdaStore *postgres.EDA edaPool *pgxpool.Pool } func openDispatchTestStore(t *testing.T) *dispatchStores { t.Helper() s := pgstore.Open(t) t.Cleanup(func() { _ = s.Close() }) pool := pgstore.Pool(t) return &dispatchStores{TaskDB: s, EdaStore: postgres.NewEDA(pool, nil), edaPool: pool} } // seedMapping inserts a mapping with the given fields and returns its id. // The mapping belongs to a catch-all event type on sourceHint, so every // capture later inserted on that source is identified as its type and // dispatches. func seedMapping(t *testing.T, s *dispatchStores, sourceHint string, fields ...mapping.Field) string { t.Helper() eventTypeID, err := s.EdaStore.InsertEventType(t.Context(), eventtype.EventType{Source: sourceHint, Name: "any"}) if err != nil { t.Fatalf("InsertEventType: %v", err) } id, err := s.EdaStore.InsertMapping(t.Context(), mapping.Mapping{ Name: sourceHint + "-mapping", SourceHint: sourceHint, EventTypeID: eventTypeID, Fields: fields, }) if err != nil { t.Fatalf("InsertMapping: %v", err) } return id } // seedArmedBinding inserts a binding and approves it, matching the operator // flow an Approve button on the dashboard drives: InsertBinding stores // pending_approval and the only sanctioned armed transition is // ApproveBinding. func seedArmedBinding(t *testing.T, s *dispatchStores, source, mappingID string) (string, int) { t.Helper() return seedArmedBindingWithRepo(t, s, source, mappingID, "", "") } // seedArmedBindingWithRepo is seedArmedBinding with an explicit // owner/repo pin (pass "", "" for the unpinned case seedArmedBinding // covers). func seedArmedBindingWithRepo(t *testing.T, s *dispatchStores, source, mappingID, owner, repo string) (string, int) { t.Helper() id, err := s.EdaStore.InsertBinding(t.Context(), binding.Binding{ Name: "test " + source, Matcher: binding.Matcher{Source: source}, MappingID: mappingID, Workflow: "implement", Owner: owner, Repo: repo, }) if err != nil { t.Fatalf("InsertBinding: %v", err) } if err := s.EdaStore.ApproveBinding(t.Context(), id); err != nil { t.Fatalf("ApproveBinding: %v", err) } got, err := s.EdaStore.GetBinding(t.Context(), id) if err != nil || got == nil { t.Fatalf("GetBinding after approve: %+v, %v", got, err) } return id, got.Version } // seedCapture inserts an inbound capture event with the given source, // authenticated flag, and body. retention=0, maxEvents=0 disable // the per-insert pruning the production path uses, so a test that // only needs a single row in the table is not at the mercy of // maxEvents=0's "no cap" reading. func seedCapture(t *testing.T, s *dispatchStores, source string, authenticated bool, body string) { t.Helper() _, err := s.EdaStore.InsertCapture(t.Context(), storecontract.CapturedEvent{ Source: source, Body: body, Authenticated: authenticated, ReceivedAt: time.Now().UTC(), }, 0, 0) if err != nil { t.Fatalf("InsertCapture: %v", err) } } // newDispatchDaemon builds a Daemon whose store-related handles all // point at the same *pgstore.TaskDB so dispatchBindings can resolve // captures through the dispatcher handles and mappings through // d.Mappings. Exactly one repo is configured so resolveBindingRepo's // single-repo fallback accepts the dispatch; with zero or many // configured repos the loop would log and skip, masking the test's // positive assertions. func newDispatchDaemon(t *testing.T, s *dispatchStores) *Daemon { t.Helper() return newDispatchDaemonWithRepos(t, s, []config.Repo{{Owner: "acme", Name: "widget"}}) } // newDispatchDaemonWithRepos is newDispatchDaemon with an explicit repo // list, for tests exercising resolveBindingRepo's owner/repo-pin path // against zero, one, or several configured repos. func newDispatchDaemonWithRepos(t *testing.T, s *dispatchStores, repos []config.Repo) *Daemon { t.Helper() cfg := config.Config{Repos: repos} return &Daemon{ Cfg: config.NewHolder(cfg), Store: s.Store, Mappings: s.EdaStore, Bindings: s.EdaStore, BindingDispatcher: s.EdaStore, BindingTaskCreator: s.Store, Log: slog.New(slog.NewTextHandler(os.Stderr, nil)), } } // assertDispatchRecorded reads the dedup ledger directly: the (binding, // capture) unique index is what guarantees no double dispatch. The dispatch // is claimed before its task exists, so the row carries no task id. func assertDispatchRecorded(t *testing.T, s *dispatchStores, bindingID string) { t.Helper() var gotBindingID string if err := s.edaPool.QueryRow(t.Context(), "SELECT binding FROM binding_dispatches WHERE binding = $1", bindingID). Scan(&gotBindingID); err != nil { t.Fatalf("binding_dispatches row missing: %v", err) } }