diff --git a/cmd/archied/main.go b/cmd/archied/main.go index 39362c7b1..952c5969d 100644 --- a/cmd/archied/main.go +++ b/cmd/archied/main.go @@ -402,7 +402,7 @@ func run() int { Cfg: cfg, St: st, LLM: llm, ChatModels: chatModels, ToolReg: toolReg, Personas: personas, ChatTasks: chatTasks, ChatController: chatController, DefaultChatIdentity: defaultChatIdentity, SessionStore: chatSessionStore, - Log: log, + Bus: bus, Log: log, } webRouter.LLM, webRouter.LLMStream = makeChatLLMResponder(ctx, "web", webSetup, chatSessionStore, webRouter) web.Chat = &webui.ChatService{ @@ -427,6 +427,7 @@ func run() int { St: st, LLM: llm, ChatModels: chatModels, ToolReg: toolReg, Personas: personas, ChatTasks: chatTasks, ChatController: chatController, DefaultChatIdentity: defaultChatIdentity, SessionStore: chatSessionStore, Updates: updateService, + Bus: bus, RegisterRestart: func(request func() error) { restartTelegram = request }, Log: log, }) if !ok { @@ -657,6 +658,12 @@ func run() int { // (cancels in-flight passes, then stops curator lifecycle), then the // registry's own Stop below, which is a no-op by then. curatorRuntime := curator.NewRuntime(curatorRegistry, curator.RuntimeConfig{}) + // Primary chat turns wake input-driven curators (archie-core-035): + // the forwarder consumes only primary-input kinds, and curator + // output never produces them, so derived work cannot feed its own + // trigger. The subscriber buffer is bounded and dropping — a slow + // curator can never backpressure the chat publisher. + curator.WakeOnPrimaryInput(ctx, bus, curatorRuntime, events.KindTurnCompleted) defer func() { stopCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() diff --git a/cmd/archied/telegram_setup.go b/cmd/archied/telegram_setup.go index 0ead98a78..8cb8d35d1 100644 --- a/cmd/archied/telegram_setup.go +++ b/cmd/archied/telegram_setup.go @@ -15,6 +15,7 @@ import ( "github.com/samcharles93/archie-core/internal/channels/telegram" "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/gateway" "github.com/samcharles93/archie-core/internal/infrastructure/configuration" "github.com/samcharles93/archie-core/internal/nell" @@ -43,7 +44,11 @@ type telegramSetup struct { Updates telegram.UpdateService Dangerous gateway.DangerousCommandAuthority RegisterRestart func(func() error) - Log *slog.Logger + // Bus carries primary-input events (archie-core-035): a completed + // chat turn is published here so input-driven curators can wake. Nil + // disables turn events (tests, minimal setups). + Bus *events.Bus + Log *slog.Logger } // setupTelegramGateway initialises the Telegram chat gateway when a @@ -249,6 +254,20 @@ func makeChatLLMResponder(ctx context.Context, channel string, s telegramSetup, if err := sessionStore.SaveMessage(ctx, sk, gateway.Message{From: s.Cfg.BotUser, Text: text}); err != nil { return "", fmt.Errorf("save outbound chat message: %w", err) } + // The turn is complete: both messages are persisted. Announce it + // as primary input (archie-core-035). Publish is non-blocking + // with bounded dropping subscriber buffers, so this never delays + // the chat path; a dropped event only delays a curator run to its + // next check-in. Curator output never produces this kind, so + // derived work cannot feed its own trigger. Redeliveries return + // above and never reach here. + if s.Bus != nil { + s.Bus.Publish(events.Event{ + Kind: events.KindTurnCompleted, + Detail: sk, + Data: map[string]any{"session": sk, "channel": channel}, + }) + } return text, nil } return func(ctx context.Context, msg gateway.Message) (string, error) { diff --git a/internal/curator/wake.go b/internal/curator/wake.go new file mode 100644 index 000000000..e65e347dd --- /dev/null +++ b/internal/curator/wake.go @@ -0,0 +1,37 @@ +package curator + +import ( + "context" + "slices" + + "github.com/samcharles93/archie-core/internal/events" +) + +// WakeOnPrimaryInput forwards primary-input events from the in-process bus +// to the runtime as best-effort nudges (archie-core-035). Only the kinds in +// inputKinds wake curators — the trigger-accounting invariant: curator- +// produced activity (curator_run, curator_action, curator_error, and any +// future derived-write kind) never appears on this path, so a curator's own +// output cannot feed its own trigger. The subscription is bounded and the +// bus drops on overflow, so a slow curator can never backpressure the chat +// publisher; a dropped event only delays a run to the next check-in. The +// forwarder runs until ctx is cancelled or the bus closes. +func WakeOnPrimaryInput(ctx context.Context, bus *events.Bus, rt *Runtime, inputKinds ...string) { + sub := bus.Subscribe(defaultWakeBuffer) + go func() { + defer sub.Close() + for { + select { + case <-ctx.Done(): + return + case e, ok := <-sub.C: + if !ok { + return // bus closed + } + if slices.Contains(inputKinds, e.Kind) { + rt.Nudge("") + } + } + } + }() +} diff --git a/internal/curator/wake_test.go b/internal/curator/wake_test.go new file mode 100644 index 000000000..f0e967991 --- /dev/null +++ b/internal/curator/wake_test.go @@ -0,0 +1,94 @@ +package curator + +import ( + "context" + "testing" + "time" + + "github.com/samcharles93/archie-core/internal/events" +) + +// TestWakeOnPrimaryInputForwardsOnlyPrimaryKinds is the trigger-accounting +// regression guard (archie-core-035). +// +// Rationale (do not delete): if derived curator output counted toward the +// condition that schedules the next curator run, a curator that writes +// memories would schedule itself again — inflating the observation +// threshold and creating a feedback loop. The wake path therefore forwards +// ONLY primary-input kinds; curator-produced activity (curator_run, +// curator_action, curator_error, and any future derived-write kind) must +// never reach it. This test fails if a derived kind is added to the +// forwarded set or the filter is removed as "redundant". +func TestWakeOnPrimaryInputForwardsOnlyPrimaryKinds(t *testing.T) { + t.Parallel() + + clock := newFakeClock(time.Unix(0, 0)) + c := newFake("c", Manifest{Interval: testInterval, OnInput: true}) + c.checkResult = true + reg := NewRegistry(Registrar{Clock: clock, Events: &testSink{}}) + if err := reg.Register(c); err != nil { + t.Fatalf("Register = %v, want nil", err) + } + rt := NewRuntime(reg, RuntimeConfig{}) + if err := rt.Start(context.Background()); err != nil { + t.Fatalf("Start() = %v, want nil", err) + } + t.Cleanup(func() { _ = rt.Stop(context.Background()) }) + + bus := events.NewBus() + t.Cleanup(bus.Close) + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + WakeOnPrimaryInput(ctx, bus, rt, events.KindTurnCompleted) + + // The initial check runs at start; the curator passes because input + // is pending. + waitFor(t, 2*time.Second, "initial pass", func() bool { return c.passCalls.Load() == 1 }) + + // Derived curator output and unrelated events must not wake the + // curator: no check, no pass. + for i := 0; i < 3; i++ { + bus.Publish(events.Event{Kind: events.KindCuratorRun}) + bus.Publish(events.Event{Kind: events.KindCuratorAction}) + bus.Publish(events.Event{Kind: events.KindCuratorError}) + bus.Publish(events.Event{Kind: events.KindTaskQueued}) + } + time.Sleep(50 * time.Millisecond) + if got := c.passCalls.Load(); got != 1 { + t.Fatalf("passCalls = %d after derived events, want 1 (derived output must not feed its own trigger)", got) + } + if got := c.checkCalls.Load(); got != 1 { + t.Fatalf("checkCalls = %d after derived events, want 1", got) + } + + // Primary input still wakes the curator. + bus.Publish(events.Event{Kind: events.KindTurnCompleted, Detail: "session-1"}) + waitFor(t, 2*time.Second, "pass on primary turn", func() bool { return c.passCalls.Load() == 2 }) +} + +func TestWakeOnPrimaryInputStopsWhenBusCloses(t *testing.T) { + t.Parallel() + + clock := newFakeClock(time.Unix(0, 0)) + c := newFake("c", Manifest{Interval: testInterval, OnInput: true}) + c.checkResult = true + reg := NewRegistry(Registrar{Clock: clock, Events: &testSink{}}) + if err := reg.Register(c); err != nil { + t.Fatalf("Register = %v, want nil", err) + } + rt := NewRuntime(reg, RuntimeConfig{}) + if err := rt.Start(context.Background()); err != nil { + t.Fatalf("Start() = %v, want nil", err) + } + t.Cleanup(func() { _ = rt.Stop(context.Background()) }) + + bus := events.NewBus() + ctx, cancel := context.WithCancel(context.Background()) + WakeOnPrimaryInput(ctx, bus, rt, events.KindTurnCompleted) + + // Closing the bus must end the forwarder cleanly (no spin on the + // closed subscriber channel); cancelling the context must too. + bus.Close() + cancel() + time.Sleep(50 * time.Millisecond) +} diff --git a/internal/events/events.go b/internal/events/events.go index 9f226f571..e574df202 100644 --- a/internal/events/events.go +++ b/internal/events/events.go @@ -36,6 +36,12 @@ const ( KindCuratorRun = "curator_run" // data: curator, actions, at KindCuratorAction = "curator_action" // data: curator, type, detail, reason KindCuratorError = "curator_error" // data: curator, phase, err + + // KindTurnCompleted marks one completed primary chat turn + // (archie-core-035). Input-driven curators wake on it. Curator output + // never produces this kind, so derived work cannot feed its own + // trigger. data: session, channel. + KindTurnCompleted = "turn_completed" ) // Event is the single wire type: task lifecycle, stage progress, agent