package gateway import ( "context" "errors" "fmt" "slices" "strings" "testing" "time" "github.com/samcharles93/archie-core/internal/taskstate" ) type fakeStore struct { counts map[string]int err error } func (f *fakeStore) StatusCounts(ctx context.Context) (map[string]int, error) { return f.counts, f.err } func fakeLLM(ctx context.Context, in Inbound) (string, error) { return "llm: " + in.Message.Text, nil } func TestRouteStatusShowsQueueDepthNotPerTaskCounts(t *testing.T) { r := NewRouter(&fakeStore{counts: map[string]int{"queued": 2, "pr_open": 1}}, nil, "test") reply, err := r.Route(context.Background(), inbound("", "/status")) if err != nil { t.Fatalf("Route: %v", err) } // queued and pr_open are not "in flight" (running/waiting/parked), so // /status reports the daemon idle -- that per-task detail is /tasks' job. want := "๐Ÿ“Š Archie status\n\nQueue: idle \nRuntime: not configured" if reply != want { t.Errorf("reply =\n%q\nwant:\n%q", reply, want) } } func TestRouteStatusIncludesActiveProviderAndModel(t *testing.T) { manager := &fakeProviderModelManager{ models: []string{"openai/gpt-5.6", "openrouter/openai/gpt-5.6"}, activeModel: "openai/gpt-5.6", } r := NewRouter(&fakeStore{counts: map[string]int{"running": 1}}, nil, "test") r.Models = manager reply, err := r.Route(context.Background(), inbound("", "/status")) if err != nil { t.Fatal(err) } want := "๐Ÿ“Š Archie status\n\nQueue: 1 in flight (1 running) \nProvider: OpenAI \nModel: openai/gpt-5.6" if reply != want { t.Fatalf("reply =\n%q\nwant:\n%q", reply, want) } } func TestRouteStatusAtMention(t *testing.T) { r := NewRouter(&fakeStore{counts: map[string]int{"running": 3}}, nil, "archie") reply, err := r.Route(context.Background(), inbound("", "/status@archie")) if err != nil { t.Fatalf("Route: %v", err) } if !strings.Contains(reply, "3 running") { t.Errorf("reply missing queue depth: %q", reply) } } func TestRouteStatusEmpty(t *testing.T) { r := NewRouter(&fakeStore{counts: map[string]int{}}, nil, "test") reply, err := r.Route(context.Background(), inbound("", "/status")) if err != nil { t.Fatalf("Route: %v", err) } want := "๐Ÿ“Š Archie status\n\nQueue: idle \nRuntime: not configured" if reply != want { t.Errorf("reply = %q, want %q", reply, want) } } type fakeCustomDisplayNamerManager struct { fakeProviderModelManager } func (f *fakeCustomDisplayNamerManager) ProviderDisplayName(provider string) string { if provider == "openai" { return "OpenAI Custom Enterprise" } return provider } func TestFormatStatus(t *testing.T) { tests := []struct { name string counts map[string]int models ModelManager want string }{ { name: "single parked task with provider and model", counts: map[string]int{"parked": 2}, models: &fakeProviderModelManager{ activeModel: "openai/gpt-5.6-luna", }, want: "๐Ÿ“Š Archie status\n\nQueue: 2 in flight (2 parked) \nProvider: OpenAI \nModel: openai/gpt-5.6-luna", }, { name: "in-flight states reduce to one aggregate line; queued and terminal states are excluded", counts: map[string]int{ "queued": 4, "running": 1, "waiting_human": 2, "parked": 3, "pr_open": 5, "merged": 6, "rejected": 7, "closed_wont_do": 8, "dead": 9, "custom_state": 10, }, models: &fakeProviderModelManager{ activeModel: "deepseek/deepseek-v4-pro", }, want: "๐Ÿ“Š Archie status\n\nQueue: 6 in flight (1 running, 2 waiting on you, 3 parked) \nProvider: DeepSeek \nModel: deepseek/deepseek-v4-pro", }, { name: "empty task counts with active model", counts: map[string]int{}, models: &fakeModelManager{ activeModel: "anthropic/claude-3-5-sonnet", }, want: "๐Ÿ“Š Archie status\n\nQueue: idle \nProvider: Anthropic \nModel: anthropic/claude-3-5-sonnet", }, { name: "nil counts with active model", counts: nil, models: &fakeModelManager{ activeModel: "google/gemini-2.5-flash", }, want: "๐Ÿ“Š Archie status\n\nQueue: idle \nProvider: Google \nModel: google/gemini-2.5-flash", }, { name: "nil model manager", counts: map[string]int{"running": 2}, models: nil, want: "๐Ÿ“Š Archie status\n\nQueue: 2 in flight (2 running) \nRuntime: not configured", }, { name: "empty counts and nil model manager", counts: map[string]int{}, models: nil, want: "๐Ÿ“Š Archie status\n\nQueue: idle \nRuntime: not configured", }, { name: "custom display namer interface", counts: map[string]int{"running": 1}, models: &fakeCustomDisplayNamerManager{ activeModel: "openai/gpt-5.6", }, want: "๐Ÿ“Š Archie status\n\nQueue: 1 in flight (1 running) \nProvider: OpenAI Custom Enterprise \nModel: openai/gpt-5.6", }, { name: "queued-only counts as idle -- queued is not in flight", counts: map[string]int{"queued": 1}, models: &fakeProviderModelManager{ activeModel: "", }, want: "๐Ÿ“Š Archie status\n\nQueue: idle \nRuntime: not configured", }, { name: "model without slash and no provider manager", counts: map[string]int{"running": 1}, models: &fakeModelManager{ activeModel: "custom-local-model", }, want: "๐Ÿ“Š Archie status\n\nQueue: 1 in flight (1 running) \nProvider: not configured \nModel: custom-local-model", }, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { // Health sections are covered by TestFormatHealthRendersOnlyWhatWasReported; // these cases pin the queue and runtime sections with no health source wired. got := formatStatus(tc.counts, HealthReport{}, tc.models, time.Date(2026, 9, 19, 12, 0, 0, 0, time.UTC)) if got != tc.want { t.Errorf("formatStatus() =\n%q\nwant:\n%q\ndiff:\ngot:\n%s\nwant:\n%s", got, tc.want, got, tc.want) } }) } } func TestRouteStatusError(t *testing.T) { r := NewRouter(&fakeStore{err: errors.New("db down")}, nil, "test") if _, err := r.Route(context.Background(), inbound("", "/status")); err == nil { t.Error("expected error from Route when StatusCounts fails") } } // -- /tasks tests -- type fakeChatTaskLister struct { tasks []ChatTaskSummary err error } func (f *fakeChatTaskLister) ListChatTasks(ctx context.Context, identity string, limit int) ([]ChatTaskSummary, error) { return f.tasks, f.err } func TestRouteTasksNotConfigured(t *testing.T) { r := NewRouter(nil, nil, "test") reply, err := r.Route(context.Background(), inbound("", "/tasks")) if err != nil { t.Fatalf("Route: %v", err) } if reply != "task list not configured" { t.Errorf("reply = %q, want the not-configured message", reply) } } func TestRouteTasksEmpty(t *testing.T) { r := NewRouter(nil, nil, "test") r.TaskLister = &fakeChatTaskLister{} reply, err := r.Route(context.Background(), inbound("", "/tasks")) if err != nil { t.Fatalf("Route: %v", err) } want := "๐Ÿ—‚ Archie tasks\n\nNo tasks yet" if reply != want { t.Errorf("reply = %q, want %q", reply, want) } } func TestRouteTasksError(t *testing.T) { r := NewRouter(nil, nil, "test") r.TaskLister = &fakeChatTaskLister{err: errors.New("store unavailable")} if _, err := r.Route(context.Background(), inbound("", "/tasks")); err == nil { t.Error("expected error from Route when ListChatTasks fails") } } func TestFormatTasks(t *testing.T) { now := time.Date(2026, 9, 3, 12, 0, 0, 0, time.UTC) tests := []struct { name string tasks []ChatTaskSummary want string }{ { name: "running task shows workflow/stage and age", tasks: []ChatTaskSummary{ {ID: 42, Title: "Fix login bug", Status: taskstate.Running, Workflow: "tdd", Stage: "implement", UpdatedAt: now.Add(-3 * time.Minute)}, }, want: "๐Ÿ—‚ Archie tasks\n\nโ–ถ #42 Fix login bug \n Running ยท tdd/implement ยท updated 3m ago", }, { // The criterion this command was built for: a bare "Running: 1" // reads the same whether the task is making progress or wedged in a // failure loop, and each task's own age is what tells them apart. name: "a stuck running task does not read like one making progress", tasks: []ChatTaskSummary{ {ID: 5, Title: "Wedged", Status: taskstate.Running, Workflow: "tdd", Stage: "implement", UpdatedAt: now.Add(-47 * time.Minute)}, {ID: 6, Title: "Working", Status: taskstate.Running, Workflow: "tdd", Stage: "implement", UpdatedAt: now.Add(-20 * time.Second)}, }, want: "๐Ÿ—‚ Archie tasks\n\nโ–ถ #5 Wedged \n Running ยท tdd/implement ยท updated 47m ago\n\nโ–ถ #6 Working \n Running ยท tdd/implement ยท updated just now", }, { name: "parked task shows its reason", tasks: []ChatTaskSummary{ {ID: 17, Title: "Add dark mode", Status: taskstate.Parked, Workflow: "feasibility", ParkReason: "gate failed 3x", UpdatedAt: now.Add(-2 * time.Hour)}, }, want: "๐Ÿ—‚ Archie tasks\n\nโธ #17 Add dark mode \n Parked ยท feasibility ยท updated 2h ago \n โ†ณ gate failed 3x", }, { name: "attempt is shown only once a retry has happened", tasks: []ChatTaskSummary{ {ID: 1, Title: "First try", Status: taskstate.Running, Attempt: 1, UpdatedAt: now}, {ID: 2, Title: "Retried", Status: taskstate.Running, Attempt: 2, UpdatedAt: now}, }, want: "๐Ÿ—‚ Archie tasks\n\nโ–ถ #1 First try \n Running ยท updated just now\n\nโ–ถ #2 Retried \n Running ยท attempt 2 ยท updated just now", }, { name: "an unrecognized status still renders, generically", tasks: []ChatTaskSummary{ {ID: 9, Title: "Mystery", Status: "custom_state", UpdatedAt: now}, }, want: "๐Ÿ—‚ Archie tasks\n\nโ€ข #9 Mystery \n Custom state ยท updated just now", }, { name: "actionable work leads terminal work regardless of recency", tasks: []ChatTaskSummary{ {ID: 3, Title: "Just merged", Status: taskstate.Merged, UpdatedAt: now}, {ID: 4, Title: "Still running", Status: taskstate.Running, UpdatedAt: now.Add(-time.Hour)}, }, want: "๐Ÿ—‚ Archie tasks\n\nโ–ถ #4 Still running \n Running ยท updated 1h ago\n\nโœ… #3 Just merged \n Merged ยท updated just now", }, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { got := formatTasks(tc.tasks, now) if got != tc.want { t.Errorf("formatTasks() =\n%q\nwant:\n%q", got, tc.want) } }) } } func TestRouteNonCommandWithLLM(t *testing.T) { r := NewRouter(nil, fakeLLM, "test") reply, err := r.Route(context.Background(), inbound("", "hello")) if err != nil { t.Fatalf("Route: %v", err) } if reply != "llm: hello" { t.Errorf("reply = %q, want %q", reply, "llm: hello") } } func TestRouteNonCommandWithoutLLM(t *testing.T) { r := NewRouter(nil, nil, "test") reply, err := r.Route(context.Background(), inbound("", "hello")) if err != nil { t.Fatalf("Route: %v", err) } if !strings.Contains(reply, "/status") { t.Errorf("reply = %q, want mention of /status", reply) } } func TestRouterRejectsUnknownCommand(t *testing.T) { tests := []string{ "/frobnicate", "/frobnicate with arguments", "/frobnicate@test with arguments", } for _, text := range tests { t.Run(text, func(t *testing.T) { llmCalls := 0 r := NewRouter(nil, func(context.Context, Inbound) (string, error) { llmCalls++ return "fabricated command behavior", nil }, "test") r.LLMStream = func(context.Context, Inbound, TurnStream) (string, error) { llmCalls++ return "fabricated streaming behavior", nil } reply, err := r.RouteStream(context.Background(), inbound("", text), DeltaFunc(func(string) {})) if err != nil { t.Fatalf("RouteStream: %v", err) } if llmCalls != 0 { t.Fatalf("unknown command invoked LLM %d times", llmCalls) } if !strings.Contains(reply, "/frobnicate") || !strings.Contains(reply, "/help") { t.Errorf("reply = %q, want unknown command and /help guidance", reply) } }) } } // -- ModelManager fakes for /model tests -- type fakeModelManager struct { models []string activeModel string setErr error } type fakeProviderModelManager struct { fakeModelManager } func (f *fakeProviderModelManager) Providers() []string { return []string{"openai", "openrouter"} } func (f *fakeProviderModelManager) ActiveProvider() string { provider, _, _ := strings.Cut(f.activeModel, "/") return provider } func (f *fakeProviderModelManager) ModelsForProvider(provider string) []string { var models []string for _, model := range f.models { if strings.HasPrefix(model, provider+"/") { models = append(models, model) } } return models } func (f *fakeProviderModelManager) SetActiveProvider(_ context.Context, provider string) error { models := f.ModelsForProvider(provider) if len(models) == 0 { return fmt.Errorf("unknown provider: %s", provider) } f.activeModel = models[0] return nil } func (f *fakeModelManager) Models() []string { return f.models } func (f *fakeModelManager) ActiveModel() string { return f.activeModel } func (f *fakeModelManager) SetActiveModel(_ context.Context, ref string) error { if f.setErr != nil { return f.setErr } if slices.Contains(f.models, ref) { f.activeModel = ref return nil } return fmt.Errorf("unknown model: %s", ref) } // -- /model tests -- func TestRouteModelsIsNoLongerACommand(t *testing.T) { r := NewRouter(nil, nil, "test-gw") reply, err := r.Route(context.Background(), inbound("", "/models")) if err != nil { t.Fatal(err) } if !strings.Contains(reply, "Unknown command /models") { t.Errorf("reply = %q, want /models to be unavailable", reply) } } func TestRouteModelSwitch(t *testing.T) { mgr := &fakeModelManager{ models: []string{"a/b", "c/d"}, } r := NewRouter(nil, nil, "test-gw") r.Models = mgr reply, err := r.Route(context.Background(), inbound("", "/model a/b")) if err != nil { t.Fatalf("Route: %v", err) } if !strings.Contains(reply, "a/b") || !strings.Contains(reply, "set to") { t.Errorf("reply should confirm model switch: %q", reply) } if mgr.activeModel != "a/b" { t.Errorf("active model = %q, want %q", mgr.activeModel, "a/b") } } func TestRouteModelAtMention(t *testing.T) { mgr := &fakeModelManager{ models: []string{"a/b"}, } r := NewRouter(nil, nil, "test-gw") r.Models = mgr reply, err := r.Route(context.Background(), inbound("", "/model@test-gw a/b")) if err != nil { t.Fatalf("Route: %v", err) } if !strings.Contains(reply, "a/b") { t.Errorf("reply should confirm model switch: %q", reply) } } func TestRouteModelUnknown(t *testing.T) { mgr := &fakeModelManager{ models: []string{"a/b"}, } r := NewRouter(nil, nil, "test-gw") r.Models = mgr reply, err := r.Route(context.Background(), inbound("", "/model unknown/unknown")) if err != nil { t.Fatalf("Route: %v", err) } if !strings.Contains(reply, "Cannot switch") { t.Errorf("reply should mention cannot switch: %q", reply) } } func TestRouteModelNoArg(t *testing.T) { mgr := &fakeModelManager{ models: []string{"a/b", "c/d"}, } r := NewRouter(nil, nil, "test-gw") r.Models = mgr reply, err := r.Route(context.Background(), inbound("", "/model")) if err != nil { t.Fatalf("Route: %v", err) } if !strings.Contains(reply, "Usage") || !strings.Contains(reply, "a/b") || !strings.Contains(reply, "c/d") { t.Errorf("reply should show usage and available models: %q", reply) } } func TestRouteModelNoManager(t *testing.T) { r := NewRouter(nil, nil, "test-gw") reply, err := r.Route(context.Background(), inbound("", "/model a/b")) if err != nil { t.Fatalf("Route: %v", err) } if !strings.Contains(reply, "not configured") { t.Errorf("reply = %q, want 'not configured' message", reply) } } // -- TaskCreator fakes for /spawn tests -- type fakeTaskCreator struct { tasks []string requests []SpawnRequest createFn func(ctx context.Context, req SpawnRequest) (int64, error) } func (f *fakeTaskCreator) CreateTask(ctx context.Context, req SpawnRequest) (int64, error) { f.tasks = append(f.tasks, req.Title) f.requests = append(f.requests, req) if f.createFn != nil { return f.createFn(ctx, req) } return int64(len(f.tasks)), nil } func TestRouteSpawnCreatesTask(t *testing.T) { tc := &fakeTaskCreator{} r := NewRouter(nil, nil, "test-gw") r.Tasks = tc reply, err := r.Route(context.Background(), inbound("", "/spawn Fix the login bug")) if err != nil { t.Fatalf("Route: %v", err) } if !strings.Contains(reply, "Created task") || !strings.Contains(reply, "1") { t.Errorf("reply should confirm task creation: %q", reply) } if len(tc.tasks) != 1 || tc.tasks[0] != "Fix the login bug" { t.Errorf("tasks = %v, want [Fix the login bug]", tc.tasks) } } func TestRouteSpawnAtMention(t *testing.T) { tc := &fakeTaskCreator{} r := NewRouter(nil, nil, "archie-bot") r.Tasks = tc reply, err := r.Route(context.Background(), inbound("", "/spawn@archie-bot Deploy the release")) if err != nil { t.Fatalf("Route: %v", err) } if !strings.Contains(reply, "Created task") { t.Errorf("reply should confirm creation: %q", reply) } } func TestRouteSpawnNoTitle(t *testing.T) { tc := &fakeTaskCreator{} r := NewRouter(nil, nil, "test-gw") r.Tasks = tc reply, err := r.Route(context.Background(), inbound("", "/spawn")) if err != nil { t.Fatalf("Route: %v", err) } if !strings.Contains(reply, "Usage") { t.Errorf("reply should show usage: %q", reply) } if len(tc.tasks) != 0 { t.Errorf("no task should be created without a title") } } func TestRouteSpawnNoManager(t *testing.T) { r := NewRouter(nil, nil, "test-gw") reply, err := r.Route(context.Background(), inbound("", "/spawn something")) if err != nil { t.Fatalf("Route: %v", err) } if !strings.Contains(reply, "not configured") { t.Errorf("reply = %q, want 'not configured'", reply) } } func TestRouteSpawnHandlesCreationError(t *testing.T) { tc := &fakeTaskCreator{ createFn: func(ctx context.Context, req SpawnRequest) (int64, error) { return 0, fmt.Errorf("store unavailable") }, } r := NewRouter(nil, nil, "test-gw") r.Tasks = tc reply, err := r.Route(context.Background(), inbound("", "/spawn Break things")) if err != nil { t.Fatalf("Route: %v", err) } if !strings.Contains(reply, "Failed") { t.Errorf("reply should mention failure: %q", reply) } } func TestRouteSpawnParsesRepoAndWorkflow(t *testing.T) { tc := &fakeTaskCreator{} r := NewRouter(nil, nil, "test-gw") r.Tasks = tc r.Identity = "archie" reply, err := r.Route(context.Background(), inbound("", "/spawn repo=acme/example-service workflow=tdd Fix the flaky test")) if err != nil { t.Fatalf("Route: %v", err) } if !strings.Contains(reply, "Created task") { t.Errorf("reply = %q, want task creation confirmation", reply) } if len(tc.requests) != 1 { t.Fatalf("requests = %d, want 1", len(tc.requests)) } got := tc.requests[0] if got.Repo != "acme/example-service" || got.Workflow != "tdd" || got.Title != "Fix the flaky test" || got.Identity != "archie" { t.Errorf("request = %+v, want {Repo:acme/example-service Workflow:tdd Title:\"Fix the flaky test\" Identity:archie}", got) } } func TestRouteSpawnParsesIdentity(t *testing.T) { tc := &fakeTaskCreator{} r := NewRouter(nil, nil, "test-gw") r.Tasks = tc r.Identity = "default" reply, err := r.Route(context.Background(), inbound("", "/spawn identity=reviewer repo=acme/example-service workflow=tdd Fix the flaky test")) if err != nil { t.Fatalf("Route: %v", err) } if !strings.Contains(reply, "Created task") { t.Errorf("reply = %q, want task creation confirmation", reply) } got := tc.requests[0] if got.Identity != "reviewer" || got.Repo != "acme/example-service" || got.Workflow != "tdd" || got.Title != "Fix the flaky test" { t.Errorf("request = %+v, want selected identity, repo, workflow, and full title", got) } } func TestRouteSpawnWithoutRepoOrWorkflowUsesDefaults(t *testing.T) { tc := &fakeTaskCreator{} r := NewRouter(nil, nil, "test-gw") r.Tasks = tc reply, err := r.Route(context.Background(), inbound("", "/spawn Fix the login bug")) if err != nil { t.Fatalf("Route: %v", err) } if !strings.Contains(reply, "Created task") { t.Errorf("reply = %q", reply) } got := tc.requests[0] if got.Repo != "" || got.Workflow != "" || got.Title != "Fix the login bug" { t.Errorf("request = %+v, want empty Repo/Workflow and full title", got) } } func TestRouteSpawnTitleLooksLikeKeyValueIsPreserved(t *testing.T) { // A title that happens to contain "=" after the repo=/workflow= // tokens must not be mistaken for another key=value token. tc := &fakeTaskCreator{} r := NewRouter(nil, nil, "test-gw") r.Tasks = tc if _, err := r.Route(context.Background(), inbound("", "/spawn repo=acme/example-service Fix x=y in config")); err != nil { t.Fatalf("Route: %v", err) } got := tc.requests[0] if got.Repo != "acme/example-service" || got.Title != "Fix x=y in config" { t.Errorf("request = %+v, want Repo:acme/example-service Title:\"Fix x=y in config\"", got) } } // -- TaskController fakes for /approve and /cancel tests -- type fakeTaskController struct { approveFn func(ctx context.Context, taskID int64, identity string) error cancelFn func(ctx context.Context, taskID int64, identity string) error approved []int64 cancelled []int64 identities []string stopRunning []int64 stopRunningErr error stoppedIdentities []string } func (f *fakeTaskController) Approve(ctx context.Context, taskID int64, identity string) error { f.approved = append(f.approved, taskID) f.identities = append(f.identities, identity) if f.approveFn != nil { return f.approveFn(ctx, taskID, identity) } return nil } func (f *fakeTaskController) Cancel(ctx context.Context, taskID int64, identity string) error { f.cancelled = append(f.cancelled, taskID) f.identities = append(f.identities, identity) if f.cancelFn != nil { return f.cancelFn(ctx, taskID, identity) } return nil } func (f *fakeTaskController) StopRunning(_ context.Context, identity string) ([]int64, error) { f.stoppedIdentities = append(f.stoppedIdentities, identity) return f.stopRunning, f.stopRunningErr } func TestRouteApproveParsesIdentity(t *testing.T) { fc := &fakeTaskController{} r := NewRouter(nil, nil, "test-gw") r.Controller = fc r.Identity = "default" reply, err := r.Route(context.Background(), inbound("", "/approve identity=reviewer 42")) if err != nil { t.Fatalf("Route: %v", err) } if !strings.Contains(reply, "approved") { t.Errorf("reply = %q, want mention of approval", reply) } if len(fc.approved) != 1 || fc.approved[0] != 42 || fc.identities[0] != "reviewer" { t.Errorf("approved/identities = %v/%v, want [42]/[reviewer]", fc.approved, fc.identities) } } func TestRouteApproveSuccess(t *testing.T) { fc := &fakeTaskController{} r := NewRouter(nil, nil, "test-gw") r.Controller = fc reply, err := r.Route(context.Background(), inbound("", "/approve 42")) if err != nil { t.Fatalf("Route: %v", err) } if !strings.Contains(reply, "approved") { t.Errorf("reply = %q, want mention of approval", reply) } if len(fc.approved) != 1 || fc.approved[0] != 42 { t.Errorf("approved = %v, want [42]", fc.approved) } } func TestRouteApproveNotConfigured(t *testing.T) { r := NewRouter(nil, nil, "test-gw") reply, err := r.Route(context.Background(), inbound("", "/approve 1")) if err != nil { t.Fatalf("Route: %v", err) } if !strings.Contains(reply, "not configured") { t.Errorf("reply = %q, want 'not configured'", reply) } } func TestRouteApproveBadID(t *testing.T) { fc := &fakeTaskController{} r := NewRouter(nil, nil, "test-gw") r.Controller = fc reply, err := r.Route(context.Background(), inbound("", "/approve notanumber")) if err != nil { t.Fatalf("Route: %v", err) } if !strings.Contains(reply, "Usage") { t.Errorf("reply = %q, want usage message", reply) } if len(fc.approved) != 0 { t.Error("Approve must not be called with an invalid ID") } } func TestRouteApproveWrongStateSurfacesError(t *testing.T) { fc := &fakeTaskController{ approveFn: func(ctx context.Context, taskID int64, identity string) error { return fmt.Errorf("task is queued, not waiting_human") }, } r := NewRouter(nil, nil, "test-gw") r.Controller = fc reply, err := r.Route(context.Background(), inbound("", "/approve 7")) if err != nil { t.Fatalf("Route: %v", err) } if !strings.Contains(reply, "Cannot approve") || !strings.Contains(reply, "waiting_human") { t.Errorf("reply = %q, want error surfaced to user", reply) } } func TestRouteCancelSuccess(t *testing.T) { fc := &fakeTaskController{} r := NewRouter(nil, nil, "test-gw") r.Controller = fc reply, err := r.Route(context.Background(), inbound("", "/cancel 5")) if err != nil { t.Fatalf("Route: %v", err) } if !strings.Contains(reply, "cancelled") { t.Errorf("reply = %q, want mention of cancellation", reply) } if len(fc.cancelled) != 1 || fc.cancelled[0] != 5 { t.Errorf("cancelled = %v, want [5]", fc.cancelled) } } func TestRouteCancelParsesIdentity(t *testing.T) { fc := &fakeTaskController{} r := NewRouter(nil, nil, "test-gw") r.Controller = fc r.Identity = "default" reply, err := r.Route(context.Background(), inbound("", "/cancel identity=reviewer 5")) if err != nil { t.Fatalf("Route: %v", err) } if !strings.Contains(reply, "cancelled") { t.Errorf("reply = %q, want mention of cancellation", reply) } if len(fc.cancelled) != 1 || fc.cancelled[0] != 5 || fc.identities[0] != "reviewer" { t.Errorf("cancelled/identities = %v/%v, want [5]/[reviewer]", fc.cancelled, fc.identities) } } func TestRouteCancelCrossIdentityRejected(t *testing.T) { fc := &fakeTaskController{ cancelFn: func(ctx context.Context, taskID int64, identity string) error { if identity != "archie" { return fmt.Errorf("task belongs to a different identity") } return nil }, } r := NewRouter(nil, nil, "test-gw") r.Controller = fc r.Identity = "winter" reply, err := r.Route(context.Background(), inbound("", "/cancel 9")) if err != nil { t.Fatalf("Route: %v", err) } if !strings.Contains(reply, "Cannot cancel") || !strings.Contains(reply, "different identity") { t.Errorf("reply = %q, want cross-identity rejection surfaced", reply) } } func TestRouteCancelNotConfigured(t *testing.T) { r := NewRouter(nil, nil, "test-gw") reply, err := r.Route(context.Background(), inbound("", "/cancel 1")) if err != nil { t.Fatalf("Route: %v", err) } if !strings.Contains(reply, "not configured") { t.Errorf("reply = %q, want 'not configured'", reply) } } // -- /whoami tests -- func TestRouteWhoami(t *testing.T) { r := NewRouter(nil, nil, "test-gw") r.Identity = "archie" reply, err := r.Route(context.Background(), inbound("", "/whoami")) if err != nil { t.Fatalf("Route: %v", err) } if !strings.Contains(reply, "archie") { t.Errorf("reply = %q, want mention of identity", reply) } } func TestRouteWhoamiNoIdentity(t *testing.T) { r := NewRouter(nil, nil, "test-gw") reply, err := r.Route(context.Background(), inbound("", "/whoami")) if err != nil { t.Fatalf("Route: %v", err) } if !strings.Contains(reply, "Archie") { t.Errorf("reply = %q, want mention of Archie", reply) } } func TestRouteWhoamiWithModel(t *testing.T) { r := NewRouter(nil, nil, "test-gw") r.Identity = "archie" r.Models = &fakeModelManager{ models: []string{"a/b", "c/d"}, activeModel: "a/b", } reply, err := r.Route(context.Background(), inbound("", "/whoami")) if err != nil { t.Fatalf("Route: %v", err) } if !strings.Contains(reply, "archie") || !strings.Contains(reply, "a/b") { t.Errorf("reply = %q, want identity and model", reply) } } // -- /profile tests -- func TestRouteProfile(t *testing.T) { r := NewRouter(nil, nil, "test-gw") r.Identity = "archie" r.Models = &fakeModelManager{ models: []string{"a/b", "c/d"}, activeModel: "a/b", } reply, err := r.Route(context.Background(), inbound("", "/profile")) if err != nil { t.Fatalf("Route: %v", err) } if !strings.Contains(reply, "archie") || !strings.Contains(reply, "a/b") { t.Errorf("reply = %q, want identity and model", reply) } } func TestRouteProfileNoIdentity(t *testing.T) { r := NewRouter(nil, nil, "test-gw") reply, err := r.Route(context.Background(), inbound("", "/profile")) if err != nil { t.Fatalf("Route: %v", err) } if !strings.Contains(reply, "not configured") { t.Errorf("reply = %q, want mention of not configured", reply) } } // -- /sessions tests -- type fakeSessionLister struct { *fakeSessionStore sessions []SessionContext err error } func (f *fakeSessionLister) List(ctx context.Context) ([]SessionContext, error) { return f.sessions, f.err } func TestRouteSessionsEmpty(t *testing.T) { r := NewRouter(nil, nil, "test-gw") r.Sessions = &fakeSessionLister{fakeSessionStore: newFakeSessionStore()} reply, err := r.Route(context.Background(), inbound("", "/sessions")) if err != nil { t.Fatalf("Route: %v", err) } if !strings.Contains(reply, "No sessions") { t.Errorf("reply = %q, want 'No sessions'", reply) } } func TestRouteSessionsNotConfigured(t *testing.T) { r := NewRouter(nil, nil, "test-gw") reply, err := r.Route(context.Background(), inbound("", "/sessions")) if err != nil { t.Fatalf("Route: %v", err) } if !strings.Contains(reply, "not configured") { t.Errorf("reply = %q, want 'not configured'", reply) } } func TestRouteSessionsError(t *testing.T) { r := NewRouter(nil, nil, "test-gw") r.Sessions = &fakeSessionLister{fakeSessionStore: newFakeSessionStore(), err: fmt.Errorf("store unavailable")} _, err := r.Route(context.Background(), inbound("", "/sessions")) if err == nil { t.Error("expected error from Route when List fails") } } // -- /resume tests -- func TestRouteResumeNoArg(t *testing.T) { r := NewRouter(nil, nil, "test-gw") r.Sessions = &fakeSessionLister{fakeSessionStore: newFakeSessionStore()} reply, err := r.Route(context.Background(), inbound("", "/resume")) if err != nil { t.Fatalf("Route: %v", err) } if !strings.Contains(reply, "Usage") { t.Errorf("reply = %q, want usage", reply) } } func TestRouteResumeNotConfigured(t *testing.T) { r := NewRouter(nil, nil, "test-gw") reply, err := r.Route(context.Background(), inbound("", "/resume abc")) if err != nil { t.Fatalf("Route: %v", err) } if !strings.Contains(reply, "not configured") { t.Errorf("reply = %q, want 'not configured'", reply) } } func TestRouteResumeNoMatch(t *testing.T) { r := NewRouter(nil, nil, "test-gw") r.Sessions = &fakeSessionLister{ fakeSessionStore: newFakeSessionStore(), sessions: []SessionContext{ {SessionID: "session-1"}, }, } reply, err := r.Route(context.Background(), inbound("", "/resume xyz")) if err != nil { t.Fatalf("Route: %v", err) } if !strings.Contains(reply, "No session matching") { t.Errorf("reply = %q, want 'No session matching'", reply) } } func TestRouteResumeAmbiguous(t *testing.T) { r := NewRouter(nil, nil, "test-gw") r.Sessions = &fakeSessionLister{ fakeSessionStore: newFakeSessionStore(), sessions: []SessionContext{ {SessionID: "abc-123"}, {SessionID: "abc-456"}, }, } reply, err := r.Route(context.Background(), inbound("", "/resume abc")) if err != nil { t.Fatalf("Route: %v", err) } if !strings.Contains(reply, "Multiple sessions") { t.Errorf("reply = %q, want 'Multiple sessions'", reply) } } func TestRouteResumeExactMatch(t *testing.T) { r := NewRouter(nil, nil, "test-gw") r.Sessions = &fakeSessionLister{ fakeSessionStore: newFakeSessionStore(), sessions: []SessionContext{ {SessionID: "abc-123"}, {SessionID: "abc-456"}, }, } reply, err := r.Route(context.Background(), inbound("", "/resume abc-123")) if err != nil { t.Fatalf("Route: %v", err) } if !strings.Contains(reply, "Resumed session") { t.Errorf("reply = %q, want 'Resumed session'", reply) } } // -- /agents tests -- type fakeAgentReader struct { agents []AgentInfo err error } func (f *fakeAgentReader) AgentList(ctx context.Context) ([]AgentInfo, error) { if f.err != nil { return nil, f.err } return f.agents, nil } func TestRouteAgentsEmpty(t *testing.T) { r := NewRouter(nil, nil, "test-gw") r.Agents = &fakeAgentReader{} reply, err := r.Route(context.Background(), inbound("", "/agents")) if err != nil { t.Fatalf("Route: %v", err) } if !strings.Contains(reply, "No active agents") { t.Errorf("reply = %q, want 'No active agents'", reply) } } func TestRouteAgentsNotConfigured(t *testing.T) { r := NewRouter(nil, nil, "test-gw") reply, err := r.Route(context.Background(), inbound("", "/agents")) if err != nil { t.Fatalf("Route: %v", err) } if !strings.Contains(reply, "not configured") { t.Errorf("reply = %q, want 'not configured'", reply) } } func TestRouteAgentsWithTasks(t *testing.T) { r := NewRouter(nil, nil, "test-gw") r.Agents = &fakeAgentReader{ agents: []AgentInfo{ {ID: 1, Title: "Fix the bug", Status: "running", Identity: "archie"}, {ID: 2, Title: "Add tests", Status: "waiting_human", Identity: "archie"}, }, } reply, err := r.Route(context.Background(), inbound("", "/agents")) if err != nil { t.Fatalf("Route: %v", err) } if !strings.Contains(reply, "Fix the bug") || !strings.Contains(reply, "Add tests") { t.Errorf("reply = %q, want task titles", reply) } if !strings.Contains(reply, "running") || !strings.Contains(reply, "waiting_human") { t.Errorf("reply = %q, want task statuses", reply) } } func TestRouteAgentsError(t *testing.T) { r := NewRouter(nil, nil, "test-gw") r.Agents = &fakeAgentReader{err: fmt.Errorf("store unavailable")} _, err := r.Route(context.Background(), inbound("", "/agents")) if err == nil { t.Error("expected error from Route when AgentList fails") } } func TestLocalCommandsIncludesNewCommands(t *testing.T) { cmds := LocalCommands() for _, want := range []string{"/whoami", "/profile", "/sessions", "/resume", "/agents", "/tasks"} { if !slices.Contains(cmds, want) { t.Errorf("LocalCommands() missing %s", want) } } } // The two command surfaces must describe the same set: /help lists the // names, adapters publish the specs, and a command in one but not the // other is either undiscoverable or advertised without an implementation. func TestLocalCommandSpecsAndCommandsAgree(t *testing.T) { names := LocalCommands() specs := LocalCommandSpecs() specified := make(map[string]bool, len(specs)) for _, s := range specs { specified[s.Command] = true if !slices.Contains(names, s.Command) { t.Errorf("LocalCommandSpecs() advertises %s, which Route does not handle", s.Command) } } for _, name := range names { if !specified[name] { t.Errorf("LocalCommandSpecs() is missing %s", name) } } } // TestSummarizeParkReasonBoundsAToolLog is the regression case for a single // parked task swamping /tasks. A gate failure parks the task with the tool's // whole output -- Sam's #10 carried a multi-line golangci-lint dump, warnings // and all -- which the list view rendered verbatim, pushing every other task // out of the reply. func TestSummarizeParkReasonBoundsAToolLog(t *testing.T) { reason := "stage fix: agent parked (gate_parked): [golangci-lint] golangci-lint run ./...\n" + "level=warning msg=\"[formatter] gofumpt: extra-rules is deprecated\"\n" + "scratchverify/main.go:38:1: calculated cyclomatic complexity for function run is 16, max is 15 (cyclop)\n" + "1 issues:\n- cyclop: 1" got := summarizeParkReason(reason) if strings.ContainsAny(got, "\n\r") { t.Fatalf("summarizeParkReason() = %q, want a single line", got) } if len([]rune(got)) > parkReasonMaxRunes+3 { t.Fatalf("summarizeParkReason() is %d runes, want at most %d plus the ellipsis", len([]rune(got)), parkReasonMaxRunes) } if !strings.HasPrefix(got, "stage fix: agent parked") { t.Fatalf("summarizeParkReason() = %q, want it to keep the leading reason", got) } } // TestSummarizeParkReasonKeepsAShortReasonIntact pins that the common case -- // a one-line reason an operator can act on -- is passed through untouched. func TestSummarizeParkReasonKeepsAShortReasonIntact(t *testing.T) { const reason = "diff is 789 changed lines (cap 400) -- split the issue or approve manually" if got := summarizeParkReason(reason); got != reason { t.Fatalf("summarizeParkReason() = %q, want it unchanged", got) } }