diff --git a/internal/app/archied/bootstrap.go b/internal/app/archied/bootstrap.go index 578842dfb..1a70f529c 100644 --- a/internal/app/archied/bootstrap.go +++ b/internal/app/archied/bootstrap.go @@ -42,7 +42,6 @@ import ( "github.com/samcharles93/archie-core/internal/forge" forgewebhook "github.com/samcharles93/archie-core/internal/forge/webhook" "github.com/samcharles93/archie-core/internal/gateway" - "github.com/samcharles93/archie-core/internal/infrastructure/captureintake" "github.com/samcharles93/archie-core/internal/infrastructure/configuration" "github.com/samcharles93/archie-core/internal/infrastructure/configuration/overlay" infraembedding "github.com/samcharles93/archie-core/internal/infrastructure/embedding" @@ -69,7 +68,6 @@ import ( memorytoolprovider "github.com/samcharles93/archie-core/internal/tools/provider/memory" "github.com/samcharles93/archie-core/internal/tools/sendfile" "github.com/samcharles93/archie-core/internal/tools/webfetch" - "github.com/samcharles93/archie-core/internal/webhookguard" "github.com/samcharles93/archie-core/internal/webui" "github.com/samcharles93/archie-core/internal/worktree" "github.com/samcharles93/archie-core/internal/worktreerpc" @@ -387,87 +385,14 @@ func (b *boot) setupObservability(ctx context.Context) { Path: origin.Path, Role: string(origin.Role), Layer: string(origin.Layer), Feature: string(origin.Feature), }) } - b.web = &webui.Server{Store: b.stateStore, Log: log.With("component", "webui"), LogFeed: b.logFeed, TaskLogs: b.taskLogs, Cfg: config.NewHolder(cfg), Channels: b.channelManager, Events: bus} - b.web.UpdateReportPath = updateReportPath(cfg.WorkDir, "webui") + b.web = &webui.Server{Log: log.With("component", "webui"), Cfg: config.NewHolder(cfg), Channels: b.channelManager} // The watchdog leaves its verdict in a file on this host, so the daemon // reads it and publishes the outcome as an event; the dashboard renders // what it receives, wherever it runs (archie-core-8cda.5.4). - b.startUpdateRelay(ctx, b.web.UpdateReportPath) - if (cfg.Chat.Telegram.Token != (secret.SecretRef{}) || cfg.Chat.Telegram.TokenEnv != "") && len(cfg.Chat.Telegram.AllowedUserIDs) > 0 { - b.web.TelegramUpdateReportPath = updateReportPath(cfg.WorkDir, cfg.BotUser) - b.web.TelegramUpdateChatID = cfg.Chat.Telegram.AllowedUserIDs[0] - } - agentStatus := b.agentStatus - b.web.RunningVersions = func() map[string]string { return daemonRunningVersions(agentStatus) } + b.startUpdateRelay(ctx, updateReportPath(cfg.WorkDir, "webui")) b.web.SetProvenance(configProvenance) - b.web.ReloadChannel = func(ctx context.Context, id string) error { - if id != "telegram" || b.restartTelegram == nil { - return fmt.Errorf("channel reload unavailable") - } - return b.restartTelegram() - } - b.wireWebStoreSurfaces() sink := bus.Subscribe(256) - go persistAndBroadcastEvents(ctx, sink, b.stateStore, b.web, log) -} - -// wireWebStoreSurfaces attaches the dashboard's optional storage surfaces. -// b.stateStore is declared as the narrow store.TaskStore, so each wider -// capture/mapping/binding surface needs its own assertion here rather than a -// direct field reuse. b.stateStore is the local *store.Store by default and a -// remote *staterpc.Client when [services.state].target is set, so the same -// assertion resolves either adapter. A store that does not implement one -// degrades that dashboard feature with a warning instead of aborting -// bootstrap. The BindingStore/BindingDispatcher/BindingTaskCreator split -// keeps each interface under the interfacebloat limit. See -// docs/prds/event-capture-storage.md, -// docs/prds/payload-field-mapping.md and docs/prds/webhook-intake-security.md, and -// docs/prds/state-store-contract.md §10 for the adapter selection. -func (b *boot) wireWebStoreSurfaces() { - cfg, log := b.cfg, b.log - // Capture/mapping/binding surfaces resolve from b.stateStore (the State - // Store contract adapter): local by default, remote *staterpc.Client when - // [services.state].target is set. See wireWebStoreSurfaces' doc and - // docs/prds/state-store-contract.md §10. - var captures store.CaptureStore - if cs, ok := b.stateStore.(store.CaptureStore); ok { - captures = cs - } else { - log.Warn("capture storage unavailable: state store does not implement CaptureStore") - } - b.web.Captures = captures - b.web.CaptureMaxEvents = cfg.Capture.MaxEvents - var bindings store.BindingDispatcher - if bd, ok := b.stateStore.(store.BindingDispatcher); ok { - bindings = bd - } else { - log.Warn("binding dispatcher unavailable: state store does not implement BindingDispatcher") - } - // The intake write belongs to the process that owns work intake; the - // dashboard keeps only the read and mounts the route - // (archie-core-8cda.5.4). Publish rides the daemon's event bus: the - // sink drain persists each event with a row id before fanning it out, - // so a capture still reaches the operator as a persisted event. - b.web.CaptureIntake = &captureintake.Receiver{ - Captures: captures, - Limiter: webhookguard.NewRateLimiter(cfg.Capture.RatePerSecond, cfg.Capture.RateBurst, time.Now), - Bindings: bindings, - Retention: cfg.Capture.Retention.Std(), - MaxEvents: cfg.Capture.MaxEvents, - MaxBodyBytes: int64(cfg.Capture.MaxBodyBytes), - Publish: b.publishEvent, - Log: log, - } - if ms, ok := b.stateStore.(store.MappingStore); ok { - b.web.Mappings = ms - } else { - log.Warn("mapping storage unavailable: state store does not implement MappingStore") - } - if bs, ok := b.stateStore.(store.BindingStore); ok { - b.web.Bindings = bs - } else { - log.Warn("binding storage unavailable: state store does not implement BindingStore") - } + go persistEvents(ctx, sink, b.stateStore, log) } // connectNATS opens the NATS client. External mode dials cfg.NATS.URL; @@ -724,15 +649,10 @@ func (b *boot) loadWorkflows(ctx context.Context) error { return err } log.Info("workflow registry built", "workflows", len(workflowCatalog.Registry)) - b.web.Workflows = workflow.DefinitionsWithOrigins(workflowCatalog.Registry, workflowCatalog.Origins) - if l := cfg.Web.Listen; l != "" && l != "off" { - b.web.Token = webTokenFor(l, cfg.DBPath, log) - go func() { - if err := b.web.Run(ctx, l); err != nil { - log.Error("web ui failed", "err", err) - } - }() - } + // The dashboard is served by the archie-ui process from the cutover + // change (archie-core-8cda.5.4, PRD gate 7): the daemon runs no webui + // listener, and [web].listen is the archie-ui process's bind address. + // b.web stays only as the configuration snapshot's renderer. return nil } @@ -1497,89 +1417,13 @@ func (b *boot) wireConfigPublishing(ctx context.Context, cfgPath, overlayPath st b.chatController.WithRuntime(b.d) } -// installUpdateConfigHandler installs the dashboard's PATCH /api/config -// handler. It applies updates to a deep copy of the published config, -// validates the materialised result, persists to the overlay, then -// publishes through the same path as reload. It must never call Set -// directly from the handler -- web.Cfg is the daemon's own Holder -- and -// it decodes into a Clone so a failed validation cannot mutate the -// published snapshot's shared maps. -func (b *boot) installUpdateConfigHandler() { - log := b.log - b.web.UpdateConfig = func(ctx context.Context, updates map[string]any) error { - if b.overlayStore == nil { - return fmt.Errorf("%w: config overlay is disabled (--no-config-overlay or ARCHIE_SKIP_CONFIG_OVERLAY=1)", webui.ErrConfigUpdateUnavailable) - } - for key := range updates { - if reason, denied := overlay.DeniedKeys[key]; denied { - return fmt.Errorf("%w: config key %s is not runtime-tunable: %s", webui.ErrConfigUpdateInvalid, key, reason) - } - } - next := b.d.Cfg.Get().Clone() - if err := applyDottedOverlay(&next, updates); err != nil { - return fmt.Errorf("%w: %w", webui.ErrConfigUpdateInvalid, err) - } - if err := configuration.Validate(&next); err != nil { - return fmt.Errorf("%w: %w", webui.ErrConfigUpdateInvalid, err) - } - for key, value := range updates { - data, err := json.Marshal(value) - if err != nil { - return fmt.Errorf("%w: %w", webui.ErrConfigUpdateInvalid, err) - } - if err := b.overlayStore.Set(ctx, key, string(data), "dashboard"); err != nil { - return err - } - } - // Provenance gets the runtime-overlay origin, replacing any prior - // one so the chain does not grow unboundedly across edits. - var kept []configuration.Origin - for _, origin := range b.currentProvenance.Load().Origins { - if origin.Path == "config_overlay (runtime)" { - continue - } - kept = append(kept, origin) - } - prov := configuration.Provenance{Origins: append(kept, - configuration.Origin{Path: "config_overlay (runtime)", Role: configuration.RoleMain, Layer: configuration.LayerOverlay})} - b.currentProvenance.Store(&prov) - b.publishConfig(ctx, next, prov) - b.bootOverlayErr.Store(nil) // a successful write proves the overlay works again - log.Info("config updated from dashboard", "keys", len(updates)) - return nil - } -} - -// installUpdateRepoFieldHandler installs the dashboard's PATCH -// /api/config/repos/{owner}/{name} handler (archie-core-b6ew.6). A -// repository is one element of a []config.Repo, not a flat dotted key, so -// this cannot go through UpdateConfig's dotted-key path directly (overlay's -// Nest/ApplyOverlayValues have no notion of "element N of this slice"). -// Instead it reads the daemon's own live, untrimmed Repos (never -// webui.RepoView, which omits fields like Preflight/TestGlob and would -// silently drop them on a naive round-trip), changes the one field on the -// matching repo, and republishes the *entire* repository list through -// UpdateConfig -- reusing its validate-persist-publish path unchanged, so -// this handler owns only "which repo, which field," never how an update is -// applied. An edit here therefore overrides the whole repos list in the -// runtime overlay, same granularity every other overlay key already has; -// [[repos]] file edits stay visible for every field this handler never -// touches until an operator resets the "repos" override. -func (b *boot) installUpdateRepoFieldHandler() { - b.web.UpdateRepoField = func(ctx context.Context, owner, name, field string, value any) error { - repos, err := applyRepoFieldUpdate(b.d.Cfg.Get().Clone().Repos, owner, name, field, value) - if err != nil { - return err - } - return b.web.UpdateConfig(ctx, map[string]any{"repos": repos}) - } -} - -// installConfigHandlers installs the dashboard's config override -// listing and per-row reset handlers, both going through the same -// publish path as reload. -func (b *boot) installConfigHandlers(cfgPath, overlayPath string) { - log := b.log +// installConfigHandlers installs the configuration renderer's override +// listing. The write handlers behind PATCH /api/config, POST +// /api/config/reset and the per-repository field update are gone with the +// cutover (archie-core-8cda.5.4, archie-core-ymut): editing is config.toml +// plus reload, the UI process answers 503 for the write routes, and the +// renderer only needs to know which keys an overlay currently overrides. +func (b *boot) installConfigHandlers() { // ConfigOverrides lists the dotted keys currently overridden by the // runtime overlay, so the dashboard can mark those rows and offer a // reset. A disabled store reports no overrides. @@ -1598,41 +1442,6 @@ func (b *boot) installConfigHandlers(cfgPath, overlayPath string) { sort.Strings(keys) return keys, nil } - - // ResetConfig deletes one overlay row and republishes file + remaining - // overlay, so a dashboard-created override can be removed without - // editing SQL -- and so an operator whose file edit is shadowed by an - // override can recover it with one click. The file is resolved and - // the target state validated BEFORE the row is deleted, so a broken - // file cannot leave the store and the running config disagreeing. - b.web.ResetConfig = func(ctx context.Context, key string) error { - if b.overlayStore == nil { - return fmt.Errorf("%w: config overlay is disabled", webui.ErrConfigUpdateUnavailable) - } - overrides, err := b.overlayStore.Snapshot(ctx) - if err != nil { - return err - } - delete(overrides, key) // the target overlay state after the reset - doc, err := b.loader.Resolve(cfgPath, overlayPath) - if err != nil { - return fmt.Errorf("%w: %w", webui.ErrConfigUpdateInvalid, err) - } - if len(overrides) > 0 { - if doc, err = b.loader.ApplyOverlay(doc, overrides); err != nil { - return fmt.Errorf("%w: %w", webui.ErrConfigUpdateInvalid, err) - } - } - if err := b.overlayStore.Delete(ctx, key); err != nil { - return err - } - applyModelCatalog(&doc.Config, b.catalog) - b.currentProvenance.Store(&doc.Provenance) - b.publishConfig(ctx, doc.Config, doc.Provenance) - b.bootOverlayErr.Store(nil) - log.Info("config key reset to file value", "key", key) - return nil - } } // shutdownCapabilityHost returns a cleanup that stops the capability diff --git a/internal/app/archied/config_update.go b/internal/app/archied/config_update.go deleted file mode 100644 index f43a5e8ea..000000000 --- a/internal/app/archied/config_update.go +++ /dev/null @@ -1,68 +0,0 @@ -package archied - -import ( - "fmt" - "slices" - - "github.com/samcharles93/archie-core/internal/config" - "github.com/samcharles93/archie-core/internal/infrastructure/configuration" - "github.com/samcharles93/archie-core/internal/infrastructure/configuration/overlay" - "github.com/samcharles93/archie-core/internal/webui" -) - -// applyDottedOverlay decodes dotted-path updates into cfg. yaml cannot -// decode dotted keys ("budgets.max_steps" is not a struct field), so -// the updates are nested into a map first -- the same nesting the -// overlay store's Snapshot performs -- then decoded with the same -// field-level merge the file overlay uses. cfg must be a copy the -// caller owns (a Clone of the published config); it is never decoded -// into a published snapshot directly. -func applyDottedOverlay(cfg *config.Config, updates map[string]any) error { - nested := make(map[string]any) - for key, value := range updates { - if err := overlay.Nest(nested, key, value); err != nil { - return err - } - } - return configuration.ApplyOverlayValues(cfg, nested) -} - -// applyRepoFieldUpdate returns a copy of repos with one editable field -// changed on the repository matched by owner/name (archie-core-b6ew.6). -// repos must already be a caller-owned copy (config.Config.Clone's -// Repos) -- this mutates the matched element in place and returns the -// same slice, matching applyDottedOverlay's "caller owns the copy" -// contract. Kept as a pure function, separate from -// installUpdateRepoFieldHandler's closure, so the field-matching and -// type-coercion logic is directly unit-testable without constructing a -// full boot. -func applyRepoFieldUpdate(repos []config.Repo, owner, name, field string, value any) ([]config.Repo, error) { - if !webui.RepoEditableFields[field] { - return nil, fmt.Errorf("%w: repo field %s is not editable from the dashboard", webui.ErrConfigUpdateInvalid, field) - } - index := slices.IndexFunc(repos, func(r config.Repo) bool { return r.Owner == owner && r.Name == name }) - if index < 0 { - return nil, fmt.Errorf("%w: repository %s/%s is not configured", webui.ErrConfigUpdateInvalid, owner, name) - } - switch field { - case "allow_concurrent": - v, ok := value.(bool) - if !ok { - return nil, fmt.Errorf("%w: allow_concurrent must be a boolean", webui.ErrConfigUpdateInvalid) - } - repos[index].AllowConcurrent = v - case "review_enabled": - v, ok := value.(bool) - if !ok { - return nil, fmt.Errorf("%w: review_enabled must be a boolean", webui.ErrConfigUpdateInvalid) - } - repos[index].ReviewEnabled = v - case "max_retries": - v, ok := value.(float64) - if !ok { - return nil, fmt.Errorf("%w: max_retries must be a number", webui.ErrConfigUpdateInvalid) - } - repos[index].MaxRetries = int(v) - } - return repos, nil -} diff --git a/internal/app/archied/config_update_test.go b/internal/app/archied/config_update_test.go deleted file mode 100644 index 99ee9594c..000000000 --- a/internal/app/archied/config_update_test.go +++ /dev/null @@ -1,110 +0,0 @@ -package archied - -import ( - "testing" - - "github.com/samcharles93/archie-core/internal/config" -) - -// TestApplyDottedOverlayNestsBeforeDecode pins the PATCH-path fix: the -// UI sends dotted keys ("budgets.max_steps") and yaml cannot decode a -// dotted key as a struct field, so the updates must be nested first. A -// regression here silently drops every dotted update while returning 200. -func TestApplyDottedOverlayNestsBeforeDecode(t *testing.T) { - cfg := config.Config{Budgets: config.Budgets{MaxSteps: 10}} - if err := applyDottedOverlay(&cfg, map[string]any{"budgets.max_steps": 20}); err != nil { - t.Fatal(err) - } - if cfg.Budgets.MaxSteps != 20 { - t.Fatalf("MaxSteps = %d, want 20 (dotted key must be nested before decode)", cfg.Budgets.MaxSteps) - } -} - -// TestApplyDottedOverlayRejectsEmptyKey pins that a malformed dotted key -// fails instead of silently nesting under a synthetic root. -func TestApplyDottedOverlayRejectsEmptyKey(t *testing.T) { - cfg := config.Config{} - if err := applyDottedOverlay(&cfg, map[string]any{"": 1}); err == nil { - t.Fatal("empty dotted key accepted") - } -} - -func twoRepoFixture() []config.Repo { - return []config.Repo{ - {Owner: "acme", Name: "widget", Base: "main", Preflight: [][]string{{"go", "version"}}}, - {Owner: "acme", Name: "gadget", Base: "main"}, - } -} - -// TestApplyRepoFieldUpdateChangesOnlyTheMatchedRepo proves the update -// targets exactly one element by owner/name and leaves every other repo, -// and every other field on the matched repo, untouched -- including -// Preflight, which webui.RepoView never carries on the wire (the whole -// point of reading b.d.Cfg's live Repos instead of the trimmed view). -func TestApplyRepoFieldUpdateChangesOnlyTheMatchedRepo(t *testing.T) { - repos, err := applyRepoFieldUpdate(twoRepoFixture(), "acme", "widget", "allow_concurrent", true) - if err != nil { - t.Fatalf("applyRepoFieldUpdate: %v", err) - } - if !repos[0].AllowConcurrent { - t.Error("widget.AllowConcurrent = false, want true") - } - if len(repos[0].Preflight) != 1 || repos[0].Preflight[0][0] != "go" { - t.Errorf("widget.Preflight = %v, want it untouched", repos[0].Preflight) - } - if repos[1].AllowConcurrent { - t.Error("gadget.AllowConcurrent changed, want the non-matched repo left alone") - } -} - -func TestApplyRepoFieldUpdateSetsEachEditableField(t *testing.T) { - repos, err := applyRepoFieldUpdate(twoRepoFixture(), "acme", "widget", "max_retries", float64(7)) - if err != nil { - t.Fatalf("applyRepoFieldUpdate: %v", err) - } - if repos[0].MaxRetries != 7 { - t.Errorf("MaxRetries = %d, want 7 (JSON numbers decode as float64)", repos[0].MaxRetries) - } - - repos, err = applyRepoFieldUpdate(twoRepoFixture(), "acme", "widget", "review_enabled", true) - if err != nil { - t.Fatalf("applyRepoFieldUpdate: %v", err) - } - if !repos[0].ReviewEnabled { - t.Error("ReviewEnabled = false, want true") - } -} - -func TestApplyRepoFieldUpdateRejectsUnknownRepo(t *testing.T) { - _, err := applyRepoFieldUpdate(twoRepoFixture(), "acme", "does-not-exist", "allow_concurrent", true) - if err == nil { - t.Fatal("expected an error for a repo that is not configured") - } -} - -func TestApplyRepoFieldUpdateRejectsUneditableField(t *testing.T) { - _, err := applyRepoFieldUpdate(twoRepoFixture(), "acme", "widget", "gate", []any{}) - if err == nil { - t.Fatal("expected an error for a field outside RepoEditableFields") - } -} - -// TestApplyRepoFieldUpdateRejectsWrongValueType proves a bool field given a -// number (or vice versa) fails with a clear error instead of a silent -// zero-value write -- the JSON body is caller-controlled (the dashboard), -// not type-checked before it reaches this function. -func TestApplyRepoFieldUpdateRejectsWrongValueType(t *testing.T) { - cases := []struct { - field string - value any - }{ - {"allow_concurrent", "yes"}, - {"review_enabled", 1.0}, - {"max_retries", true}, - } - for _, tc := range cases { - if _, err := applyRepoFieldUpdate(twoRepoFixture(), "acme", "widget", tc.field, tc.value); err == nil { - t.Errorf("field %q accepted wrong-typed value %#v", tc.field, tc.value) - } - } -} diff --git a/internal/app/archied/main.go b/internal/app/archied/main.go index f16f88cdf..68ad76fc0 100644 --- a/internal/app/archied/main.go +++ b/internal/app/archied/main.go @@ -49,7 +49,6 @@ import ( "github.com/samcharles93/archie-core/internal/tools/mcp" toolprovider "github.com/samcharles93/archie-core/internal/tools/provider" mcptoolprovider "github.com/samcharles93/archie-core/internal/tools/provider/mcp" - "github.com/samcharles93/archie-core/internal/webui" "github.com/samcharles93/archie-core/internal/worktree" "github.com/samcharles93/archie-core/internal/worktreerpc" ) @@ -444,17 +443,16 @@ func Run() int { //nolint:cyclop // the composition root's setup sequence is del return exitCode(b.runLoop(ctx, args.once)) } -// wireConfigSurfaces attaches the dashboard's configuration read and write -// paths: the published snapshot plus the three validate-persist-publish -// handlers behind PATCH /api/config, POST /api/config/reset and the -// per-repository field update. They are wired together because they are one -// capability -- the daemon owning configuration on the dashboard's behalf -- -// and archie-core-8cda.5.4 replaces the set of them at once. +// wireConfigSurfaces attaches the dashboard's configuration read path and +// the reload plumbing behind it. The write handlers (PATCH /api/config, the +// per-repository field update, per-row reset) are descoped for the UI +// process (archie-core-ymut): the daemon still owns the validate-persist- +// publish policy, but no HTTP route reaches it -- editing is config.toml +// plus reload -- so only the snapshot publication and the override list the +// renderer needs stay wired. func (b *boot) wireConfigSurfaces(ctx context.Context, cfgPath, overlayPath string) { b.wireConfigPublishing(ctx, cfgPath, overlayPath) - b.installUpdateConfigHandler() - b.installUpdateRepoFieldHandler() - b.installConfigHandlers(cfgPath, overlayPath) + b.installConfigHandlers() // Publish once at boot. Every later change goes through publishConfig, // which republishes; without this the UI process would render nothing // until the first reload or dashboard edit. @@ -509,24 +507,24 @@ func recordBootOverlayError(p *atomic.Pointer[string], log *slog.Logger, err err log.Error(msg, args...) } -// persistAndBroadcastEvents drains the bus until it closes, giving each -// event an ID from the store before fanning it out. +// persistEvents drains the bus until it closes, giving each event an ID +// from the store. The store is the only fan-out point (docs/architecture/ +// migration-decisions.md, "Dashboard live event delivery"): the UI process +// reads the same table through its event pump, so the daemon's job is +// persistence, not delivery. // // The insert deliberately outlives ctx: this loop ends when the bus closes, // which is part of shutdown, and the last events of a run are exactly the // ones an operator wants to read afterwards. -func persistAndBroadcastEvents(ctx context.Context, sink *events.Sub, st store.TaskStore, web *webui.Server, log *slog.Logger) { +func persistEvents(ctx context.Context, sink *events.Sub, st store.TaskStore, log *slog.Logger) { ctx = context.WithoutCancel(ctx) for e := range sink.C { - if e.ID == 0 { - id, err := st.InsertEvent(ctx, e) - if err != nil { - log.Error("event sink insert failed", "err", err) - continue - } - e.ID = id + if e.ID != 0 { + continue + } + if _, err := st.InsertEvent(ctx, e); err != nil { + log.Error("event sink insert failed", "err", err) } - web.Broadcast(e) } } @@ -979,27 +977,6 @@ func safePluginInfo(p plugin.Plugin) (name, version string) { return p.Name(), p.Version() } -// webTokenFor returns the dashboard token for a listen address, or "" when -// none is needed. -// -// A loopback bind needs no token: local access already implies the agent's own -// authority, since its shell and edit tools run as this user. A reachable bind -// mints one and logs a URL to click, so an instance cannot be left exposed -// merely by omitting configuration. -func webTokenFor(listen, dbPath string, log *slog.Logger) string { - if webui.IsLoopback(listen) { - return "" - } - path := filepath.Join(filepath.Dir(dbPath), "web-token") - tok, err := webui.LoadOrCreateToken(path) - if err != nil { - log.Error("web ui token", "err", err) - return "" - } - log.Info("web ui token", "open", webui.DashboardURL(listen, tok), "stored", path) - return tok -} - // memoryProvider builds the built-in memory provider, falling back to the // default work directory when the configured one cannot be established. // diff --git a/internal/app/archied/state_store_consumers_test.go b/internal/app/archied/state_store_consumers_test.go index 08e587968..9a6bd61e2 100644 --- a/internal/app/archied/state_store_consumers_test.go +++ b/internal/app/archied/state_store_consumers_test.go @@ -9,7 +9,6 @@ import ( "github.com/samcharles93/archie-core/internal/daemon" "github.com/samcharles93/archie-core/internal/infrastructure/configuration" taskactionstore "github.com/samcharles93/archie-core/internal/infrastructure/taskactions" - "github.com/samcharles93/archie-core/internal/logging" "github.com/samcharles93/archie-core/internal/store" "github.com/samcharles93/archie-core/internal/webui" ) @@ -69,11 +68,14 @@ func TestBuildDaemonRoutesTaskStoreThroughStateStore(t *testing.T) { } } -// TestSetupObservabilityRoutesTaskStoreThroughStateStore proves the dashboard's -// task store (web.Store) is wired from b.stateStore (the State Store contract -// adapter), not b.st, so the webui reaches the same contract adapter the -// daemon uses. -func TestSetupObservabilityRoutesTaskStoreThroughStateStore(t *testing.T) { +// TestSetupObservabilityKeepsStoreSurfacesOutOfTheDaemonWebui proves the +// cutover's composition rule: the daemon's webui is the configuration +// snapshot's renderer, so it carries the config Holder and provenance and +// no store surfaces -- the dashboard's store-backed reads resolve in the +// UI process from its own State Store client (pinned by archieui's +// compose tests), and a store handle here would be an unused second +// authority. +func TestSetupObservabilityKeepsStoreSurfacesOutOfTheDaemonWebui(t *testing.T) { storeA, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "store-a.db")) if err != nil { t.Fatal(err) @@ -81,7 +83,6 @@ func TestSetupObservabilityRoutesTaskStoreThroughStateStore(t *testing.T) { t.Cleanup(func() { _ = storeA.Close() }) storeB := openSecondStore(t) - logFeed := logging.NewFeed(16) b := &boot{ cfg: config.Config{}, log: slog.New(slog.DiscardHandler), @@ -89,21 +90,23 @@ func TestSetupObservabilityRoutesTaskStoreThroughStateStore(t *testing.T) { stateStore: storeB, doc: &configuration.Document{}, agentStatus: &daemon.AgentStatus{}, - logFeed: logFeed, - taskLogs: logging.NewTaskRegistry(filepath.Join(t.TempDir(), "logs"), logFeed, logging.TaskSinkOptions{}), } t.Cleanup(b.cleanup) b.setupObservability(t.Context()) - if b.web.Store != storeB { - t.Fatalf("webui Store = %p, want b.stateStore (%p); dashboard task store did not route through the State Store adapter", b.web.Store, storeB) + if b.web.Cfg == nil { + t.Fatal("webui Cfg is nil; the daemon renders the configuration snapshot it publishes (archie-core-ymut)") } - // Capture/mapping/binding surfaces resolve from the same adapter. - if b.web.Captures != storeB { - t.Fatalf("webui Captures = %p, want b.stateStore (%p)", b.web.Captures, storeB) - } - if b.web.Mappings != storeB { - t.Fatalf("webui Mappings = %p, want b.stateStore (%p)", b.web.Mappings, storeB) + for name, surface := range map[string]any{ + "Store": b.web.Store, + "Captures": b.web.Captures, + "Mappings": b.web.Mappings, + "Bindings": b.web.Bindings, + "CaptureIntake": b.web.CaptureIntake, + } { + if surface != nil { + t.Errorf("webui %s is wired; the daemon serves no dashboard after the cutover", name) + } } } diff --git a/internal/app/archieui/compose.go b/internal/app/archieui/compose.go index a177ad9b7..05b1e88ac 100644 --- a/internal/app/archieui/compose.go +++ b/internal/app/archieui/compose.go @@ -9,8 +9,8 @@ import ( "github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/gateway" "github.com/samcharles93/archie-core/internal/infrastructure/captureintake" - "github.com/samcharles93/archie-core/internal/webhookguard" "github.com/samcharles93/archie-core/internal/store" + "github.com/samcharles93/archie-core/internal/webhookguard" "github.com/samcharles93/archie-core/internal/webui" ) @@ -119,12 +119,12 @@ func wireCaptureSurfaces(d deps, srv *webui.Server) { // store records captures without announcing them (compose's test-only // shape); an insert failure is logged, not surfaced -- the capture row is // already durable, and the inspector refetches on its next view. -func captureArrivalPublisher(d deps) func(events.Event) { +func captureArrivalPublisher(d deps) func(context.Context, events.Event) { if d.Store == nil { return nil } - return func(e events.Event) { - ctx, cancel := context.WithTimeout(context.Background(), captureEventTimeout) + return func(ctx context.Context, e events.Event) { + ctx, cancel := context.WithTimeout(ctx, captureEventTimeout) defer cancel() if _, err := d.Store.InsertEvent(ctx, e); err != nil { d.Log.Warn("capture arrival event not published", "err", err) diff --git a/internal/infrastructure/captureintake/receiver.go b/internal/infrastructure/captureintake/receiver.go index c401bfdd4..bcc975018 100644 --- a/internal/infrastructure/captureintake/receiver.go +++ b/internal/infrastructure/captureintake/receiver.go @@ -13,6 +13,7 @@ package captureintake import ( + "context" "encoding/json" "fmt" "io" @@ -52,9 +53,11 @@ type Receiver struct { // MaxBodyBytes rejects (413) a body larger than this before redaction // or storage sees it. MaxBodyBytes int64 - // Publish puts the capture's arrival on the activity stream. Nil records - // the capture without announcing it. - Publish func(events.Event) + // Publish puts the capture's arrival on the activity stream, with the + // request's context: the announce happens synchronously inside the + // handler, before the 202 is written, so the request's lifetime bounds + // it. Nil records the capture without announcing it. + Publish func(ctx context.Context, e events.Event) Log *slog.Logger } @@ -156,7 +159,7 @@ func (rc *Receiver) ServeHTTP(w http.ResponseWriter, r *http.Request) { // The captures view treats this purely as an invalidation signal and // refetches the list for the actual row data. if rc.Publish != nil { - rc.Publish(events.Event{ + rc.Publish(r.Context(), events.Event{ Kind: "capture", Detail: "capture from " + source, Data: map[string]any{"id": id, "source": source}, diff --git a/internal/infrastructure/captureintake/receiver_test.go b/internal/infrastructure/captureintake/receiver_test.go index b77dc71a3..22c07def3 100644 --- a/internal/infrastructure/captureintake/receiver_test.go +++ b/internal/infrastructure/captureintake/receiver_test.go @@ -27,7 +27,7 @@ type recordingPublisher struct { published []events.Event } -func (r *recordingPublisher) Publish(e events.Event) { +func (r *recordingPublisher) Publish(_ context.Context, e events.Event) { r.published = append(r.published, e) } diff --git a/internal/webui/server.go b/internal/webui/server.go index c6dc8a880..0052ba829 100644 --- a/internal/webui/server.go +++ b/internal/webui/server.go @@ -15,7 +15,6 @@ import ( "net/http" "sync" "sync/atomic" - "time" "github.com/samcharles93/archie-core/internal/channels" "github.com/samcharles93/archie-core/internal/config" @@ -387,22 +386,6 @@ func trimLeadingSlash(p string) string { return p } -// Run serves until ctx ends. -func (s *Server) Run(ctx context.Context, listen string) error { - srv := &http.Server{Addr: listen, Handler: s.Handler(), ReadHeaderTimeout: 5 * time.Second} - go func() { - <-ctx.Done() - shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 2*time.Second) - defer cancel() - _ = srv.Shutdown(shutdownCtx) - }() - s.Log.Info("web ui listening", "addr", "http://"+listen) - if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed { - return err - } - return nil -} - func writeJSON(w http.ResponseWriter, v any) { w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(v)