fix(plugin): add missing CLAUDE.md reference to plugin engine rule

Test TestPluginEngineRuleIsCanonicalAndSharedByAgentInstructions was
missing entirely, letting CLAUDE.md drift out of sync with
ARCHITECTURE.md#plugin-engine-rule-strict. Added the test and the
missing reference.
This commit is contained in:
sam committed 2026-08-31 21:25:20 +10:00
1 parent 88a995a736
commit 5fa010c9c2
32 files changed
+1148 -1118

No files matched your search

File diff suppressed because it is too large. Load diff
-152
View File
@@ -1,152 +0,0 @@
package main
import (
"encoding/json"
"fmt"
"go/ast"
"go/parser"
"go/token"
"log/slog"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"testing"
"github.com/moby/moby/client"
natsio "github.com/nats-io/nats.go"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/container"
)
// setupContainers must discover the bridge before embedded NATS starts, but
// its cleanup registration comes afterwards. boot.cleanup is LIFO, so this
// ordering stops worker containers before closing the daemon client and the
// embedded server they are connected to.
func TestSetupBackendsRegistersContainerCleanupAfterNATS(t *testing.T) {
fileset := token.NewFileSet()
file, err := parser.ParseFile(fileset, "bootstrap.go", nil, 0)
if err != nil {
t.Fatal(err)
}
setupContainers := methodBody(t, file, "setupContainers")
if methodCallPosition(setupContainers, "addCleanup") != token.NoPos {
t.Fatal("setupContainers registers cleanup before NATS; LIFO would stop the broker before workers")
}
setupBackends := methodBody(t, file, "setupBackends")
connect := methodCallPosition(setupBackends, "connectNATS")
register := methodCallPosition(setupBackends, "addCleanup")
if connect == token.NoPos || register == token.NoPos || register < connect {
t.Fatalf("setupBackends call positions: connectNATS=%d addCleanup=%d, want container cleanup registered after connect", connect, register)
}
}
func methodBody(t *testing.T, file *ast.File, name string) *ast.BlockStmt {
t.Helper()
for _, decl := range file.Decls {
fn, ok := decl.(*ast.FuncDecl)
if ok && fn.Recv != nil && fn.Name.Name == name {
return fn.Body
}
}
t.Fatalf("method %s not found", name)
return nil
}
func methodCallPosition(body *ast.BlockStmt, name string) token.Pos {
position := token.NoPos
ast.Inspect(body, func(node ast.Node) bool {
call, ok := node.(*ast.CallExpr)
if !ok {
return true
}
selector, ok := call.Fun.(*ast.SelectorExpr)
if ok && selector.Sel.Name == name && position == token.NoPos {
position = call.Pos()
}
return true
})
return position
}
// This is the native-daemon deployment seam: Docker supplies the host-side
// gateway of the worker bridge, embedded NATS binds that address, and the
// runtime credential shared with workers is required by the same listener.
func TestConnectEmbeddedNATSUsesManagedWorkerBridge(t *testing.T) {
const gateway = "127.0.0.1"
dockerAPI := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case strings.HasSuffix(r.URL.Path, "/networks/workers"):
writeDockerResponse(t, w, map[string]any{
"Name": "workers",
"Driver": "bridge",
"Scope": "local",
"IPAM": map[string]any{
"Config": []map[string]string{{
"Subnet": "127.0.0.0/8",
"Gateway": gateway,
}},
},
})
case strings.HasSuffix(r.URL.Path, "/containers/json"):
writeDockerResponse(t, w, []any{})
default:
http.Error(w, fmt.Sprintf("unexpected Docker API path %s", r.URL.Path), http.StatusNotFound)
}
}))
t.Cleanup(dockerAPI.Close)
dockerClient, err := client.New(client.WithHost(dockerAPI.URL), client.WithAPIVersion("1.55"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = dockerClient.Close() })
pool, err := container.NewPool(t.Context(), container.Config{
DockerClient: dockerClient,
Network: "workers",
RequireHostGateway: true,
}, slog.New(slog.DiscardHandler))
if err != nil {
t.Fatalf("container.NewPool = %v", err)
}
t.Cleanup(func() { _ = pool.Close() })
b := &boot{
cfg: config.Config{
DBPath: filepath.Join(t.TempDir(), "archie.db"),
NATS: config.NATSConfig{Mode: config.NATSModeEmbedded},
},
log: slog.New(slog.DiscardHandler),
containerPool: pool,
}
if err := b.connectNATS(t.Context()); err != nil {
t.Fatalf("connectNATS = %v", err)
}
t.Cleanup(b.cleanup)
if !strings.HasPrefix(b.natsURL, "nats://"+gateway+":") {
t.Errorf("connected NATS URL = %q, want bridge gateway %s", b.natsURL, gateway)
}
if b.natsToken == "" {
t.Fatal("connected NATS token is empty")
}
if unauthenticated, connectErr := natsio.Connect(b.natsURL); connectErr == nil {
unauthenticated.Close()
t.Fatal("unauthenticated worker connection succeeded")
}
authenticated, err := natsio.Connect(b.natsURL, natsio.Token(b.natsToken))
if err != nil {
t.Fatalf("authenticated worker connection = %v", err)
}
authenticated.Close()
}
func writeDockerResponse(t *testing.T, w http.ResponseWriter, value any) {
t.Helper()
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(value); err != nil {
t.Errorf("encode Docker response: %v", err)
}
}
-166
View File
@@ -1,166 +0,0 @@
package main
import (
"context"
"fmt"
"slices"
"strings"
"sync"
"github.com/samcharles93/archie-core/internal/gateway"
"github.com/samcharles93/archie-core/internal/infrastructure/modelcatalog"
)
// chatModelManager owns the process-local model selected for interactive chat.
// The configured role-to-model map supplies the available catalog; switching
// chat models does not rewrite daemon configuration or affect workflow roles.
type chatModelManager struct {
mu sync.RWMutex
models []string
active string
details map[string]gateway.ModelDetails
providerNames map[string]string
}
func newChatModelManager(configured map[string]string, catalogs ...[]string) *chatModelManager {
unique := make(map[string]struct{}, len(configured))
for _, ref := range configured {
ref = strings.TrimSpace(ref)
if ref != "" {
unique[ref] = struct{}{}
}
}
for _, catalog := range catalogs {
for _, ref := range catalog {
ref = strings.TrimSpace(ref)
if ref != "" {
unique[ref] = struct{}{}
}
}
}
models := make([]string, 0, len(unique))
for ref := range unique {
models = append(models, ref)
}
slices.Sort(models)
active := strings.TrimSpace(configured["chat"])
if active == "" {
active = strings.TrimSpace(configured["builder"])
}
return &chatModelManager{
models: models, active: active,
details: make(map[string]gateway.ModelDetails),
providerNames: make(map[string]string),
}
}
func (m *chatModelManager) ApplyModelCatalog(snapshot modelcatalog.Snapshot) {
m.mu.Lock()
defer m.mu.Unlock()
for _, provider := range snapshot.Providers {
m.providerNames[provider.ID] = provider.Name
for _, model := range provider.Models {
ref := provider.ID + "/" + model.ID
m.details[ref] = gateway.ModelDetails{
Ref: ref, Name: model.Name,
ContextWindow: model.ContextWindow, MaxOutputTokens: model.MaxOutputTokens,
Reasoning: model.Reasoning, Tools: true,
Attachment: model.Attachment, Structured: model.Structured,
InputModalities: slices.Clone(model.InputModalities),
}
}
}
}
func (m *chatModelManager) ProviderDisplayName(provider string) string {
m.mu.RLock()
defer m.mu.RUnlock()
return m.providerNames[provider]
}
func (m *chatModelManager) ModelDetails(ref string) (gateway.ModelDetails, bool) {
m.mu.RLock()
defer m.mu.RUnlock()
details, ok := m.details[ref]
return details, ok
}
func (m *chatModelManager) Models() []string {
m.mu.RLock()
defer m.mu.RUnlock()
return slices.Clone(m.models)
}
func (m *chatModelManager) ActiveModel() string {
m.mu.RLock()
defer m.mu.RUnlock()
return m.active
}
func (m *chatModelManager) SetActiveModel(ctx context.Context, ref string) error {
if err := ctx.Err(); err != nil {
return err
}
m.mu.Lock()
defer m.mu.Unlock()
if !slices.Contains(m.models, ref) {
return fmt.Errorf("model %q is not configured", ref)
}
m.active = ref
return nil
}
func (m *chatModelManager) Providers() []string {
m.mu.RLock()
defer m.mu.RUnlock()
seen := make(map[string]bool)
var providers []string
for _, model := range m.models {
provider, _, ok := strings.Cut(model, "/")
if ok && provider != "" && !seen[provider] {
seen[provider] = true
providers = append(providers, provider)
}
}
slices.Sort(providers)
return providers
}
func (m *chatModelManager) ActiveProvider() string {
m.mu.RLock()
defer m.mu.RUnlock()
provider, _, _ := strings.Cut(m.active, "/")
return provider
}
func (m *chatModelManager) ModelsForProvider(provider string) []string {
m.mu.RLock()
defer m.mu.RUnlock()
prefix := provider + "/"
var models []string
for _, model := range m.models {
if strings.HasPrefix(model, prefix) {
models = append(models, model)
}
}
return models
}
func (m *chatModelManager) SetActiveProvider(ctx context.Context, provider string) error {
if err := ctx.Err(); err != nil {
return err
}
m.mu.Lock()
defer m.mu.Unlock()
prefix := provider + "/"
for _, model := range m.models {
if strings.HasPrefix(model, prefix) {
m.active = model
return nil
}
}
return fmt.Errorf("provider %q is not configured", provider)
}
-144
View File
@@ -1,144 +0,0 @@
package main
import (
"context"
"testing"
)
func TestChatModelManagerBuildsUniqueCatalogAndSelectsChatDefault(t *testing.T) {
manager := newChatModelManager(map[string]string{
"builder": "provider/zeta",
"chat": "provider/alpha",
"review": "provider/zeta",
"empty": "",
})
models := manager.Models()
if len(models) != 2 || models[0] != "provider/alpha" || models[1] != "provider/zeta" {
t.Fatalf("Models() = %v, want sorted unique model references", models)
}
models[0] = "mutated"
if got := manager.Models()[0]; got != "provider/alpha" {
t.Fatalf("Models() exposed internal state: first model = %q", got)
}
if got := manager.ActiveModel(); got != "provider/alpha" {
t.Fatalf("ActiveModel() = %q, want chat model", got)
}
}
func TestChatModelManagerFallsBackToBuilder(t *testing.T) {
manager := newChatModelManager(map[string]string{
"builder": "provider/builder",
"review": "provider/reviewer",
})
if got := manager.ActiveModel(); got != "provider/builder" {
t.Fatalf("ActiveModel() = %q, want builder fallback", got)
}
}
func TestChatModelManagerSwitchesOnlyToConfiguredModels(t *testing.T) {
manager := newChatModelManager(map[string]string{
"chat": "provider/one",
"review": "provider/two",
})
if err := manager.SetActiveModel(context.Background(), "provider/two"); err != nil {
t.Fatalf("SetActiveModel() error = %v", err)
}
if got := manager.ActiveModel(); got != "provider/two" {
t.Fatalf("ActiveModel() = %q, want switched model", got)
}
if err := manager.SetActiveModel(context.Background(), "provider/unknown"); err == nil {
t.Fatal("SetActiveModel() error = nil, want unknown-model error")
}
if got := manager.ActiveModel(); got != "provider/two" {
t.Fatalf("failed switch changed ActiveModel() to %q", got)
}
}
func TestChatModelManagerHonorsCancelledContext(t *testing.T) {
manager := newChatModelManager(map[string]string{
"chat": "provider/one",
"review": "provider/two",
})
ctx, cancel := context.WithCancel(context.Background())
cancel()
if err := manager.SetActiveModel(ctx, "provider/two"); err == nil {
t.Fatal("SetActiveModel() error = nil, want context cancellation")
}
if got := manager.ActiveModel(); got != "provider/one" {
t.Fatalf("cancelled switch changed ActiveModel() to %q", got)
}
}
func TestChatModelManagerSeparatesProvidersAndModels(t *testing.T) {
manager := newChatModelManager(map[string]string{
"chat": "openrouter/openai/gpt-5.6",
"builder": "openai/gpt-5.6",
"review": "anthropic/claude-opus",
})
providers := manager.Providers()
if len(providers) != 3 ||
providers[0] != "anthropic" ||
providers[1] != "openai" ||
providers[2] != "openrouter" {
t.Fatalf("Providers() = %v", providers)
}
if got := manager.ActiveProvider(); got != "openrouter" {
t.Fatalf("ActiveProvider() = %q, want openrouter", got)
}
if got := manager.ModelsForProvider("openai"); len(got) != 1 || got[0] != "openai/gpt-5.6" {
t.Fatalf("openai models = %v", got)
}
if got := manager.ModelsForProvider("openrouter"); len(got) != 1 || got[0] != "openrouter/openai/gpt-5.6" {
t.Fatalf("openrouter models = %v", got)
}
}
func TestChatModelManagerProviderSwitchSelectsValidModel(t *testing.T) {
manager := newChatModelManager(map[string]string{
"chat": "openrouter/openai/gpt-5.6",
"builder": "openai/gpt-5.6",
"review": "openai/o3",
})
if err := manager.SetActiveProvider(context.Background(), "openai"); err != nil {
t.Fatalf("SetActiveProvider() error = %v", err)
}
if got := manager.ActiveProvider(); got != "openai" {
t.Fatalf("ActiveProvider() = %q, want openai", got)
}
if got := manager.ActiveModel(); got != "openai/gpt-5.6" {
t.Fatalf("ActiveModel() = %q, want first configured openai model", got)
}
if err := manager.SetActiveProvider(context.Background(), "missing"); err == nil {
t.Fatal("SetActiveProvider() error = nil, want unknown-provider error")
}
if got := manager.ActiveProvider(); got != "openai" {
t.Fatalf("failed switch changed provider to %q", got)
}
}
func TestChatModelManagerIncludesExplicitChatCatalog(t *testing.T) {
manager := newChatModelManager(
map[string]string{"chat": "openai/gpt-5.6-sol"},
[]string{
"openrouter/openai/gpt-5.6-sol",
"anthropic/claude-opus",
"openai/gpt-5.6-sol",
},
)
if got := manager.Models(); len(got) != 3 {
t.Fatalf("Models() = %v, want workflow model plus explicit catalog", got)
}
if got := manager.ModelsForProvider("openrouter"); len(got) != 1 ||
got[0] != "openrouter/openai/gpt-5.6-sol" {
t.Fatalf("OpenRouter catalog = %v", got)
}
}
-239
View File
@@ -1,239 +0,0 @@
package main
import (
"strings"
"testing"
"github.com/samcharles93/ai-sdk/core"
"github.com/samcharles93/archie-core/internal/gateway"
)
// recordingStream captures the turn's reported progress in arrival order.
type recordingStream struct {
events []string
}
func (s *recordingStream) Delta(text string) {
s.events = append(s.events, "text:"+text)
}
func (s *recordingStream) ToolCall(event gateway.ToolCallEvent) {
s.events = append(s.events, "tool:"+event.Name+":"+event.Parameters+":"+event.Summary())
}
func (s *recordingStream) Media(event gateway.MediaEvent) {
// Path is recorded alongside the type: a local attachment that lost
// its path on the way through would still look like a media event.
s.events = append(s.events, "media:"+event.ToolName+":"+event.Attachment.Type+":"+event.Attachment.Path)
}
func streamOf(parts ...core.StreamPart) <-chan core.StreamPart {
ch := make(chan core.StreamPart, len(parts))
for _, part := range parts {
ch <- part
}
close(ch)
return ch
}
func TestDrainChatStream(t *testing.T) {
tests := []struct {
name string
parts []core.StreamPart
wantText string
wantEvents []string
}{
{
name: "text only",
parts: []core.StreamPart{
{Type: core.StreamPartTextDelta, TextDelta: "hello "},
{Type: core.StreamPartTextDelta, TextDelta: "world"},
},
wantText: "hello world",
wantEvents: []string{"text:hello ", "text:world"},
},
{
name: "a tool result is reported between the text around it",
parts: []core.StreamPart{
{Type: core.StreamPartTextDelta, TextDelta: "checking"},
{Type: core.StreamPartToolCall, ToolCall: &core.ToolCall{ToolCallID: "1", ToolName: "shell", Input: `{"cmd":"true"}`}},
{Type: core.StreamPartToolResult, ToolResult: &core.ToolResult{ToolCallID: "1", ToolName: "shell", Output: "exit 0"}},
{Type: core.StreamPartTextDelta, TextDelta: " done"},
},
wantText: "checking done",
wantEvents: []string{"text:checking", `tool:shell:{"cmd":"[string]"}:exit 0`, "text: done"},
},
{
name: "a failed tool is reported as a failure, not silence",
parts: []core.StreamPart{
{Type: core.StreamPartToolResult, ToolResult: &core.ToolResult{ToolName: "shell", Error: "exit status 2"}},
},
wantEvents: []string{"tool:shell::failed: exit status 2"},
},
{
// The tool call part carries no outcome yet: reporting it as
// well would show every tool twice.
name: "the tool call part alone reports nothing",
parts: []core.StreamPart{
{Type: core.StreamPartToolCall, ToolCall: &core.ToolCall{ToolName: "shell"}},
},
wantEvents: nil,
},
{
name: "parts with nothing to render are skipped",
parts: []core.StreamPart{
{Type: core.StreamPartStartStep},
{Type: core.StreamPartTextDelta, TextDelta: ""},
{Type: core.StreamPartReasoningDelta, ReasoningDelta: "thinking"},
{Type: core.StreamPartToolResult},
{Type: core.StreamPartFinishStep},
{Type: core.StreamPartFinish},
},
wantEvents: nil,
},
{
// A tool's output carrying a tools.MultimodalResult envelope
// must report both the ordinary tool-call event (so the turn
// narrates what ran) and a Media event per URL, so the
// channel has something to actually deliver.
name: "a tool result carrying MultimodalResult URLs reports Media",
parts: []core.StreamPart{
{Type: core.StreamPartToolCall, ToolCall: &core.ToolCall{ToolCallID: "1", ToolName: "generate_video"}},
{Type: core.StreamPartToolResult, ToolResult: &core.ToolResult{
ToolCallID: "1",
ToolName: "generate_video",
Output: `{"is_multimodal":true,"urls":[{"type":"video","url":"https://x/v"}]}`,
}},
},
wantEvents: []string{
`tool:generate_video::{"is_multimodal":true,"urls":[{"type":"video","url":"https://x/v"}]}`,
"media:generate_video:video:",
},
},
{
// A local file has no URL and must not acquire one: the
// channel uploads it. Losing Path here is exactly the
// silent non-delivery send_file exists to end.
name: "a tool result carrying a local path reports Media with that path",
parts: []core.StreamPart{
{Type: core.StreamPartToolCall, ToolCall: &core.ToolCall{ToolCallID: "1", ToolName: "send_file"}},
{Type: core.StreamPartToolResult, ToolResult: &core.ToolResult{
ToolCallID: "1",
ToolName: "send_file",
Output: `{"is_multimodal":true,"urls":[{"type":"document","path":"/tmp/a.md"}]}`,
}},
},
wantEvents: []string{
"tool:send_file::" + `{"is_multimodal":true,"urls":[{"type":"document","path":"/tmp/a.md"}]}`,
"media:send_file:document:/tmp/a.md",
},
},
{
// A ref naming neither a URL nor a path is not deliverable,
// and an empty attachment would render as a delivered file.
name: "a media ref with no source reports no Media event",
parts: []core.StreamPart{
{Type: core.StreamPartToolCall, ToolCall: &core.ToolCall{ToolCallID: "1", ToolName: "odd_tool"}},
{Type: core.StreamPartToolResult, ToolResult: &core.ToolResult{
ToolCallID: "1",
ToolName: "odd_tool",
Output: `{"is_multimodal":true,"urls":[{"type":"document"}]}`,
}},
},
wantEvents: []string{"tool:odd_tool::" + `{"is_multimodal":true,"urls":[{"type":"document"}]}`},
},
{
// An ordinary JSON tool result that happens to be a JSON
// object but isn't a MultimodalResult (no is_multimodal, or
// false) must not be misread as carrying media.
name: "a plain JSON tool result reports no Media event",
parts: []core.StreamPart{
{Type: core.StreamPartToolCall, ToolCall: &core.ToolCall{ToolCallID: "1", ToolName: "read_file"}},
{Type: core.StreamPartToolResult, ToolResult: &core.ToolResult{
ToolCallID: "1",
ToolName: "read_file",
Output: `{"path":"a.txt","content":"hello"}`,
}},
},
wantEvents: []string{`tool:read_file::{"path":"a.txt","content":"hello"}`},
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
sink := &recordingStream{}
text := drainChatStream(streamOf(tc.parts...), sink)
if text != tc.wantText {
t.Fatalf("text = %q, want %q", text, tc.wantText)
}
if len(sink.events) != len(tc.wantEvents) {
t.Fatalf("events = %v, want %v", sink.events, tc.wantEvents)
}
for i := range tc.wantEvents {
if sink.events[i] != tc.wantEvents[i] {
t.Fatalf("events = %v, want %v", sink.events, tc.wantEvents)
}
}
})
}
}
func TestDrainChatStreamCorrelatesBoundsAndRedactsToolParameters(t *testing.T) {
secret := strings.Repeat("s", 200)
sink := &recordingStream{}
drainChatStream(streamOf(
core.StreamPart{Type: core.StreamPartToolCall, ToolCall: &core.ToolCall{
ToolCallID: "call-2",
ToolName: "shell",
Input: `{"cmd":"curl -H 'Authorization: Bearer ` + secret + `'","nested":{"api_token":"` + secret + `"}}`,
}},
core.StreamPart{Type: core.StreamPartToolCall, ToolCall: &core.ToolCall{
ToolCallID: "call-1",
ToolName: "read",
Input: `{"path":"/tmp/one"}`,
}},
core.StreamPart{Type: core.StreamPartToolResult, ToolResult: &core.ToolResult{
ToolCallID: "call-1",
ToolName: "read",
Output: "one",
}},
core.StreamPart{Type: core.StreamPartToolResult, ToolResult: &core.ToolResult{
ToolCallID: "call-2",
ToolName: "shell",
Output: "ok",
}},
), sink)
if len(sink.events) != 2 {
t.Fatalf("events = %v, want two completed calls", sink.events)
}
if sink.events[0] != `tool:read:{"path":"[string]"}:one` {
t.Fatalf("first event = %q, want parameters correlated by call ID", sink.events[0])
}
if strings.Contains(sink.events[1], secret) {
t.Fatalf("second event exposed secret parameters: %q", sink.events[1])
}
if !strings.Contains(sink.events[1], `"api_token":"[redacted]"`) {
t.Fatalf("second event = %q, want redacted token", sink.events[1])
}
if len([]rune(sink.events[1])) > 180 {
t.Fatalf("second event is %d runes, want bounded parameters", len([]rune(sink.events[1])))
}
}
// The stream must be drained to close even when nobody is rendering it:
// ai-sdk writes to FullStream synchronously, so an abandoned stream stalls
// the generating goroutine.
func TestDrainChatStreamWithoutASinkStillCollectsText(t *testing.T) {
text := drainChatStream(streamOf(
core.StreamPart{Type: core.StreamPartTextDelta, TextDelta: "a"},
core.StreamPart{Type: core.StreamPartToolResult, ToolResult: &core.ToolResult{ToolName: "shell", Output: "ok"}},
core.StreamPart{Type: core.StreamPartTextDelta, TextDelta: "b"},
), nil)
if text != "ab" {
t.Fatalf("text = %q, want %q", text, "ab")
}
}
-99
View File
@@ -1,99 +0,0 @@
package main
import (
"context"
"encoding/json"
"github.com/samcharles93/ai-sdk/chat"
"github.com/samcharles93/ai-sdk/core"
"github.com/samcharles93/ai-sdk/runtime"
"github.com/samcharles93/archie-core/internal/agentexec"
"github.com/samcharles93/archie-core/internal/gateway"
"github.com/samcharles93/archie-core/internal/tools"
)
// chatTurnModel adapts the provider-specific ai-sdk runtime to the gateway's
// provider-neutral TurnModel seam. Tool construction remains here because it
// depends on runtime registries and configured execution limits.
type chatTurnModel struct {
llm *runtime.Runtime
registry *tools.Registry
maxSteps int
limits agentexec.ToolLimits
}
func newChatTurnModel(
llm *runtime.Runtime,
registry *tools.Registry,
maxSteps int,
limits agentexec.ToolLimits,
) gateway.TurnModel {
return &chatTurnModel{
llm: llm,
registry: registry,
maxSteps: maxSteps,
limits: limits,
}
}
func (m *chatTurnModel) Prepare(
ctx context.Context,
model string,
extra []tools.ToolEntry,
) (gateway.PreparedTurnModel, error) {
options, err := chatGenerateOptions(ctx, nil, m.registry, m.maxSteps, m.limits, extra)
if err != nil {
return nil, err
}
toolSchema, err := json.Marshal(options.Tools)
if err != nil {
return nil, err
}
return &preparedChatTurnModel{
llm: m.llm,
model: model,
options: options,
toolInfo: toolSummaries(options.Tools),
toolTokens: gateway.EstimateTokens(string(toolSchema)),
}, nil
}
type preparedChatTurnModel struct {
llm *runtime.Runtime
model string
options core.GenerateOptions
toolInfo []gateway.ToolSummary
toolTokens int
}
func (m *preparedChatTurnModel) ToolSummaries() []gateway.ToolSummary {
return append([]gateway.ToolSummary(nil), m.toolInfo...)
}
func (m *preparedChatTurnModel) ToolSchemaTokens() int {
return m.toolTokens
}
func (m *preparedChatTurnModel) Generate(
ctx context.Context,
request gateway.TurnModelRequest,
stream gateway.TurnStream,
) (string, error) {
options := m.options
options.Messages = make([]chat.Message, len(request.Messages))
for i, message := range request.Messages {
role := chat.RoleUser
switch message.Role {
case "assistant":
role = chat.RoleAssistant
case "system":
role = chat.RoleSystem
}
options.Messages[i] = chat.Message{Role: role, Content: message.Content}
}
// This is one provider response's output allowance, not a turn-
// continuation budget. Tool loops remain free to continue.
options.MaxTokens = request.MaxOutputTokens
return sendChatTurn(ctx, m.llm, m.model, options, stream)
}
-121
View File
@@ -1,121 +0,0 @@
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"io"
"os"
"github.com/samcharles93/archie-core/internal/indexing"
)
// flagErrorOutput receives helper diagnostics. It is a variable so tests can
// capture them, and it is deliberately not stdout: the parent parses stdout
// as JSON, so a stray usage message there would corrupt the result.
var flagErrorOutput io.Writer = os.Stderr
// codesearchHelperCommand is the argv[1] token that switches archied out of
// daemon mode and into the codesearch helper.
//
// indexing.Manager deliberately runs the google/codesearch library in a child
// process: upstream calls fatal exits on a corrupt index and leaks mmapped
// regions, neither of which may be allowed to take down a long-lived daemon.
// The child it spawns is this binary, so this name is a contract with
// internal/indexing -- renaming either side silently disables indexed search
// and falls the agent back to unindexed grep.
const codesearchHelperCommand = "workspace-codesearch"
// isCodesearchHelperArgs reports whether args (os.Args[1:]) selects the
// helper rather than the daemon.
func isCodesearchHelperArgs(args []string) bool {
return len(args) > 0 && args[0] == codesearchHelperCommand
}
// runCodesearchHelper executes one helper subcommand and returns a process
// exit code. Output is the machine-readable result the parent decodes; all
// diagnostics go to stderr so they cannot corrupt it.
func runCodesearchHelper(args []string, out io.Writer) int {
if len(args) == 0 {
helperErrorf("%s: expected a subcommand (build|candidates)\n", codesearchHelperCommand)
return 2
}
ctx := context.Background()
switch args[0] {
case "build":
fs := newHelperFlagSet("build")
root := fs.String("root", "", "workspace root to index")
index := fs.String("index", "", "path of the index sidecar to write")
if err := fs.Parse(args[1:]); err != nil {
return 2
}
if *root == "" || *index == "" {
helperErrorf("build: --root and --index are required\n")
return 2
}
if err := indexing.BuildIndex(ctx, *root, *index); err != nil {
helperErrorf("build: %v\n", err)
return 1
}
return 0
case "candidates":
return runCandidates(args[1:], out)
default:
helperErrorf("%s: unknown subcommand %q\n", codesearchHelperCommand, args[0])
return 2
}
}
func newHelperFlagSet(name string) *flag.FlagSet {
fs := flag.NewFlagSet(name, flag.ContinueOnError)
fs.SetOutput(flagErrorOutput)
return fs
}
// runCandidates handles the "candidates" subcommand, returning candidate
// file paths as a JSON array on stdout.
func runCandidates(args []string, out io.Writer) int {
fs := newHelperFlagSet("candidates")
index := fs.String("index", "", "path of the index sidecar to query")
pattern := fs.String("pattern", "", "search pattern")
literal := fs.Bool("literal", false, "treat the pattern as a literal string")
caseSensitive := fs.Bool("case-sensitive", false, "match case sensitively")
if err := fs.Parse(args); err != nil {
return 2
}
if *index == "" || *pattern == "" {
helperErrorf("candidates: --index and --pattern are required\n")
return 2
}
files, err := indexing.IndexCandidates(*index, *pattern, *literal, *caseSensitive)
if err != nil {
helperErrorf("candidates: %v\n", err)
return 1
}
// The parent decodes a JSON array and treats any decode failure as
// "no index", so a nil slice must still marshal as [] rather than null.
if files == nil {
files = []string{}
}
encoded, err := json.Marshal(files)
if err != nil {
helperErrorf("candidates: encode result: %v\n", err)
return 1
}
if _, err := out.Write(encoded); err != nil {
helperErrorf("candidates: write result: %v\n", err)
return 1
}
return 0
}
// helperErrorf writes a diagnostic to stderr. The write result is ignored
// deliberately: if stderr is gone there is nowhere left to report it, and the
// exit code already carries the outcome the parent acts on.
func helperErrorf(format string, args ...any) {
_, _ = fmt.Fprintf(flagErrorOutput, format, args...)
}
-85
View File
@@ -1,85 +0,0 @@
package main
import (
"encoding/json"
"os"
"path/filepath"
"slices"
"strings"
"testing"
)
func TestRunCodesearchHelper(t *testing.T) {
root := t.TempDir()
if err := os.WriteFile(filepath.Join(root, "a.txt"), []byte("alpha needle omega\n"), 0o600); err != nil {
t.Fatalf("write fixture: %v", err)
}
if err := os.WriteFile(filepath.Join(root, "b.txt"), []byte("nothing here\n"), 0o600); err != nil {
t.Fatalf("write fixture: %v", err)
}
indexPath := filepath.Join(t.TempDir(), "workspace.csearch")
t.Run("build writes an index sidecar", func(t *testing.T) {
var out strings.Builder
code := runCodesearchHelper([]string{"build", "--root", root, "--index", indexPath}, &out)
if code != 0 {
t.Fatalf("build exit code = %d, want 0", code)
}
if _, err := os.Stat(indexPath); err != nil {
t.Fatalf("index sidecar not written: %v", err)
}
})
t.Run("candidates emits the JSON contract the manager decodes", func(t *testing.T) {
var out strings.Builder
code := runCodesearchHelper([]string{
"candidates", "--index", indexPath, "--pattern", "needle",
}, &out)
if code != 0 {
t.Fatalf("candidates exit code = %d, want 0", code)
}
var files []string
if err := json.Unmarshal([]byte(out.String()), &files); err != nil {
t.Fatalf("decode candidates output %q: %v", out.String(), err)
}
if !slices.ContainsFunc(files, func(p string) bool {
return strings.HasSuffix(p, "a.txt")
}) {
t.Errorf("candidates = %v, want the file containing the needle", files)
}
})
invalid := []struct {
name string
args []string
}{
{name: "no subcommand", args: nil},
{name: "unknown subcommand", args: []string{"frobnicate"}},
{name: "build without root", args: []string{"build", "--index", indexPath}},
{name: "build without index", args: []string{"build", "--root", root}},
{name: "candidates without index", args: []string{"candidates", "--pattern", "x"}},
{name: "candidates without pattern", args: []string{"candidates", "--index", indexPath}},
}
for _, tc := range invalid {
t.Run(tc.name+" is rejected", func(t *testing.T) {
var out strings.Builder
if code := runCodesearchHelper(tc.args, &out); code == 0 {
t.Errorf("exit code = 0, want non-zero for %v", tc.args)
}
})
}
}
// The manager shells out to argv[0] with this exact subcommand name, so a
// rename on either side silently disables indexed search.
func TestCodesearchHelperSubcommandIsRecognised(t *testing.T) {
if !isCodesearchHelperArgs([]string{codesearchHelperCommand, "build"}) {
t.Errorf("isCodesearchHelperArgs() did not recognise %q", codesearchHelperCommand)
}
if isCodesearchHelperArgs([]string{"-once"}) {
t.Error("isCodesearchHelperArgs() claimed a normal daemon flag")
}
if isCodesearchHelperArgs(nil) {
t.Error("isCodesearchHelperArgs() claimed an empty argument list")
}
}
-24
View File
@@ -1,24 +0,0 @@
package main
import (
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
"github.com/samcharles93/archie-core/internal/infrastructure/configuration/overlay"
)
// 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)
}
-30
View File
@@ -1,30 +0,0 @@
package main
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")
}
}
@@ -1,24 +0,0 @@
package main
import (
"os"
"strings"
"testing"
)
// Autonomous execution has one production composition: managed task
// containers over embedded or external NATS. These old switches must not
// quietly restore a host or no-broker path in the composition root.
func TestCompositionContainsNoAutonomousExecutionOptOut(t *testing.T) {
for _, file := range []string{"bootstrap.go", "main.go"} {
source, err := os.ReadFile(file)
if err != nil {
t.Fatal(err)
}
for _, forbidden := range []string{"NATSModeOff", "Containers.Enabled"} {
if strings.Contains(string(source), forbidden) {
t.Errorf("%s contains removed autonomous execution switch %q", file, forbidden)
}
}
}
}
+4 -1068
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
-127
View File
@@ -1,127 +0,0 @@
package main
import (
"log/slog"
"os"
"path/filepath"
"strings"
"testing"
)
// TestMemoryProviderFallsBackInsteadOfFailing guards the same startup rule as
// TestResolveForgeDegradesInsteadOfFailing: a bad path must not take the
// daemon down. A config copied from another host (a container path such as
// /var/lib/archie/work onto a laptop) has to warn and land on the default,
// not exit 1 and crash-loop under Restart=on-failure.
func TestMemoryProviderFallsBackInsteadOfFailing(t *testing.T) {
tests := []struct {
name string
// workDir builds the configured work directory; the returned string
// is passed to memoryProvider.
workDir func(t *testing.T) string
// wantDefault says the result must be the default location rather
// than the configured one.
wantDefault bool
// wantAvailable says memory must end up actually usable.
wantAvailable bool
}{
{
name: "usable configured directory is kept",
workDir: func(t *testing.T) string { return t.TempDir() },
wantAvailable: true,
},
{
name: "missing configured directory is created",
workDir: func(t *testing.T) string {
return filepath.Join(t.TempDir(), "does", "not", "exist")
},
wantAvailable: true,
},
{
name: "unwritable configured directory falls back to the default",
workDir: func(t *testing.T) string {
ro := filepath.Join(t.TempDir(), "ro")
if err := os.Mkdir(ro, 0o500); err != nil {
t.Fatalf("mkdir: %v", err)
}
return filepath.Join(ro, "work")
},
wantDefault: true,
wantAvailable: true,
},
{
name: "empty work dir falls back to the default",
workDir: func(t *testing.T) string { return "" },
wantDefault: true,
wantAvailable: true,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
if tc.wantDefault && os.Geteuid() == 0 {
t.Skip("running as root: permission cases are not meaningful")
}
// Keep the default location inside the test's own tree so the
// fallback cannot write to the developer's real ~/.local/share.
dataHome := t.TempDir()
t.Setenv("XDG_DATA_HOME", dataHome)
wantDefaultDir := filepath.Join(dataHome, "archie", "work", "memory")
workDir := tc.workDir(t)
provider, dir := memoryProvider(workDir, slog.New(slog.DiscardHandler))
if provider == nil {
t.Fatal("memoryProvider returned nil: startup would exit 1 over a path problem")
}
if got := provider.IsAvailable(); got != tc.wantAvailable {
t.Fatalf("IsAvailable() = %v, want %v (dir %q, err %v)",
got, tc.wantAvailable, dir, provider.Err())
}
if tc.wantDefault {
if dir != wantDefaultDir {
t.Fatalf("dir = %q, want the default %q", dir, wantDefaultDir)
}
} else {
if want := filepath.Join(workDir, "memory"); dir != want {
t.Fatalf("dir = %q, want the configured %q", dir, want)
}
}
if tc.wantAvailable {
if info, err := os.Stat(dir); err != nil || !info.IsDir() {
t.Fatalf("reported available but %q is not a usable directory (err %v)", dir, err)
}
}
})
}
}
// The fallback is only worth anything if the operator can tell it happened
// and why -- a silent switch to a different directory looks like memory loss.
func TestMemoryProviderExplainsTheFallback(t *testing.T) {
if os.Geteuid() == 0 {
t.Skip("running as root: permission cases are not meaningful")
}
t.Setenv("XDG_DATA_HOME", t.TempDir())
ro := filepath.Join(t.TempDir(), "ro")
if err := os.Mkdir(ro, 0o500); err != nil {
t.Fatalf("mkdir: %v", err)
}
configured := filepath.Join(ro, "work")
var sb strings.Builder
log := slog.New(slog.NewTextHandler(&sb, &slog.HandlerOptions{Level: slog.LevelWarn}))
memoryProvider(configured, log)
out := sb.String()
if !strings.Contains(out, configured) {
t.Fatalf("log does not name the rejected directory %q: %s", configured, out)
}
if !strings.Contains(out, "default") {
t.Fatalf("log does not say a default was used: %s", out)
}
}
-55
View File
@@ -1,55 +0,0 @@
package main
import (
"maps"
"slices"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/infrastructure/modelcatalog"
"github.com/samcharles93/archie-core/internal/secret"
)
func applyModelCatalog(cfg *config.Config, snapshot modelcatalog.Snapshot) []string {
discovered := make(map[string]config.Provider, len(snapshot.Providers))
limits := make(map[string]config.ModelLimits)
var models []string
for _, provider := range snapshot.Providers {
discovered[provider.ID] = config.Provider{
Class: provider.Class, APIKeyEnv: provider.APIKeyEnv, BaseURL: provider.BaseURL,
}
for _, model := range provider.Models {
ref := provider.ID + "/" + model.ID
models = append(models, ref)
limits[ref] = config.ModelLimits{ContextWindow: model.ContextWindow, MaxOutputTokens: model.MaxOutputTokens}
}
}
cfg.ModelLimits = limits
cfg.Providers = mergeProviders(discovered, cfg.Providers)
for i := range cfg.Identities {
cfg.Identities[i].Providers = mergeProviders(discovered, cfg.Identities[i].Providers)
}
slices.Sort(models)
return models
}
func mergeProviders(base, overrides map[string]config.Provider) map[string]config.Provider {
merged := make(map[string]config.Provider, len(base)+len(overrides))
maps.Copy(merged, base)
for id, override := range overrides {
resolved := merged[id]
if override.Class != "" {
resolved.Class = override.Class
}
if override.APIKeyEnv != "" {
resolved.APIKeyEnv = override.APIKeyEnv
}
if override.APIKey != (secret.SecretRef{}) {
resolved.APIKey = override.APIKey
}
if override.BaseURL != "" {
resolved.BaseURL = override.BaseURL
}
merged[id] = resolved
}
return merged
}
-55
View File
@@ -1,55 +0,0 @@
package main
import (
"reflect"
"testing"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/infrastructure/modelcatalog"
)
func TestApplyModelCatalogNormalizesEveryExecutionScope(t *testing.T) {
cfg := config.Config{
Providers: map[string]config.Provider{
"openai": {Class: "custom", APIKeyEnv: "CUSTOM_KEY"},
},
Identities: []config.IdentityConfig{
{Name: "one", Providers: map[string]config.Provider{
"identity-only": {Class: "openai-compatible"},
}},
},
}
snapshot := modelcatalog.Snapshot{Providers: []modelcatalog.Provider{
{
ID: "openai", Class: "openai", APIKeyEnv: "OPENAI_API_KEY",
BaseURL: "https://api.openai.test/v1",
Models: []modelcatalog.Model{{ID: "gpt-tool", ContextWindow: 128_000, MaxOutputTokens: 16_000}},
},
{
ID: "anthropic", Class: "anthropic", APIKeyEnv: "ANTHROPIC_API_KEY",
Models: []modelcatalog.Model{{ID: "claude-tool"}},
},
}}
models := applyModelCatalog(&cfg, snapshot)
if got := cfg.Providers["openai"]; got.Class != "custom" || got.APIKeyEnv != "CUSTOM_KEY" {
t.Fatalf("explicit global provider was overwritten: %#v", got)
}
if _, ok := cfg.Providers["anthropic"]; !ok {
t.Fatal("discovered provider missing from global execution config")
}
if _, ok := cfg.Identities[0].Providers["anthropic"]; !ok {
t.Fatal("discovered provider missing from identity execution config")
}
if _, ok := cfg.Identities[0].Providers["identity-only"]; !ok {
t.Fatal("explicit identity provider was removed")
}
wantModels := []string{"anthropic/claude-tool", "openai/gpt-tool"}
if !reflect.DeepEqual(models, wantModels) {
t.Fatalf("models = %v, want %v", models, wantModels)
}
if got := cfg.ModelLimits["openai/gpt-tool"]; got.ContextWindow != 128_000 || got.MaxOutputTokens != 16_000 {
t.Fatalf("model limits = %+v, want catalog capacity", got)
}
}
-78
View File
@@ -1,78 +0,0 @@
package main
import (
"crypto/sha256"
"fmt"
"log/slog"
"os"
"strings"
"github.com/traefik/yaegi/stdlib/unrestricted"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/secret"
"github.com/samcharles93/archie-core/internal/secret/enginehost"
"github.com/samcharles93/archie-core/internal/secret/secretextract"
)
func configuredSecretRegistry(cfg *config.Config, log *slog.Logger) (*secret.Registry, error) {
registry := secret.NewRegistry()
if cfg.SecretEngineDir != "" {
// Secret engines are operator-authored code in the same trust
// domain as the daemon config, and the shipped engines run CLIs
// (sops, vault, age). They shell out through enginehost.Run (the
// host-side helper) because yaegi's interpreted os/exec cannot
// pass an environment to child processes; unrestricted symbols
// are included for parity with skillscript interpretation.
loaded, err := registry.LoadDir(cfg.SecretEngineDir, secretextract.Symbols, enginehost.Symbols, unrestricted.Symbols)
if err != nil {
return nil, fmt.Errorf("load secret engines from %q: %w", cfg.SecretEngineDir, err)
}
log.Info("secret engines loaded", "count", loaded)
}
if err := resolveProviderSecrets(cfg, registry); err != nil {
return nil, fmt.Errorf("resolve provider secrets: %w", err)
}
return registry, nil
}
func resolveProviderSecrets(cfg *config.Config, registry *secret.Registry) error {
if err := resolveProviderMap("root", cfg.Providers, registry); err != nil {
return err
}
for i := range cfg.Identities {
if err := resolveProviderMap(cfg.Identities[i].Name, cfg.Identities[i].Providers, registry); err != nil {
return fmt.Errorf("identity %q: %w", cfg.Identities[i].Name, err)
}
}
return nil
}
func resolveProviderMap(scope string, providers map[string]config.Provider, registry *secret.Registry) error {
for id, provider := range providers {
if provider.APIKey == (secret.SecretRef{}) {
continue
}
value, err := provider.APIKey.Resolve(registry)
if err != nil {
return fmt.Errorf("provider %q: %w", id, err)
}
value = strings.TrimSpace(value)
if value == "" {
return fmt.Errorf("provider %q: resolved api_key is empty", id)
}
envName := providerSecretEnvName(scope, id)
if err := os.Setenv(envName, value); err != nil {
return fmt.Errorf("provider %q: export resolved api_key: %w", id, err)
}
provider.APIKey = secret.SecretRef{}
provider.APIKeyEnv = envName
providers[id] = provider
}
return nil
}
func providerSecretEnvName(scope, providerID string) string {
sum := sha256.Sum256([]byte(scope + "\x00" + providerID))
return fmt.Sprintf("ARCHIE_PROVIDER_%X_API_KEY", sum[:8])
}
-226
View File
@@ -1,226 +0,0 @@
package main
import (
"context"
"log/slog"
"os"
"reflect"
"sync/atomic"
"time"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
)
// ReloadController re-runs the configuration load on demand and
// publishes the result through apply. A failed reload never publishes:
// apply is called only with a Document that passed validation, and the
// running config is left untouched on error. That "Set is not called on
// the error path" property is the safety core of the reload feature --
// a bad file must leave the daemon running on the previous config.
type ReloadController struct {
loader *configuration.Loader
base string
overlay string
// apply receives a freshly loaded, validated Document. It is the
// composition root's job to wire this to whatever owns the running
// config (the daemon's Holder, the dashboard's provenance). Must be
// non-nil; newReloadController requires it.
apply func(*configuration.Document)
// overlayValues, when non-nil, returns the runtime config overlay
// (dotted keys -> typed values) to layer over the file config before
// publishing. A failed overlay read or validation aborts the reload
// exactly like a bad file.
overlayValues func() (map[string]any, error)
status atomic.Pointer[config.ReloadStatus]
}
func newReloadController(loader *configuration.Loader, base, overlay string, apply func(*configuration.Document)) *ReloadController {
c := &ReloadController{loader: loader, base: base, overlay: overlay, apply: apply}
c.status.Store(&config.ReloadStatus{})
return c
}
// Reload re-runs the configuration load. On validation failure it
// records the error in Status and returns it; apply is not called and
// the running configuration is unchanged. On success it calls apply
// with the fresh Document and records the reload time.
func (c *ReloadController) Reload() error {
doc, err := c.loader.Resolve(c.base, c.overlay)
if err != nil {
c.status.Store(&config.ReloadStatus{
LastError: err.Error(),
LastErrorAt: time.Now().UTC().Format(time.RFC3339),
})
return err
}
if c.overlayValues != nil {
values, err := c.overlayValues()
if err != nil {
c.status.Store(&config.ReloadStatus{
LastError: err.Error(),
LastErrorAt: time.Now().UTC().Format(time.RFC3339),
})
return err
}
if len(values) > 0 {
// ApplyOverlay never mutates its input: on failure the
// resolved document (and the running config) is untouched.
if doc, err = c.loader.ApplyOverlay(doc, values); err != nil {
c.status.Store(&config.ReloadStatus{
LastError: err.Error(),
LastErrorAt: time.Now().UTC().Format(time.RFC3339),
})
return err
}
}
}
c.apply(doc)
c.status.Store(&config.ReloadStatus{
LastReloadAt: time.Now().UTC().Format(time.RFC3339),
})
return nil
}
// WithOverlay attaches the runtime config overlay source. Optional: a
// controller without it publishes the file config alone.
func (c *ReloadController) WithOverlay(fn func() (map[string]any, error)) *ReloadController {
c.overlayValues = fn
return c
}
// Status returns the most recent reload outcome.
func (c *ReloadController) Status() config.ReloadStatus {
if p := c.status.Load(); p != nil {
return *p
}
return config.ReloadStatus{}
}
// reloadLoop waits for a reload signal on ch and re-loads the config
// each time, until ctx is cancelled. A failed reload is logged and the
// running config is left untouched (see ReloadController.Reload).
func reloadLoop(ctx context.Context, ch <-chan os.Signal, c *ReloadController, log *slog.Logger) {
for {
select {
case <-ctx.Done():
return
case <-ch:
if err := c.Reload(); err != nil {
log.Error("config reload failed; keeping running config", "err", err)
}
}
}
}
// reloadableFields are the Config fields a reload takes effect on
// without a restart. The criterion: a field is reloadable when EVERY
// consumer re-reads it. That question read as "what does the daemon
// re-read" while the daemon owned the only Holder; it stopped being
// sufficient when webui began sharing that Holder, because webui
// handlers re-read on every request. MaxRetries is the worked example:
// its only consumer is api_tasks.go:380,383, reading per-request
// s.Cfg.Get(), and nothing in the daemon reads it -- so it reloads.
// Chat.Telegram.TokenEnv is the counter-example: webui reads it per
// request AND a telegram bot built at startup consumes it, so it is
// NOT reloadable, and treating "webui reads it" as sufficient would
// display a new token while the bot uses the old one.
//
// This is deliberately an allowlist: a field added to Config later
// defaults to requires-restart, which is the safe direction and forces
// whoever adds it to decide deliberately.
var reloadableFields = map[string]bool{
// Tickers reset on change (daemon.go Run / runIdentities).
"PollInterval": true,
// Poll loops re-read per cycle (daemon.go poll / pollForIdentity).
"Repos": true,
// Per-task snapshot: ForTask carries these into every dispatched
// TaskContext (config.go ForTask), built fresh from d.Cfg.Get() at
// dispatch. Pinned by TestReloadableFieldsCoverForTaskSnapshot so a
// field added to ForTask cannot silently drift out of this list.
"DiffCapLines": true,
"Budgets": true,
"Dispatch": true,
"Models": true,
"ModelLimits": true,
"Notify": true,
// BotUser/BotEmail used to be poll-path only; ForTask now carries both
// into the task snapshot as well, because the sandboxed worker builds
// its own worktree.Manager and signs its own commits (agentworker
// task_execution.go, config.go ForTask). The commit identity is
// therefore per-dispatch and does reload. The startup-built daemon
// trees (bootstrap.go:654) still capture both, but only to record
// user.name/user.email in the clone's own .git/config
// (worktree.go setIdentity) -- cosmetic, not the signature go-git
// commits with -- so a reload applies where it counts and this stays
// reloadable rather than requires-restart.
"BotEmail": true,
// cfg.Label additionally feeds IssuesWithLabel per poll cycle
// (daemon.go:359,390) and cfg.BotUser feeds AssignedIssues (:364,377).
// Label is not carried by ForTask, so it is pinned by hand in
// TestReloadableFieldsCoverForTaskSnapshot.
"Label": true,
"BotUser": true,
// Worked example of the every-consumer criterion above: the sole
// consumer is the webui maxRetriesFor handler (api_tasks.go:380,383),
// which re-reads per request; the daemon never reads MaxRetries. The
// per-task half of this list is pinned mechanically; this webui-only
// entry is pinned by TestChangedNonReloadableFields.
"MaxRetries": true,
// [agent] is a decode-only compatibility shim; changes have no runtime
// consumer and therefore require neither reload nor restart.
"LegacyAgent": true,
}
// reloadableSubFields are sub-fields of structs that are otherwise
// startup-built. VolumeTTL is re-read per cycle in cleanupExpiredStorage;
// everything else in Containers (Image, MaxConcurrency,
// MaxUptime, PullPolicy, Network) is frozen in the startup-built
// container pool -- the dispatchers re-read MaxConcurrency but the pool
// captures it at construction (container/pool.go:94,163), so a change
// only partially applies and must warn requires-restart. Forge.Host is
// carried into TaskContext by ForTask (display/link building only); the
// forge client itself is startup-built, so Type/Token/TokenEnv stay
// requires-restart.
var reloadableSubFields = map[string]map[string]bool{
"Containers": {"LegacyEnabled": true, "VolumeTTL": true},
"Forge": {"Host": true},
}
// changedNonReloadableFields compares old and new and returns the
// dotted names of top-level Config fields whose values differ and are
// not re-read per cycle. The reload log warns about these so the
// operator knows their edit did not take effect until a restart --
// the alternative is an operator who believes a reloaded poll interval
// changed the forge token, and burns an hour discovering it did not.
func changedNonReloadableFields(old, next config.Config) []string {
var changed []string
ov, nv := reflect.ValueOf(old), reflect.ValueOf(next)
ot := reflect.TypeFor[config.Config]()
for i := 0; i < ot.NumField(); i++ {
f := ot.Field(i)
name := f.Name
if reloadableFields[name] {
continue
}
if subs, ok := reloadableSubFields[name]; ok && f.Type.Kind() == reflect.Struct {
for j := 0; j < f.Type.NumField(); j++ {
sub := f.Type.Field(j).Name
if subs[sub] {
continue
}
if !reflect.DeepEqual(ov.Field(i).Field(j).Interface(), nv.Field(i).Field(j).Interface()) {
changed = append(changed, name+"."+sub)
}
}
continue
}
if !reflect.DeepEqual(ov.Field(i).Interface(), nv.Field(i).Interface()) {
changed = append(changed, name)
}
}
return changed
}
-300
View File
@@ -1,300 +0,0 @@
package main
import (
"context"
"errors"
"log/slog"
"os"
"path/filepath"
"reflect"
"sync"
"syscall"
"testing"
"time"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
)
// writeConfig writes a TOML config file. The minimal shape (bot_user +
// one repo) is the same fixture loader_test.go uses to satisfy
// validation.
func writeConfig(t *testing.T, path, body string) {
t.Helper()
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
t.Fatal(err)
}
}
func minimalConfigTOML(botUser string) string {
return "bot_user = \"" + botUser + "\"\n[[repos]]\nowner = \"acme\"\nname = \"app\"\n"
}
func invalidConfigTOML() string {
return "bot_user = \"widget\"\ndispatch = { trigger = \"bogus-trigger\" }\n[[repos]]\nowner = \"acme\"\nname = \"app\"\n"
}
func TestReloadAppliesAndPublishes(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "config.toml")
writeConfig(t, path, minimalConfigTOML("first"))
loader := configuration.New(slog.New(slog.DiscardHandler))
var published config.Config
controller := newReloadController(loader, path, "", func(doc *configuration.Document) {
published = doc.Config
})
if err := controller.Reload(); err != nil {
t.Fatalf("first reload: %v", err)
}
if published.BotUser != "first" {
t.Fatalf("published BotUser = %q, want first", published.BotUser)
}
writeConfig(t, path, minimalConfigTOML("second"))
if err := controller.Reload(); err != nil {
t.Fatalf("second reload: %v", err)
}
if published.BotUser != "second" {
t.Fatalf("published BotUser = %q, want second", published.BotUser)
}
if st := controller.Status(); st.LastReloadAt == "" || st.LastError != "" {
t.Fatalf("Status after success = %+v, want LastReloadAt set and no error", st)
}
}
// TestReloadValidationFailureDoesNotApply pins the safety property of
// the whole reload feature: a reload that fails validation must not
// publish. If apply were called on the error path, a bad file would
// half-apply or corrupt the running config.
func TestReloadValidationFailureDoesNotApply(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "config.toml")
writeConfig(t, path, minimalConfigTOML("widget"))
loader := configuration.New(slog.New(slog.DiscardHandler))
applied := 0
controller := newReloadController(loader, path, "", func(*configuration.Document) { applied++ })
if err := controller.Reload(); err != nil {
t.Fatalf("first reload: %v", err)
}
if applied != 1 {
t.Fatalf("apply called %d times after successful reload, want 1", applied)
}
writeConfig(t, path, invalidConfigTOML())
err := controller.Reload()
if err == nil {
t.Fatal("reload with invalid config: expected an error")
}
if applied != 1 {
t.Fatalf("apply called %d times after failed reload, want still 1", applied)
}
if st := controller.Status(); st.LastError == "" || st.LastErrorAt == "" {
t.Fatalf("Status after failed reload = %+v, want LastError and LastErrorAt set", st)
}
// A subsequent valid reload clears the error.
writeConfig(t, path, minimalConfigTOML("widget"))
if err := controller.Reload(); err != nil {
t.Fatalf("recovery reload: %v", err)
}
if st := controller.Status(); st.LastError != "" || st.LastReloadAt == "" {
t.Fatalf("Status after recovery = %+v, want no error and a reload time", st)
}
}
func TestReloadAppliesOverlayBeforePublish(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "config.toml")
writeConfig(t, path, minimalConfigTOML("widget"))
loader := configuration.New(slog.New(slog.DiscardHandler))
var published config.Config
controller := newReloadController(loader, path, "", func(doc *configuration.Document) {
published = doc.Config
}).WithOverlay(func() (map[string]any, error) {
return map[string]any{"poll_interval": "90s"}, nil
})
if err := controller.Reload(); err != nil {
t.Fatal(err)
}
if published.PollInterval != config.Duration(90*time.Second) {
t.Errorf("PollInterval = %v, want 90s (overlay applied before publish)", published.PollInterval)
}
}
// TestReloadOverlayFailureAborts pins that a failed overlay read or
// validation aborts the reload exactly like a bad file: apply is not
// called and the error is recorded.
func TestReloadOverlayFailureAborts(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "config.toml")
writeConfig(t, path, minimalConfigTOML("widget"))
loader := configuration.New(slog.New(slog.DiscardHandler))
applied := 0
controller := newReloadController(loader, path, "", func(*configuration.Document) { applied++ }).
WithOverlay(func() (map[string]any, error) {
return nil, errors.New("overlay unreadable")
})
if err := controller.Reload(); err == nil {
t.Fatal("expected an error from the failed overlay")
}
if applied != 0 {
t.Fatalf("apply called %d times after overlay failure, want 0", applied)
}
if st := controller.Status(); st.LastError == "" {
t.Fatal("expected LastError recorded")
}
}
func TestReloadLoopAppliesOnSignalAndStopsOnCancel(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "config.toml")
writeConfig(t, path, minimalConfigTOML("widget"))
loader := configuration.New(slog.New(slog.DiscardHandler))
applied := make(chan struct{}, 1)
controller := newReloadController(loader, path, "", func(*configuration.Document) {
applied <- struct{}{}
})
ctx, cancel := context.WithCancel(context.Background())
ch := make(chan os.Signal, 1)
var wg sync.WaitGroup
wg.Go(func() {
reloadLoop(ctx, ch, controller, slog.New(slog.DiscardHandler))
})
ch <- syscall.SIGHUP
select {
case <-applied:
case <-time.After(5 * time.Second):
t.Fatal("reload not applied after signal")
}
cancel()
wg.Wait()
}
func TestChangedNonReloadableFields(t *testing.T) {
base := config.Config{
BotUser: "a",
MaxRetries: 3,
PollInterval: config.Duration(30 * time.Second),
Repos: []config.Repo{{Owner: "x", Name: "y"}},
}
// Unchanged -> empty.
if got := changedNonReloadableFields(base, base); len(got) != 0 {
t.Fatalf("unchanged: got %v, want []", got)
}
// Reloadable-only changes -> empty.
reloadableOnly := base
reloadableOnly.PollInterval = config.Duration(60 * time.Second)
reloadableOnly.Repos = []config.Repo{{Owner: "x", Name: "z"}}
reloadableOnly.Budgets = config.Budgets{MaxSteps: 99}
reloadableOnly.Dispatch = config.Dispatch{Trigger: "label"}
reloadableOnly.DiffCapLines = 1234
reloadableOnly.Models = map[string]string{"builder": "provider/model"}
reloadableOnly.Notify = config.Notify{Webhook: "https://notify.example/hook"}
reloadableOnly.Label = "archie"
reloadableOnly.BotUser = "new-bot"
reloadableOnly.Forge = config.Forge{Host: "https://new-forge.example"}
reloadableOnly.MaxRetries = 5
if got := changedNonReloadableFields(base, reloadableOnly); len(got) != 0 {
t.Fatalf("reloadable-only: got %v, want []", got)
}
// The removed [agent] section remains decode-only for old files. Changing
// it has no running consumer and must not claim a restart will apply it.
legacyOnly := base
legacyOnly.LegacyAgent = config.LegacyAgent{Mode: "subprocess"}
if got := changedNonReloadableFields(base, legacyOnly); len(got) != 0 {
t.Fatalf("legacy agent change: got %v, want []", got)
}
legacyContainers := base
legacyContainers.Containers.LegacyEnabled = true
if got := changedNonReloadableFields(base, legacyContainers); len(got) != 0 {
t.Fatalf("legacy containers.enabled change: got %v, want []", got)
}
// Containers sub-field granularity: Image change warns, MaxConcurrency
// and VolumeTTL changes do not.
c1 := base
c1.Containers = config.ContainerConfig{Image: "img1", MaxConcurrency: 2, VolumeTTL: config.Duration(24 * time.Hour)}
c2 := c1
c2.Containers.Image = "img2"
if got := changedNonReloadableFields(c1, c2); len(got) != 1 || got[0] != "Containers.Image" {
t.Fatalf("Image change: got %v, want [Containers.Image]", got)
}
c3 := c1
c3.Containers.MaxConcurrency = 4
// MaxConcurrency is NOT reloadable: the dispatchers re-read it but the
// startup-built container pool captures it (container/pool.go:94), so
// a change only partially applies and must warn requires-restart.
if got := changedNonReloadableFields(c1, c3); len(got) != 1 || got[0] != "Containers.MaxConcurrency" {
t.Fatalf("MaxConcurrency change: got %v, want [Containers.MaxConcurrency]", got)
}
c4 := c1
c4.Containers.VolumeTTL = config.Duration(48 * time.Hour)
if got := changedNonReloadableFields(c1, c4); len(got) != 0 {
t.Fatalf("VolumeTTL change: got %v, want []", got)
}
// NATS is not reloadable: a URL change warns (the daemon's client is
// startup-built; containers get the frozen ConnectedNATS).
natsChanged := base
natsChanged.NATS = config.NATSConfig{URL: "nats://new:4222"}
if got := changedNonReloadableFields(base, natsChanged); len(got) != 1 || got[0] != "NATS" {
t.Fatalf("NATS change: got %v, want [NATS]", got)
}
// Forge.Host is reloadable but Forge.Type is not: only the host is
// carried into TaskContext by ForTask.
forgeTypeChanged := base
forgeTypeChanged.Forge = config.Forge{Type: "gitea"}
if got := changedNonReloadableFields(base, forgeTypeChanged); len(got) != 1 || got[0] != "Forge.Type" {
t.Fatalf("Forge.Type change: got %v, want [Forge.Type]", got)
}
}
// TestReloadableFieldsCoverForTaskSnapshot pins the allowlist against
// the per-dispatch snapshot: every field ForTask carries into a
// TaskContext is re-read at dispatch, so a reload applies to new tasks.
// If a field is added to ForTask later, this test fails until the
// allowlist is updated -- a hand-maintained list that mirrors ForTask
// otherwise drifts silently into a wrong 'requires a restart' warning.
func TestReloadableFieldsCoverForTaskSnapshot(t *testing.T) {
tt := reflect.TypeFor[config.TaskConfig]()
for field := range tt.Fields() {
name := field.Name
if name == "Forge" {
// TaskConfig.Forge is TaskForge{Host}; it maps to the
// Config.Forge.Host sub-field allowlist entry.
if !reloadableSubFields["Forge"]["Host"] {
t.Errorf("ForTask field Forge (Host) is not allowlisted as reloadable")
}
continue
}
if !reloadableFields[name] {
t.Errorf("ForTask field %s is not allowlisted as reloadable", name)
}
}
// Label is not carried by ForTask; BotUser now is, but it is also read
// on the poll path independently of the task snapshot. Pin both by hand
// so a refactor that moves either read site -- including one that drops
// BotUser from ForTask again -- does not silently drop the allowlist
// entry the poll path still depends on.
for _, name := range []string{"Label", "BotUser"} {
if !reloadableFields[name] {
t.Errorf("poll-path field %s is not allowlisted as reloadable", name)
}
}
}
-40
View File
@@ -1,40 +0,0 @@
package main
import (
"errors"
"os"
"path/filepath"
"testing"
)
func TestProductionTaskStoreUsesSQLite(t *testing.T) {
configuredPath := filepath.Join(t.TempDir(), "state.db")
path := taskDBPath(configuredPath)
if path == configuredPath {
t.Fatal("task database must use an independent fresh path")
}
st, err := openProductionTaskStore(t.Context(), path)
if err != nil {
t.Fatal(err)
}
if _, err := os.Stat(configuredPath); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("configured anchor path was opened directly: %v", err)
}
inserted, err := st.EnqueueIssue(t.Context(), "acme", "widget", 7, "persisted", "", "", "")
if err != nil || !inserted {
t.Fatalf("EnqueueIssue = (%v, %v), want (true, nil)", inserted, err)
}
if err := st.Close(); err != nil {
t.Fatal(err)
}
st, err = openProductionTaskStore(t.Context(), path)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = st.Close() })
task, err := st.TaskByIssue(t.Context(), "acme", "widget", 7)
if err != nil || task == nil || task.Title != "persisted" {
t.Fatalf("TaskByIssue after reopen = (%+v, %v)", task, err)
}
}
-340
View File
@@ -1,340 +0,0 @@
package main
import (
"context"
"path/filepath"
"strings"
"testing"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/store"
"github.com/samcharles93/archie-core/internal/taskstate"
"github.com/samcharles93/archie-core/internal/webui"
)
func TestChatTaskActorAdapterCrossIdentityRefused(t *testing.T) {
ctx := context.Background()
st, err := store.Open(ctx, filepath.Join(t.TempDir(), "tasks.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = st.Close() })
task, err := st.EnqueueChatTask(ctx, "acme", "widget", "parked job", "", "", "identity-owner")
if err != nil {
t.Fatal(err)
}
if err := st.Transition(ctx, task.ID, store.StatusQueued, store.StatusParked, "needs help"); err != nil {
t.Fatal(err)
}
srv := &webui.Server{Store: st, Cfg: config.NewHolder(config.Config{})}
adapter := chatTaskActorAdapter{
tasks: st.TaskByID,
handler: srv.Handler(),
token: func() string { return srv.Token },
}
tests := []struct {
name string
actorIdentity string
action taskstate.Action
}{
{
name: "different identity cannot abandon",
actorIdentity: "identity-attacker",
action: taskstate.ActionAbandon,
},
{
name: "different identity cannot retry",
actorIdentity: "identity-attacker",
action: taskstate.ActionRetry,
},
{
name: "different identity cannot archive",
actorIdentity: "identity-attacker",
action: taskstate.ActionArchive,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
_, err := adapter.ApplyChatTaskAction(ctx, tc.actorIdentity, task.ID, tc.action)
if err == nil {
t.Fatalf("ApplyChatTaskAction() allowed cross-identity action %s by %q on task owned by %q",
tc.action, tc.actorIdentity, task.Identity)
}
if !strings.Contains(err.Error(), "identity-owner") || !strings.Contains(err.Error(), tc.actorIdentity) {
t.Errorf("error = %q, want mention of both identities", err.Error())
}
// Confirm store state was NOT mutated.
current, err := st.TaskByID(ctx, task.ID)
if err != nil || current == nil {
t.Fatalf("TaskByID = (%+v, %v)", current, err)
}
if current.Status != store.StatusParked {
t.Errorf("task status mutated to %q despite cross-identity refusal", current.Status)
}
})
}
}
func TestChatTaskActorAdapterRefusesDisallowedStateAction(t *testing.T) {
ctx := context.Background()
st, err := store.Open(ctx, filepath.Join(t.TempDir(), "tasks.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = st.Close() })
srv := &webui.Server{Store: st, Cfg: config.NewHolder(config.Config{})}
adapter := chatTaskActorAdapter{
tasks: st.TaskByID,
handler: srv.Handler(),
token: func() string { return srv.Token },
}
tests := []struct {
name string
initialStatus string
attemptAction taskstate.Action
}{
{
name: "cannot abandon running task",
initialStatus: store.StatusRunning,
attemptAction: taskstate.ActionAbandon,
},
{
name: "cannot archive parked task",
initialStatus: store.StatusParked,
attemptAction: taskstate.ActionArchive,
},
{
name: "cannot retry queued task",
initialStatus: store.StatusQueued,
attemptAction: taskstate.ActionRetry,
},
{
name: "cannot approve running task",
initialStatus: store.StatusRunning,
attemptAction: taskstate.ActionApprove,
},
{
name: "cannot reject merged task",
initialStatus: store.StatusMerged,
attemptAction: taskstate.ActionReject,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
task, err := st.EnqueueChatTask(ctx, "acme", "widget", "test task", "", "", "archie")
if err != nil {
t.Fatal(err)
}
if tc.initialStatus != store.StatusQueued {
if err := st.Transition(ctx, task.ID, store.StatusQueued, tc.initialStatus, "setup"); err != nil {
t.Fatal(err)
}
}
_, err = adapter.ApplyChatTaskAction(ctx, "archie", task.ID, tc.attemptAction)
if err == nil {
t.Fatalf("expected error attempting %s on %s task, got nil", tc.attemptAction, tc.initialStatus)
}
// Assert error matches taskstate rules.
wantErr := taskstate.CheckAction(tc.initialStatus, tc.attemptAction)
if wantErr != nil && !strings.Contains(err.Error(), wantErr.Error()) {
t.Errorf("error = %q, want substring %q", err.Error(), wantErr.Error())
}
// Ensure task status did not change.
current, err := st.TaskByID(ctx, task.ID)
if err != nil || current == nil {
t.Fatalf("TaskByID = (%+v, %v)", current, err)
}
if current.Status != tc.initialStatus {
t.Errorf("task status changed to %q, want %q", current.Status, tc.initialStatus)
}
})
}
}
func TestChatTaskActorAdapterTaskNotFound(t *testing.T) {
ctx := context.Background()
st, err := store.Open(ctx, filepath.Join(t.TempDir(), "tasks.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = st.Close() })
srv := &webui.Server{Store: st, Cfg: config.NewHolder(config.Config{})}
adapter := chatTaskActorAdapter{
tasks: st.TaskByID,
handler: srv.Handler(),
token: func() string { return srv.Token },
}
_, err = adapter.ApplyChatTaskAction(ctx, "archie", 999999, taskstate.ActionAbandon)
if err == nil {
t.Fatal("expected error for non-existent task, got nil")
}
if !strings.Contains(err.Error(), "not found") {
t.Errorf("error = %q, want 'not found'", err.Error())
}
}
func TestChatTaskActorAdapterAppliesActionsToStore(t *testing.T) {
tests := []struct {
name string
initialStatus string
action taskstate.Action
wantStatus string
wantArchived bool
}{
{
name: "abandon parked task closes it won't do",
initialStatus: store.StatusParked,
action: taskstate.ActionAbandon,
wantStatus: store.StatusClosedWontDo,
},
{
name: "retry parked task requeues it",
initialStatus: store.StatusParked,
action: taskstate.ActionRetry,
wantStatus: store.StatusQueued,
},
{
name: "cancel queued task closes it",
initialStatus: store.StatusQueued,
action: taskstate.ActionCancel,
wantStatus: store.StatusClosedWontDo,
},
{
name: "approve waiting_human task queues it",
initialStatus: store.StatusWaitingHuman,
action: taskstate.ActionApprove,
wantStatus: store.StatusQueued,
},
{
name: "reject waiting_human task closes it",
initialStatus: store.StatusWaitingHuman,
action: taskstate.ActionReject,
wantStatus: store.StatusClosedWontDo,
},
{
name: "archive dead task removes it from store",
initialStatus: store.StatusDead,
action: taskstate.ActionArchive,
wantArchived: true,
},
{
name: "archive closed_wont_do task removes it from store",
initialStatus: store.StatusClosedWontDo,
action: taskstate.ActionArchive,
wantArchived: true,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
ctx := context.Background()
st, err := store.Open(ctx, filepath.Join(t.TempDir(), "tasks.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = st.Close() })
srv := &webui.Server{Store: st, Cfg: config.NewHolder(config.Config{MaxRetries: 3})}
adapter := chatTaskActorAdapter{
tasks: st.TaskByID,
handler: srv.Handler(),
token: func() string { return srv.Token },
}
task, err := st.EnqueueChatTask(ctx, "acme", "widget", "actionable task", "", "", "archie")
if err != nil {
t.Fatal(err)
}
if tc.initialStatus != store.StatusQueued {
if err := st.Transition(ctx, task.ID, store.StatusQueued, tc.initialStatus, "setup"); err != nil {
t.Fatal(err)
}
}
result, err := adapter.ApplyChatTaskAction(ctx, "archie", task.ID, tc.action)
if err != nil {
t.Fatalf("ApplyChatTaskAction(%s) error = %v", tc.action, err)
}
if result.TaskID != task.ID {
t.Errorf("result.TaskID = %d, want %d", result.TaskID, task.ID)
}
if result.Action != string(tc.action) {
t.Errorf("result.Action = %q, want %q", result.Action, tc.action)
}
current, err := st.TaskByID(ctx, task.ID)
if err != nil {
t.Fatal(err)
}
if tc.wantArchived {
if current != nil {
t.Errorf("task %d still exists in store after archive: %+v", task.ID, current)
}
} else {
if current == nil {
t.Fatalf("task %d not found in store", task.ID)
}
if current.Status != tc.wantStatus {
t.Errorf("task status = %q, want %q", current.Status, tc.wantStatus)
}
}
})
}
}
func TestChatTaskActorAdapterWithTokenAuth(t *testing.T) {
ctx := context.Background()
st, err := store.Open(ctx, filepath.Join(t.TempDir(), "tasks.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = st.Close() })
srv := &webui.Server{
Store: st,
Cfg: config.NewHolder(config.Config{MaxRetries: 3}),
Token: "secret-token-12345",
}
adapter := chatTaskActorAdapter{
tasks: st.TaskByID,
handler: srv.Handler(),
token: func() string { return srv.Token },
}
task, err := st.EnqueueChatTask(ctx, "acme", "widget", "auth task", "", "", "archie")
if err != nil {
t.Fatal(err)
}
if err := st.Transition(ctx, task.ID, store.StatusQueued, store.StatusParked, "park"); err != nil {
t.Fatal(err)
}
result, err := adapter.ApplyChatTaskAction(ctx, "archie", task.ID, taskstate.ActionAbandon)
if err != nil {
t.Fatalf("ApplyChatTaskAction with token auth failed: %v", err)
}
if result.TaskID != task.ID {
t.Errorf("result.TaskID = %d, want %d", result.TaskID, task.ID)
}
current, err := st.TaskByID(ctx, task.ID)
if err != nil || current == nil {
t.Fatalf("TaskByID = (%+v, %v)", current, err)
}
if current.Status != store.StatusClosedWontDo {
t.Errorf("status = %q, want %q", current.Status, store.StatusClosedWontDo)
}
}
-113
View File
@@ -1,113 +0,0 @@
package main
import (
"bytes"
"context"
"net/http"
"net/http/httptest"
"path/filepath"
"strconv"
"testing"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/gateway"
"github.com/samcharles93/archie-core/internal/store"
"github.com/samcharles93/archie-core/internal/webui"
)
// The dashboard and chat both let an operator approve or decline a task, and
// they had drifted: declining from the dashboard left the task
// closed_wont_do, cancelling the same task from chat left it rejected. Two
// operators looking at one queue saw different states for the same decision,
// and "rejected" -- which reconcilePRs uses for a pull request closed without
// merging -- no longer meant one thing.
//
// This drives both real surfaces against one store and asserts they agree.
// It lives in cmd/archied because that is the only place both are wired.
func TestDashboardAndChatAgreeOnTerminalStates(t *testing.T) {
tests := []struct {
name string
// viaChat runs the action through the chat router; otherwise it
// goes through the dashboard's HTTP handler.
viaChat bool
action string
want string
}{
{name: "dashboard reject", action: "reject", want: store.StatusClosedWontDo},
{name: "chat cancel", viaChat: true, action: "cancel", want: store.StatusClosedWontDo},
{name: "dashboard approve", action: "approve", want: store.StatusQueued},
{name: "chat approve", viaChat: true, action: "approve", want: store.StatusQueued},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
ctx := context.Background()
st, err := store.Open(ctx, filepath.Join(t.TempDir(), "tasks.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = st.Close() })
task, err := st.EnqueueChatTask(ctx, "acme", "widget", "decide on me", "", "", "reviewer")
if err != nil {
t.Fatal(err)
}
if err := st.Transition(ctx, task.ID, store.StatusQueued, store.StatusWaitingHuman, "await"); err != nil {
t.Fatal(err)
}
if tc.viaChat {
runChatAction(t, ctx, st, tc.action, task.ID)
} else {
runDashboardAction(t, ctx, st, tc.action, task.ID)
}
got, err := st.TaskByID(ctx, task.ID)
if err != nil || got == nil {
t.Fatalf("TaskByID = (%+v, %v)", got, err)
}
if got.Status != tc.want {
t.Errorf("status = %q, want %q: the two surfaces disagree about "+
"what this action means", got.Status, tc.want)
}
})
}
}
// runChatAction performs the approve/cancel action through the chat
// controller path and fails the test on error.
func runChatAction(t *testing.T, ctx context.Context, st store.TaskStore, action string, taskID int64) {
t.Helper()
controller := gateway.NewStoreTaskController(chatTaskControllerAdapter{
taskByID: st.TaskByID,
requeue: st.Requeue,
transition: st.Transition,
})
var err error
if action == "approve" {
err = controller.Approve(ctx, taskID, "reviewer")
} else {
err = controller.Cancel(ctx, taskID, "reviewer")
}
if err != nil {
t.Fatalf("chat %s: %v", action, err)
}
}
// runDashboardAction performs the approve/cancel action through the
// dashboard's HTTP handler and fails the test when the request is
// rejected.
func runDashboardAction(t *testing.T, ctx context.Context, st store.TaskStore, action string, taskID int64) {
t.Helper()
srv := &webui.Server{Store: st, Cfg: config.NewHolder(config.Config{MaxRetries: 3})}
req := httptest.NewRequestWithContext(ctx, http.MethodPost,
"/api/tasks/"+strconv.FormatInt(taskID, 10)+"/action",
bytes.NewBufferString(`{"action":"`+action+`"}`))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Archie-CSRF", "1")
w := httptest.NewRecorder()
srv.Handler().ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("dashboard %s: status %d, body %s", action, w.Code, w.Body)
}
}
@@ -1,41 +0,0 @@
package main
import (
"bytes"
"fmt"
"os"
"path/filepath"
"testing"
"github.com/samcharles93/archie-core/internal/config"
)
func TestTelegramConversationStoreUsesFreshSQLiteWithoutReadingTaskLog(t *testing.T) {
taskLogPath := filepath.Join(t.TempDir(), "tasks.db")
taskLog := []byte("not a SQLite database")
if err := os.WriteFile(taskLogPath, taskLog, 0o600); err != nil {
t.Fatalf("write task log fixture: %v", err)
}
sessions, err := makeTelegramSessionStore(config.Config{
DBPath: taskLogPath,
})
if err != nil {
t.Fatalf("makeTelegramSessionStore: %v", err)
}
t.Cleanup(func() { _ = sessions.Close() })
if got, want := fmt.Sprintf("%T", sessions), "*gateway.sqliteSessionStore"; got != want {
t.Fatalf("conversation store type = %q, want %q", got, want)
}
if _, err := os.Stat(conversationDBPath(taskLogPath)); err != nil {
t.Fatalf("stat conversation database: %v", err)
}
gotTaskLog, err := os.ReadFile(taskLogPath)
if err != nil {
t.Fatalf("read task log fixture: %v", err)
}
if !bytes.Equal(gotTaskLog, taskLog) {
t.Fatalf("task log changed during conversation-store cutover: got %q, want %q", gotTaskLog, taskLog)
}
}
-474
View File
@@ -1,474 +0,0 @@
package main
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"os"
"path/filepath"
"strings"
"github.com/samcharles93/ai-sdk/chat"
"github.com/samcharles93/ai-sdk/core"
"github.com/samcharles93/ai-sdk/runtime"
channelruntime "github.com/samcharles93/archie-core/internal/channels"
"github.com/samcharles93/archie-core/internal/channels/telegram"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/daemon"
"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/installtype"
"github.com/samcharles93/archie-core/internal/releaseannounce"
"github.com/samcharles93/archie-core/internal/releaseupdate"
"github.com/samcharles93/archie-core/internal/store"
"github.com/samcharles93/archie-core/internal/tools"
)
// telegramSetup contains the inputs needed to initialise the Telegram
// chat gateway. Every field is intentionally explicit so the function
// signature acts as a contract of what the gateway depends on.
type telegramSetup struct {
// Cfg is read once per setup function via Get(); the daemon is not
// running yet at this point, so the reload-safe Holder is mostly a
// formality, but matching the daemon's API keeps callers honest.
Cfg *config.Holder
CfgPath string
OverlayPath string
St store.TaskStore
LLM *runtime.Runtime
ChatModels gateway.ModelManager
ToolReg *tools.Registry
Personas *gateway.PersonaRegistry
ChatTasks gateway.TaskCreator
ChatController gateway.TaskController
ChatTaskLister gateway.ChatTaskLister
ChatTaskLogs gateway.ChatTaskLogReader
ChatTaskActor gateway.ChatTaskActor
DefaultChatIdentity string
SessionStore gateway.SessionStore
Updates telegram.UpdateService
Dangerous gateway.DangerousCommandAuthority
RegisterRestart func(func() error)
// 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
ChannelManager *channelruntime.Manager
// AgentStatus is the composition root's shared tracker for the most
// recently observed archie-agent version (see daemon.AgentStatus).
// Nil disables the agent component of RunningVersions.
AgentStatus *daemon.AgentStatus
}
// setupTelegramGateway initialises the Telegram chat gateway when a
// token is configured. It returns a start function (nil when no token
// is configured) and ok=false to signal the caller must exit early.
func setupTelegramGateway(ctx context.Context, s telegramSetup) (start func(), ok bool) {
cfg := s.Cfg.Get()
if cfg.Chat.Telegram.TokenEnv == "" {
return nil, true
}
tgToken := os.Getenv(cfg.Chat.Telegram.TokenEnv)
if tgToken == "" {
s.Log.Error("chat.telegram configured but token env var is empty", "env", cfg.Chat.Telegram.TokenEnv)
return nil, false
}
if len(cfg.Chat.Telegram.AllowedUserIDs) == 0 {
s.Log.Warn("chat.telegram has no allowed_user_ids: every sender will be rejected. " +
"Add your Telegram user id to chat.telegram.allowed_user_ids to enable the bot.")
}
tg := telegram.New(tgToken, "", "", cfg.Chat.Telegram.AllowedUserIDs, s.Log)
if s.RegisterRestart != nil {
s.RegisterRestart(tg.RequestRestart)
}
tg.Version = func() string {
return fmt.Sprintf("Archie\nGateway: %s\nRuntime: %s", gatewayVersion, runtimeVersion)
}
if s.Updates != nil {
tg.Updates = s.Updates
} else {
configureTelegramUpdates(tg, s)
}
tg.Dangerous = s.Dangerous
tg.SetShowToolCalls(cfg.Chat.ShowToolCalls)
tg.ReleaseAnnouncements = &releaseannounce.Announcer{
StatePath: releaseAnnouncementStatePath(cfg.WorkDir, cfg.BotUser),
Components: []releaseannounce.Component{
{ID: "gateway", Label: "THE GATEWAY", Version: gatewayVersion, ChangelogPath: packagedGatewayChangelogPath},
{ID: "runtime", Label: "THE RUNTIME", Version: runtimeVersion, ChangelogPath: packagedRuntimeChangelogPath},
},
}
tg.UpdateReportPath = updateReportPath(cfg.WorkDir, cfg.BotUser)
agentStatus := s.AgentStatus
tg.RunningVersions = func() map[string]string { return daemonRunningVersions(agentStatus) }
tg.Reload = makeTelegramReload(s)
sessionStore := s.SessionStore
if sessionStore == nil {
s.Log.Error("telegram conversation store is not configured")
return nil, false
}
router := buildTelegramRouter(ctx, tg, s, sessionStore)
return func() {
if s.ChannelManager != nil {
s.ChannelManager.MarkStarting("telegram")
}
go func() {
if err := tg.Start(ctx, router); err != nil && ctx.Err() == nil {
if s.ChannelManager != nil {
s.ChannelManager.MarkFailed("telegram", err.Error())
}
s.Log.Error("telegram gateway stopped", "err", err)
}
}()
s.Log.Info("telegram gateway started")
}, true
}
// daemonRunningVersions reports the component versions this process can
// vouch for, for checking a pending update report against (see
// releaseupdate.Report.Verify).
//
// The daemon component is always vouched for from its own build:
// gatewayVersion is compiled into this binary, so if an installer claims it
// put a version into service and this value disagrees, the installer is
// wrong. runtimeVersion is deliberately NOT used for the agent component --
// it records the agent version archied's own release pipeline stamped, not
// the version an agent container is actually running, and the two diverge in
// exactly the situation this check exists to detect.
//
// The agent component is included only once agentStatus has actually
// observed one running -- self-reported by an archie-agent worker in a
// taskrun.Response (see daemon.AgentStatus), since every archie-agent
// process is task-scoped and ephemeral, not something this process can query
// directly. Before the first task completes, or when agentStatus is nil
// (composition never wired one), the agent component is left out entirely
// so it reports as unchecked rather than as confirmed.
func daemonRunningVersions(agentStatus *daemon.AgentStatus) map[string]string {
versions := map[string]string{releaseupdate.ComponentDaemon: gatewayVersion}
if agentStatus != nil {
if version, _, ok := agentStatus.Snapshot(); ok {
versions[releaseupdate.ComponentAgent] = version
}
}
return versions
}
// componentInstallTypeEnricher builds Service.Enrich: it knows how to
// describe the three component kinds this daemon can say anything true
// about. Anything else (a check command reporting a component ID this
// process has no source for) is left alone -- an empty return leaves
// whatever the check command itself set.
func componentInstallTypeEnricher(agentStatus *daemon.AgentStatus, nats config.NATSConfig) func(string) (string, string) {
return func(componentID string) (installType, reference string) {
switch componentID {
case releaseupdate.ComponentDaemon:
return installtype.Type(), ""
case releaseupdate.ComponentAgent:
if agentStatus == nil {
return "", ""
}
_, observedInstallType, ok := agentStatus.Snapshot()
if !ok {
return "", ""
}
return observedInstallType, ""
case releaseupdate.ComponentNATS:
switch nats.Mode {
case config.NATSModeEmbedded:
return config.NATSModeEmbedded, ""
case config.NATSModeExternal:
return config.NATSModeExternal, nats.URL
default:
return "", ""
}
default:
return "", ""
}
}
}
func configureTelegramUpdates(tg *telegram.Gateway, s telegramSetup) {
if updates := makeUpdateService(s); updates != nil {
tg.Updates = updates
}
}
func makeUpdateService(s telegramSetup) *releaseupdate.Service {
cfg := s.Cfg.Get()
if len(cfg.Chat.Telegram.UpdateCheckCommand) == 0 {
return nil
}
updates := &releaseupdate.Service{
Catalog: releaseupdate.CommandCatalog{Command: cfg.Chat.Telegram.UpdateCheckCommand},
StatePath: filepath.Join(cfg.WorkDir, "telegram-update-deferrals.json"),
InstallType: installtype.Type(),
Enrich: componentInstallTypeEnricher(s.AgentStatus, cfg.NATS),
}
if len(cfg.Chat.Telegram.UpdateInstallCommand) != 0 {
updates.Installer = releaseupdate.CommandInstaller{Command: cfg.Chat.Telegram.UpdateInstallCommand}
}
return updates
}
func makeTelegramReload(s telegramSetup) func(*telegram.Gateway) error {
return func(g *telegram.Gateway) error {
doc, err := configuration.New(s.Log).Resolve(s.CfgPath, s.OverlayPath)
if err != nil {
return fmt.Errorf("reload config: %w", err)
}
newCfg := doc.Config
tokenEnv := newCfg.Chat.Telegram.TokenEnv
if tokenEnv == "" {
return fmt.Errorf("reload config: chat.telegram.token_env is unset")
}
token := os.Getenv(tokenEnv)
if token == "" {
return fmt.Errorf("reload config: %s is empty", tokenEnv)
}
g.Token = token
g.AllowedUserIDs = newCfg.Chat.Telegram.AllowedUserIDs
g.SetShowToolCalls(newCfg.Chat.ShowToolCalls)
s.Log.Info("chat gateway config reloaded",
"allowed_user_ids", len(g.AllowedUserIDs),
"show_tool_calls", g.ShowToolCalls())
return nil
}
}
func makeTelegramSessionStore(cfg config.Config) (gateway.SessionStore, error) {
return gateway.OpenSQLiteSessionStore(conversationDBPath(cfg.DBPath))
}
// conversationDBPath keeps conversation state in its own SQLite database.
func conversationDBPath(taskDBPath string) string {
return taskDBPath + "-conversations.sqlite"
}
func buildTelegramRouter(ctx context.Context, tg *telegram.Gateway, s telegramSetup, sessionStore gateway.SessionStore) *gateway.Router {
// The router is built before the responder so the responder can resolve
// sessions through it. Both orderings work at runtime -- the responder is
// a closure -- but this way the dependency is visible rather than
// captured by reference.
router := gateway.NewRouter(s.St, nil, "telegram")
router.Models = s.ChatModels
router.Updates = s.Updates
router.Personas = s.Personas
router.InitSessions(sessionStore)
router.Titles = newChatTitleGenerator(s)
router.Log = s.Log
configureTaskCommands(router, s.ChatTasks, s.ChatController, s.DefaultChatIdentity)
if s.LLM != nil {
turnRunner := newChatTurnRunner(ctx, tg.Name(), s, sessionStore, router)
router.LLM = turnRunner.Respond
router.LLMStream = turnRunner.RespondStream
}
return router
}
func makeChatLLMResponder(
ctx context.Context,
channel string,
s telegramSetup,
sessionStore gateway.SessionStore,
router *gateway.Router,
) (gateway.LLMResponder, gateway.LLMStreamResponder) {
if s.LLM == nil {
return nil, nil
}
runner := newChatTurnRunner(ctx, channel, s, sessionStore, router)
return runner.Respond, runner.RespondStream
}
func newChatTurnRunner(
ctx context.Context,
channel string,
s telegramSetup,
sessionStore gateway.SessionStore,
router *gateway.Router,
) *gateway.TurnRunner {
cfg := s.Cfg.Get()
runner := gateway.NewTurnRunner(gateway.TurnRunnerConfig{
Router: router,
Sessions: sessionStore,
Models: s.ChatModels,
Personas: s.Personas,
Model: newChatTurnModel(s.LLM, s.ToolReg, cfg.Chat.MaxSteps, toolLimits(cfg)),
TaskLister: s.ChatTaskLister,
Tasks: s.ChatTasks,
TaskLogs: s.ChatTaskLogs,
TaskActor: s.ChatTaskActor,
TaskIdentity: s.DefaultChatIdentity,
Bus: s.Bus,
BotUser: cfg.BotUser,
Channel: channel,
Operator: cfg.Chat.Operator,
Log: s.Log,
})
if err := runner.Recover(ctx); err != nil && s.Log != nil {
s.Log.Error("recover chat turns", "channel", channel, "err", err)
}
return runner
}
func sendChatTurn(ctx context.Context, llm *runtime.Runtime, chatModel string, options core.GenerateOptions, turn gateway.TurnStream) (string, error) {
if turn == nil {
result, err := llm.Chat(ctx, chatModel, options)
if err != nil {
return "", fmt.Errorf("llm chat: %w", err)
}
return result.Text, nil
}
stream, err := llm.ChatStream(ctx, chatModel, options)
if err != nil {
return "", fmt.Errorf("llm chat stream: %w", err)
}
text := drainChatStream(stream.FullStream, turn)
if _, err := stream.FinishReason(); err != nil {
return "", fmt.Errorf("llm chat stream: %w", err)
}
return text, nil
}
// drainChatStream consumes a model stream to close, reporting assistant text
// and each completed tool call to turn, and returns the assembled reply.
//
// FullStream is authoritative and its writes are synchronous, so it must be
// drained to close even when turn is nil -- an unread stream stalls the
// generating goroutine.
//
// A tool is reported on its result, never on its call: the call part carries
// no outcome yet, so reporting both would show every tool twice, once with
// nothing to say.
func drainChatStream(parts <-chan core.StreamPart, turn gateway.TurnStream) string {
type pendingToolCall struct {
name string
parameters string
}
var sb strings.Builder
pending := make(map[string]pendingToolCall)
for part := range parts {
switch part.Type {
case core.StreamPartTextDelta:
if part.TextDelta == "" {
continue
}
sb.WriteString(part.TextDelta)
if turn != nil {
turn.Delta(part.TextDelta)
}
case core.StreamPartToolCall:
if part.ToolCall == nil || part.ToolCall.ToolCallID == "" {
continue
}
pending[part.ToolCall.ToolCallID] = pendingToolCall{
name: part.ToolCall.ToolName,
parameters: gateway.SummarizeToolParameters(part.ToolCall.Input),
}
case core.StreamPartToolResult:
if part.ToolResult == nil || turn == nil {
continue
}
call := pending[part.ToolResult.ToolCallID]
delete(pending, part.ToolResult.ToolCallID)
name := part.ToolResult.ToolName
if name == "" {
name = call.name
}
turn.ToolCall(gateway.ToolCallEvent{
ID: part.ToolResult.ToolCallID,
Name: name,
Parameters: call.parameters,
Output: part.ToolResult.Output,
Err: part.ToolResult.Error,
})
for _, ref := range multimodalMediaRefs(part.ToolResult.Output) {
// Path and URL are alternatives, not a pair: the channel
// uploads one and fetches the other. A ref carrying
// neither names nothing deliverable, so it is dropped
// rather than sent as an empty attachment.
if ref.URL == "" && ref.Path == "" {
continue
}
turn.Media(gateway.MediaEvent{
ToolName: name,
Attachment: gateway.MediaAttachment{
Type: ref.Type,
URL: ref.URL,
Path: ref.Path,
FileName: ref.FileName,
},
})
}
}
}
return sb.String()
}
// multimodalMediaRefs extracts the URLs a tool result carries when its
// output is a tools.MultimodalResult, so drainChatStream can report each as
// a gateway.MediaEvent alongside the ordinary ToolCall event.
//
// output is decoded with json.Unmarshal directly rather than checked
// against a schema first: most tool output is plain text or unrelated
// JSON, and unmarshalling into MultimodalResult simply leaves IsMultimodal
// false for anything that doesn't match, which is exactly "not multimodal"
// -- no separate detection step earns its keep here.
func multimodalMediaRefs(output string) []tools.MediaRef {
if output == "" {
return nil
}
var result tools.MultimodalResult
if err := json.Unmarshal([]byte(output), &result); err != nil || !result.IsMultimodal {
return nil
}
return result.URLs
}
// chatTitleGenerator proposes session titles through the chat model. It
// is a pure proposal: it persists nothing, so a failed or slow title
// call can never corrupt conversation history or fail the turn. The
// gateway bounds the call with its own timeout; errors leave the session
// untitled and are logged here.
type chatTitleGenerator struct {
log *slog.Logger
llm *runtime.Runtime
chatModels gateway.ModelManager
}
// newChatTitleGenerator wires an LLM-backed title generator for a chat
// setup, or nil when no model is available. Title generation is optional
// everywhere, so every caller tolerates nil.
func newChatTitleGenerator(s telegramSetup) gateway.TitleGenerator {
if s.LLM == nil || s.ChatModels == nil {
return nil
}
return &chatTitleGenerator{log: s.Log, llm: s.LLM, chatModels: s.ChatModels}
}
func (g *chatTitleGenerator) GenerateTitle(ctx context.Context, sessionID, firstMessage string) (string, error) {
messages := []chat.Message{
{Role: chat.RoleSystem, Content: gateway.TitleGenerationSystemPrompt},
{Role: chat.RoleUser, Content: firstMessage},
}
// No tools: a title is a single completion. The active model is read
// at call time so a /model switch applies to titles too.
text, err := sendChatTurn(ctx, g.llm, g.chatModels.ActiveModel(),
core.GenerateOptions{Messages: messages, MaxSteps: 1}, nil)
if err != nil {
if g.log != nil {
g.log.Error("session title generation failed", "session", sessionID, "err", err)
}
return "", fmt.Errorf("generate title for session %s: %w", sessionID, err)
}
if g.log != nil {
g.log.Info("session title generated", "session", sessionID)
}
return text, nil
}
@@ -1,27 +0,0 @@
package main
import (
"context"
"log/slog"
"testing"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/gateway"
)
func TestBuildTelegramRouterWiresPersonas(t *testing.T) {
personas := gateway.NewPersonaRegistry(gateway.DefaultPersonas())
sessions := gateway.NewSessionStoreMemory()
t.Cleanup(func() { _ = sessions.Close() })
router := buildTelegramRouter(context.Background(), nil, telegramSetup{
Cfg: config.NewHolder(config.Config{}),
Personas: personas,
SessionStore: sessions,
Log: slog.Default(),
}, sessions)
if router.Personas != personas {
t.Fatalf("router.Personas = %p, want the configured registry %p", router.Personas, personas)
}
}
-140
View File
@@ -1,140 +0,0 @@
package main
import (
"testing"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/daemon"
"github.com/samcharles93/archie-core/internal/installtype"
"github.com/samcharles93/archie-core/internal/releaseupdate"
)
// TestMakeUpdateServiceWiresInstallType is the regression test for
// archie-core-522's fail-closed guarantee actually reaching production: a
// Service built without InstallType always refuses to install (see
// releaseupdate.ErrUnknownInstallType), so wiring it here is what makes
// /update work at all for a correctly-stamped build, not just a detail.
func TestMakeUpdateServiceWiresInstallType(t *testing.T) {
cfg := config.Config{}
cfg.Chat.Telegram.UpdateCheckCommand = []string{"archie-update-check"}
cfg.Chat.Telegram.UpdateInstallCommand = []string{"archie-update-install"}
service := makeUpdateService(telegramSetup{Cfg: config.NewHolder(cfg)})
if service == nil {
t.Fatal("makeUpdateService returned nil despite a configured check command")
}
if service.InstallType != installtype.Type() {
t.Errorf("Service.InstallType = %q, want installtype.Type() = %q", service.InstallType, installtype.Type())
}
if service.Enrich == nil {
t.Fatal("Service.Enrich is nil; component InstallType/Reference will never be populated")
}
}
func TestComponentInstallTypeEnricherDaemon(t *testing.T) {
enrich := componentInstallTypeEnricher(nil, config.NATSConfig{})
gotType, gotRef := enrich(releaseupdate.ComponentDaemon)
if gotType != installtype.Type() || gotRef != "" {
t.Errorf("daemon = (%q, %q), want (%q, \"\")", gotType, gotRef, installtype.Type())
}
}
func TestComponentInstallTypeEnricherAgentBeforeAnyObservation(t *testing.T) {
var status daemon.AgentStatus
enrich := componentInstallTypeEnricher(&status, config.NATSConfig{})
gotType, gotRef := enrich(releaseupdate.ComponentAgent)
if gotType != "" || gotRef != "" {
t.Errorf("agent before any Observe = (%q, %q), want (\"\", \"\")", gotType, gotRef)
}
}
func TestComponentInstallTypeEnricherAgentAfterObservation(t *testing.T) {
var status daemon.AgentStatus
status.Observe("1.9.11", "container")
enrich := componentInstallTypeEnricher(&status, config.NATSConfig{})
gotType, _ := enrich(releaseupdate.ComponentAgent)
if gotType != "container" {
t.Errorf("agent InstallType = %q, want the observed install type %q", gotType, "container")
}
}
func TestComponentInstallTypeEnricherAgentNilStatus(t *testing.T) {
enrich := componentInstallTypeEnricher(nil, config.NATSConfig{})
gotType, gotRef := enrich(releaseupdate.ComponentAgent)
if gotType != "" || gotRef != "" {
t.Errorf("agent with nil AgentStatus = (%q, %q), want (\"\", \"\")", gotType, gotRef)
}
}
func TestComponentInstallTypeEnricherNATS(t *testing.T) {
tests := []struct {
name string
nats config.NATSConfig
wantType string
wantRef string
}{
{name: "embedded", nats: config.NATSConfig{Mode: "embedded"}, wantType: "embedded", wantRef: ""},
{name: "external", nats: config.NATSConfig{Mode: "external", URL: "nats://nats.internal:4222"}, wantType: "external", wantRef: "nats://nats.internal:4222"},
{name: "off", nats: config.NATSConfig{Mode: "off"}, wantType: "", wantRef: ""},
{name: "unset", nats: config.NATSConfig{}, wantType: "", wantRef: ""},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
enrich := componentInstallTypeEnricher(nil, test.nats)
gotType, gotRef := enrich(releaseupdate.ComponentNATS)
if gotType != test.wantType || gotRef != test.wantRef {
t.Errorf("nats(%+v) = (%q, %q), want (%q, %q)", test.nats, gotType, gotRef, test.wantType, test.wantRef)
}
})
}
}
func TestComponentInstallTypeEnricherUnknownComponent(t *testing.T) {
enrich := componentInstallTypeEnricher(nil, config.NATSConfig{})
gotType, gotRef := enrich("something-else")
if gotType != "" || gotRef != "" {
t.Errorf("unknown component = (%q, %q), want (\"\", \"\")", gotType, gotRef)
}
}
// TestDaemonRunningVersionsVouchesOnlyForItselfWithoutAgentStatus: the point
// of checking a pending update report against running versions is that the
// value checked against is ground truth. This process's own compiled-in
// version is; a guess at the agent's is not, because runtimeVersion records
// what archied's release pipeline stamped, not what an agent container is
// actually running. Before any task has reported an observed agent version
// (agentStatus nil, or nothing observed yet), including one would recreate
// the false success the check exists to catch, so its absence is the
// assertion.
func TestDaemonRunningVersionsVouchesOnlyForItselfWithoutAgentStatus(t *testing.T) {
running := daemonRunningVersions(nil)
if got := running[releaseupdate.ComponentDaemon]; got != gatewayVersion {
t.Errorf("running[%q] = %q, want gatewayVersion = %q", releaseupdate.ComponentDaemon, got, gatewayVersion)
}
if _, ok := running[releaseupdate.ComponentAgent]; ok {
t.Errorf("running vouches for %q, which this process cannot verify: %#v",
releaseupdate.ComponentAgent, running)
}
}
// TestDaemonRunningVersionsIncludesObservedAgent: once a task response has
// actually self-reported an agent version (daemon.AgentStatus.Observe), that
// -- not archied's release pipeline's expectation -- is ground truth for
// what is running, so it belongs in the verification set.
func TestDaemonRunningVersionsIncludesObservedAgent(t *testing.T) {
var status daemon.AgentStatus
status.Observe("1.9.11", "container")
running := daemonRunningVersions(&status)
if got := running[releaseupdate.ComponentAgent]; got != "1.9.11" {
t.Errorf("running[%q] = %q, want the observed version %q", releaseupdate.ComponentAgent, got, "1.9.11")
}
}
-36
View File
@@ -1,36 +0,0 @@
package main
import (
"slices"
"strings"
aicore "github.com/samcharles93/ai-sdk/core"
"github.com/samcharles93/archie-core/internal/gateway"
)
// toolSummaries converts the toolset handed to the model into the capability
// metadata advertised in its system prompt, so the two can never disagree.
//
// core.ToolSet is a map, so the result is sorted by name: an unstable tool
// order would change the system prompt on every turn and defeat provider-side
// prompt caching.
func toolSummaries(set aicore.ToolSet) []gateway.ToolSummary {
summaries := make([]gateway.ToolSummary, 0, len(set))
for name, tool := range set {
if tool == nil {
continue
}
summaries = append(summaries, gateway.ToolSummary{
Name: name,
Description: tool.Description,
})
}
if len(summaries) == 0 {
return nil
}
slices.SortFunc(summaries, func(a, b gateway.ToolSummary) int {
return strings.Compare(a.Name, b.Name)
})
return summaries
}
-56
View File
@@ -1,56 +0,0 @@
package main
import (
"testing"
aicore "github.com/samcharles93/ai-sdk/core"
)
func TestToolSummaries(t *testing.T) {
tests := []struct {
name string
set aicore.ToolSet
want []string // expected "name: description" pairs, in order
}{
{
name: "nil set yields no summaries",
set: nil,
want: nil,
},
{
name: "empty set yields no summaries",
set: aicore.ToolSet{},
want: nil,
},
{
name: "summaries are sorted by name for a stable prompt",
set: aicore.ToolSet{
"skill_activate": aicore.NewTool("skill_activate", "Load a skill", nil, nil),
"memory_edit": aicore.NewTool("memory_edit", "Edit memory", nil, nil),
},
// ToolSet is a map: without sorting the prompt text would
// differ between turns and defeat provider prompt caching.
want: []string{"memory_edit: Edit memory", "skill_activate: Load a skill"},
},
{
name: "nil entries are skipped rather than panicking",
set: aicore.ToolSet{"broken": nil},
want: nil,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got := toolSummaries(tc.set)
if len(got) != len(tc.want) {
t.Fatalf("toolSummaries() returned %d summaries, want %d: %+v", len(got), len(tc.want), got)
}
for i, want := range tc.want {
joined := got[i].Name + ": " + got[i].Description
if joined != want {
t.Errorf("summary %d = %q, want %q", i, joined, want)
}
}
})
}
}