diff --git a/.golangci.yml b/.golangci.yml index 140aebf37..250399b87 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -116,7 +116,6 @@ linters: formatters: enable: - gofumpt - - goimports - gci settings: gofumpt: @@ -131,9 +130,10 @@ formatters: custom-order: true exclusions: generated: strict - # These are Yaegi programs shipped as examples. goimports cannot type-check - # files excluded by //go:build ignore and deletes their genuinely used - # internal/secret import, leaving the interpreter unable to load them. + # These Yaegi programs sit behind //go:build ignore, so a formatter cannot + # type-check them: rewriting their imports deletes the genuinely used + # internal/secret import and the interpreter can no longer load them. + # Excluded from every formatter so adding one cannot reintroduce that. paths: - ^examples/secret-engines/(age|sops|vault)\.go$ diff --git a/Taskfile.yml b/Taskfile.yml index dce4ca076..2c5ca3023 100644 --- a/Taskfile.yml +++ b/Taskfile.yml @@ -14,8 +14,8 @@ tasks: cmds: - go fix ./... # This must use the same engine and configuration as task lint. Running - # standalone gofumpt cannot reproduce goimports or gci's custom import - # grouping, so it can leave a tree that the gate rejects. + # standalone gofumpt cannot reproduce gci's custom import grouping, so it + # can leave a tree that the gate rejects. - golangci-lint fmt proto:install: diff --git a/internal/app/archied/bootstrap.go b/internal/app/archied/bootstrap.go index 8972f54b8..54f51c868 100644 --- a/internal/app/archied/bootstrap.go +++ b/internal/app/archied/bootstrap.go @@ -995,7 +995,7 @@ func (b *boot) setupCurators(ctx context.Context) { // Conversations backs the session-memory curator; b.chatSessionStore // is opened by openChatSessions before setupCurators. Conversations: sessioncurator.NewAdapter(b.chatSessionStore), - LLM: curatorLLMRunner{rt: b.llm}, + LLM: curatorLLMRunner{rt: b.llm, outcomes: b.providerOutcomes}, // b.chatModels.ActiveModel() is the same source sendChatTurn uses // for a real chat turn (telegram_setup.go) -- not // b.defaultChatIdentity, which names a task-routing identity, not diff --git a/internal/app/archied/chat_setup.go b/internal/app/archied/chat_setup.go index 59982ab6c..9eb882292 100644 --- a/internal/app/archied/chat_setup.go +++ b/internal/app/archied/chat_setup.go @@ -238,10 +238,11 @@ func chatRepoEnv(cfg config.Config, identity string) []gateway.RepoEnv { } // sendChatTurn runs one chat-model call and records its outcome for /status' -// chat-model line. Recording happens in this one wrapper because every -// chat-model call in this process passes through it: recording at the call -// sites instead would let a path make a call and leave the reported -// last-known outcome stale, which is a /status that lies about the provider. +// chat-model line. Every chat turn passes through here, so one wrapper covers +// the whole chat path; curator work is the other model caller in this process +// and records at its own adapter (curatorLLMRunner). Anything that reaches the +// runtime without recording leaves /status reporting a stale last-known +// outcome, which is a /status that lies about the provider. func sendChatTurn(ctx context.Context, llm *runtime.Runtime, chatModel string, options core.GenerateOptions, turn gateway.TurnStream, outcomes *providerOutcomeRecorder) (string, error) { text, err := runChatTurn(ctx, llm, chatModel, options, turn) // record tolerates a nil recorder: a setup built without one (tests, a @@ -374,7 +375,6 @@ type chatTitleGenerator struct { log *slog.Logger llm *runtime.Runtime chatModels gateway.ModelManager - outcomes *providerOutcomeRecorder } // newChatTitleGenerator wires an LLM-backed title generator for a chat @@ -384,7 +384,7 @@ func newChatTitleGenerator(s chatSetup) gateway.TitleGenerator { if s.LLM == nil || s.ChatModels == nil { return nil } - return &chatTitleGenerator{log: s.Log, llm: s.LLM, chatModels: s.ChatModels, outcomes: s.ProviderOutcomes} + return &chatTitleGenerator{log: s.Log, llm: s.LLM, chatModels: s.ChatModels} } func (g *chatTitleGenerator) GenerateTitle(ctx context.Context, sessionID, firstMessage string) (string, error) { @@ -394,8 +394,15 @@ func (g *chatTitleGenerator) GenerateTitle(ctx context.Context, sessionID, first } // No tools: a title is a single completion. The active model is read // at call time so a /model switch applies to titles too. + // + // Deliberately records no outcome for /status. A title is cosmetic, + // generated in a detached goroutine under its own 30s bound + // (gateway.titleGenerationTimeout), and its error is swallowed by the + // caller. Sharing the process-wide recorder let a title that merely timed + // out overwrite the chat-model health line with "failed", reporting a + // broken provider on the strength of a call no user was waiting for. text, err := sendChatTurn(ctx, g.llm, g.chatModels.ActiveModel(), - core.GenerateOptions{Messages: messages, MaxSteps: 1}, nil, g.outcomes) + core.GenerateOptions{Messages: messages, MaxSteps: 1}, nil, nil) if err != nil { if g.log != nil { g.log.Error("session title generation failed", "session", sessionID, "err", err) diff --git a/internal/app/archied/main.go b/internal/app/archied/main.go index ac0ae114d..750d4f6b0 100644 --- a/internal/app/archied/main.go +++ b/internal/app/archied/main.go @@ -547,14 +547,29 @@ func (s curatorEventSink) Emit(kind, detail string, data map[string]any) { // single completion are a bigger decision than this adapter makes. type curatorLLMRunner struct { rt *runtime.Runtime + // outcomes records this call for /status alongside sendChatTurn's. A + // curator call is a model call this process made, and it does not pass + // through sendChatTurn, so without this a daemon whose only recent model + // traffic was curator work reports "no calls attempted yet" while the + // provider is demonstrably reachable -- or worse, keeps showing a much + // older chat outcome as current. + outcomes *providerOutcomeRecorder } func (r curatorLLMRunner) Chat(ctx context.Context, req curator.ChatRequest) (curator.ChatResult, error) { + // agentexec.NewRuntime returns nil when no provider is configured, and a + // nil *runtime.Runtime panics on the first method call. A curator asking + // for a completion on a daemon with no providers is a misconfiguration, + // not a reason to take the process down. + if r.rt == nil { + return curator.ChatResult{}, fmt.Errorf("curator chat: no model runtime is configured") + } msgs := make([]chat.Message, 0, len(req.Messages)) for _, m := range req.Messages { msgs = append(msgs, chat.Message{Role: chat.Role(m.Role), Content: m.Content}) } res, err := r.rt.Chat(ctx, req.Model, core.GenerateOptions{Messages: msgs, MaxSteps: max(req.MaxSteps, 1)}) + r.outcomes.record(req.Model, err) if err != nil { return curator.ChatResult{}, err } diff --git a/internal/app/archied/status_health.go b/internal/app/archied/status_health.go index 9d03bb616..74efec41a 100644 --- a/internal/app/archied/status_health.go +++ b/internal/app/archied/status_health.go @@ -39,15 +39,31 @@ func newProviderOutcomeRecorder() *providerOutcomeRecorder { return &providerOut // when it succeeded. A nil recorder records nothing -- call paths built // without one (tests, minimal setups) must not panic. func (r *providerOutcomeRecorder) record(model string, err error) { + r.recordAt(model, err, time.Now().UTC()) +} + +// recordAt stores one call's outcome, keeping whichever is most recent. +// +// The completion time is taken by the caller, before the lock, so it reports +// when the call actually finished rather than when this goroutine won the +// mutex. That ordering is not the same as the lock's: two concurrent calls can +// reach the lock in the opposite order to their completion, and an +// unconditional store would then leave /status reporting an older call as the +// latest one. Keeping the newer of the two is what makes the reported outcome +// true regardless of scheduling. +func (r *providerOutcomeRecorder) recordAt(model string, err error, at time.Time) { if r == nil { return } - outcome := gateway.ChatModelOutcome{Model: model, At: time.Now().UTC()} + outcome := gateway.ChatModelOutcome{Model: model, At: at} if err != nil { outcome.Err = err.Error() } r.mu.Lock() defer r.mu.Unlock() + if r.attempted && outcome.At.Before(r.outcome.At) { + return + } r.outcome = outcome r.attempted = true } diff --git a/internal/app/archied/status_health_test.go b/internal/app/archied/status_health_test.go index 8ffb518a8..b78dce541 100644 --- a/internal/app/archied/status_health_test.go +++ b/internal/app/archied/status_health_test.go @@ -19,6 +19,7 @@ import ( "github.com/samcharles93/archie-core/internal/agentexec" "github.com/samcharles93/archie-core/internal/channels/status" "github.com/samcharles93/archie-core/internal/daemon" + "github.com/samcharles93/archie-core/internal/domain/curator" "github.com/samcharles93/archie-core/internal/domain/messaging" "github.com/samcharles93/archie-core/internal/gateway" "github.com/samcharles93/archie-core/internal/store" @@ -463,3 +464,111 @@ func TestRouterWithHealthAnswersStatus(t *testing.T) { t.Errorf("reply = %q, want the wired broker line", reply) } } + +// TestRecordKeepsTheLatestOutcomeUnderReordering is the regression case for a +// /status chat-model line that reports an older call as the latest. The +// completion time is taken before the lock, so two concurrent calls can reach +// the lock in the opposite order to their completion; an unconditional store +// then overwrites the newer outcome with the older one. +func TestRecordKeepsTheLatestOutcomeUnderReordering(t *testing.T) { + r := &providerOutcomeRecorder{} + newer := time.Now().UTC() + older := newer.Add(-time.Minute) + + // The later call completes and stores first, as it would when the earlier + // call is descheduled between stamping and locking. + r.recordAt("openai/gpt-5.6", nil, newer) + r.recordAt("openai/gpt-4o", errors.New("401 Unauthorized"), older) + + got, attempted := r.LastChatModelOutcome() + if !attempted { + t.Fatal("LastChatModelOutcome reports no attempt after two records") + } + if got.Model != "openai/gpt-5.6" || got.Err != "" { + t.Fatalf("outcome = %+v, want the newer successful call to survive", got) + } +} + +// TestRecordStoresTheFirstOutcomeWhateverItsAge pins that the ordering guard +// does not swallow the first record, whose timestamp has nothing to compare +// against. +func TestRecordStoresTheFirstOutcomeWhateverItsAge(t *testing.T) { + r := &providerOutcomeRecorder{} + r.recordAt("openai/gpt-4o", nil, time.Now().UTC().Add(-time.Hour)) + + if _, attempted := r.LastChatModelOutcome(); !attempted { + t.Fatal("the first recorded outcome was dropped") + } +} + +// TestCuratorRunnerRefusesWithoutARuntime pins that a curator asking for a +// completion on a daemon with no configured provider gets an error. The +// runtime constructor returns nil in that case, and a nil *runtime.Runtime +// panics on its first method call, which would take the daemon down. Nothing +// is recorded: no provider call was attempted, and saying one failed would be +// a /status that blames the provider for a local misconfiguration. +func TestCuratorRunnerRefusesWithoutARuntime(t *testing.T) { + recorder := &providerOutcomeRecorder{} + runner := curatorLLMRunner{outcomes: recorder} + + if _, err := runner.Chat(context.Background(), curator.ChatRequest{Model: "openai/gpt-4o"}); err == nil { + t.Fatal("Chat with no runtime returned no error") + } + if _, attempted := recorder.LastChatModelOutcome(); attempted { + t.Error("a local misconfiguration was recorded as a provider call") + } +} + +// TestCuratorRunnerRecordsItsOutcome pins that curator model calls reach +// /status. They do not pass through sendChatTurn, so before this a daemon +// whose only recent model traffic was curator work reported "no calls +// attempted yet" while the provider was demonstrably reachable. +func TestCuratorRunnerRecordsItsOutcome(t *testing.T) { + recorder := &providerOutcomeRecorder{} + // A provider pointed at a closed local port fails fast without touching + // the network. The outcome is what matters here: a failed provider call is + // exactly what /status must not miss. + rt := agentexec.NewRuntime(map[string]agentexec.Provider{ + "openai": {Class: "openai", BaseURL: "http://127.0.0.1:1", APIKeyEnv: "ARCHIE_TEST_MISSING_KEY"}, + }) + if rt == nil { + t.Fatal("NewRuntime returned nil for a configured provider") + } + runner := curatorLLMRunner{rt: rt, outcomes: recorder} + + _, err := runner.Chat(context.Background(), curator.ChatRequest{Model: "openai/gpt-4o"}) + if err == nil { + t.Fatal("Chat against a closed port returned no error") + } + + got, attempted := recorder.LastChatModelOutcome() + if !attempted { + t.Fatal("curator call was not recorded; /status would report no calls attempted") + } + if got.Model != "openai/gpt-4o" || got.Err == "" { + t.Fatalf("outcome = %+v, want the failed curator call", got) + } +} + +// TestTitleGenerationDoesNotRecordChatModelHealth is the regression case for +// /status blaming the provider for a cosmetic failure. Title generation runs +// detached after a first turn under its own 30s bound and its error is +// swallowed by the caller, so a title that merely timed out must not become +// the process-wide "Chat model: failed" that an operator reads as an outage. +func TestTitleGenerationDoesNotRecordChatModelHealth(t *testing.T) { + recorder := &providerOutcomeRecorder{} + rt := agentexec.NewRuntime(map[string]agentexec.Provider{ + "openai": {Class: "openai", BaseURL: "http://127.0.0.1:1", APIKeyEnv: "ARCHIE_TEST_MISSING_KEY"}, + }) + if rt == nil { + t.Fatal("NewRuntime returned nil for a configured provider") + } + gen := &chatTitleGenerator{llm: rt, chatModels: newChatModelManager(map[string]string{"chat": "openai/gpt-4o"}, nil, nil)} + + if _, err := gen.GenerateTitle(context.Background(), "s1", "hello"); err == nil { + t.Fatal("GenerateTitle against a closed port returned no error") + } + if _, attempted := recorder.LastChatModelOutcome(); attempted { + t.Error("a failed title proposal was recorded as chat-model health") + } +} diff --git a/internal/channels/telegram/commands.go b/internal/channels/telegram/commands.go index 64b5b353c..cc0d357e0 100644 --- a/internal/channels/telegram/commands.go +++ b/internal/channels/telegram/commands.go @@ -19,7 +19,7 @@ type commandSpec struct { // published command menu and /help. Keeping the discoverability surfaces // together prevents a newly registered command from being omitted from help. var gatewayCommandSpecs = []commandSpec{ - {Command: "status", Description: "Show daemon health: broker, workers, channels, provider", Usage: "/status"}, + {Command: "status", Description: "Show health: queue depth, broker, and the last chat-model call", Usage: "/status"}, {Command: "tasks", Description: "Show your tasks: state, stage, age, parked reason", Usage: "/tasks"}, {Command: "version", Description: "Show installed Archie versions", Usage: "/version"}, {Command: "update", Description: "Check for Archie updates", Usage: "/update"}, diff --git a/internal/config/clone_test.go b/internal/config/clone_test.go index 29729b251..c81b493b2 100644 --- a/internal/config/clone_test.go +++ b/internal/config/clone_test.go @@ -11,12 +11,14 @@ import ( func TestConfigCloneDeepCopiesReferenceFields(t *testing.T) { enabled := true orig := Config{ - Models: map[string]string{"builder": "m"}, - ModelLimits: map[string]ModelLimits{"m": {ContextWindow: 128_000}}, - Repos: []Repo{{Gate: [][]string{{"task", "check"}}, Protect: []string{"p"}}}, + Models: map[string]string{"builder": "m"}, + ModelLimits: map[string]ModelLimits{"m": {ContextWindow: 128_000}}, + Repos: []Repo{{Gate: [][]string{{"task", "check"}}, Protect: []string{"p"}}}, + DiffCapLines: new(400), Identities: []IdentityConfig{{ - Models: map[string]string{"planner": "m2"}, - Repos: []Repo{{Gate: [][]string{{"go", "vet"}}}}, + Models: map[string]string{"planner": "m2"}, + DiffCapLines: new(50), + Repos: []Repo{{Gate: [][]string{{"go", "vet"}}}}, }}, Dispatch: Dispatch{Labels: map[string]string{"q": "archie:q"}}, Tools: ToolsConfig{ @@ -51,6 +53,8 @@ func TestConfigCloneDeepCopiesReferenceFields(t *testing.T) { got.Extra["custom"] = 2 got.Bindings.PreviousEncryptionKeys[0] = SecretRef{Engine: "env", Key: "changed"} *got.Tools.WebFetch.Enabled = false + *got.DiffCapLines = 1 + *got.Identities[0].DiffCapLines = 2 got.Image.Hosted["openai"] = ImageHostedProvider{Enabled: false} got.Image.Local["sdxl"] = ImageLocalProvider{Enabled: false} got.Services[ServiceNameState] = ServiceConnection{Target: "changed"} @@ -85,6 +89,12 @@ func TestConfigCloneDeepCopiesReferenceFields(t *testing.T) { if orig.Bindings.PreviousEncryptionKeys[0].Key != "K0" { t.Error("Bindings.PreviousEncryptionKeys is shared") } + if orig.DiffCap() != 400 { + t.Errorf("DiffCapLines pointer is shared: orig.DiffCap() = %d, want 400", orig.DiffCap()) + } + if got := orig.Identities[0].DiffCapLines; got == nil || *got != 50 { + t.Errorf("Identities[0].DiffCapLines pointer is shared: got %v, want 50", got) + } if !*orig.Tools.WebFetch.Enabled { t.Error("WebFetch.Enabled pointer is shared") } diff --git a/internal/config/config.go b/internal/config/config.go index 11a838b5a..3e26e81da 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -695,10 +695,22 @@ func (c Config) Clone() Config { v := *c.Tools.WebFetch.Enabled c.Tools.WebFetch.Enabled = &v } + c.DiffCapLines = cloneIntPtr(c.DiffCapLines) c.Extra = maps.Clone(c.Extra) return c } +// cloneIntPtr copies an optional int so a clone cannot write through to the +// original. Optional ints carry a real meaning in their zero value (see +// DiffCapLines), which is why they are pointers in the first place. +func cloneIntPtr(v *int) *int { + if v == nil { + return nil + } + n := *v + return &n +} + func cloneRepos(repos []Repo) []Repo { if repos == nil { return nil @@ -723,6 +735,7 @@ func cloneIdentities(ids []IdentityConfig) []IdentityConfig { id.Providers = maps.Clone(id.Providers) id.Dispatch.Labels = cloneStringMap(id.Dispatch.Labels) id.Repos = cloneRepos(id.Repos) + id.DiffCapLines = cloneIntPtr(id.DiffCapLines) out[i] = id } return out diff --git a/internal/domain/messaging/commands.go b/internal/domain/messaging/commands.go index 80aa7fb29..c1fd68e83 100644 --- a/internal/domain/messaging/commands.go +++ b/internal/domain/messaging/commands.go @@ -20,7 +20,7 @@ type CommandSpec struct { } var localCommandSpecs = []CommandSpec{ - {Command: "/status", Description: "Show daemon health: broker, workers, channels, provider", Usage: "/status"}, + {Command: "/status", Description: "Show health: queue depth, broker, and the last chat-model call", Usage: "/status"}, {Command: "/tasks", Description: "Show your tasks: state, stage, age, parked reason", Usage: "/tasks"}, {Command: "/model", Description: "Choose a provider and model", Usage: "/model [provider/model]"}, {Command: "/spawn", Description: "Create a tracked task", Usage: "/spawn "}, diff --git a/internal/gateway/health.go b/internal/gateway/health.go index cdf6924c9..945b48987 100644 --- a/internal/gateway/health.go +++ b/internal/gateway/health.go @@ -156,7 +156,10 @@ func formatChannels(channels []ChannelHealth) string { // multi-line error cannot break the chat reply's layout, and bounds its // length. A failed adapter is the case where an operator most needs the // reason, so this trims rather than drops it. -func channelDetail(detail string) string { +// boundedDetail flattens and caps a detail so one line of /status stays one +// line. A provider error carries whatever the provider sent back, which for an +// HTML error page or a echoed request body is neither short nor single-line. +func boundedDetail(detail string) string { flattened := strings.Join(strings.Fields(detail), " ") runes := []rune(flattened) if len(runes) <= maxChannelDetail { @@ -165,6 +168,8 @@ func channelDetail(detail string) string { return string(runes[:maxChannelDetail]) + "…" } +func channelDetail(detail string) string { return boundedDetail(detail) } + func formatChatModel(health ChatModelHealth, now time.Time) string { if !health.Attempted { // The decision behind this line: /status never probes the provider. @@ -183,9 +188,9 @@ func formatChatModel(health ChatModelHealth, now time.Time) string { case outcome.Err == "": return fmt.Sprintf("ok %s%s", age, model) case age == "": - return fmt.Sprintf("failed%s: %s", model, outcome.Err) + return fmt.Sprintf("failed%s: %s", model, boundedDetail(outcome.Err)) default: - return fmt.Sprintf("failed %s%s: %s", age, model, outcome.Err) + return fmt.Sprintf("failed %s%s: %s", age, model, boundedDetail(outcome.Err)) } } diff --git a/internal/gateway/health_test.go b/internal/gateway/health_test.go index b5bcab73b..f3a9a3ae2 100644 --- a/internal/gateway/health_test.go +++ b/internal/gateway/health_test.go @@ -240,3 +240,28 @@ func TestHandleStatusReadsTheWiredHealthSource(t *testing.T) { }) } } + +// TestFormatChatModelBoundsTheProviderError pins that a provider error cannot +// break /status' one-line-per-fact layout. The error is whatever the provider +// returned, which for an HTML error page is neither short nor single-line, and +// unlike a channel detail it was passed through raw. +func TestFormatChatModelBoundsTheProviderError(t *testing.T) { + now := time.Now() + health := ChatModelHealth{ + Attempted: true, + Outcome: ChatModelOutcome{ + Model: "openai/gpt-5.6", + At: now.Add(-time.Minute), + Err: "502 Bad Gateway\n<html>\n<head><title>502\n" + strings.Repeat("body text ", 40), + }, + } + + got := formatChatModel(health, now) + if strings.ContainsAny(got, "\n\r") { + t.Fatalf("formatChatModel() = %q, want a single line", got) + } + if len([]rune(got)) > maxChannelDetail+80 { + t.Fatalf("formatChatModel() is %d runes, want it bounded near maxChannelDetail (%d)", + len([]rune(got)), maxChannelDetail) + } +}