From f0cf11fee83d3d7a92c020835ecee5f422a8bbd9 Mon Sep 17 00:00:00 2001 From: Danathar Date: Fri, 6 Nov 2026 08:43:13 -0500 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20fix(scheduler):=20kicks=20point?= =?UTF-8?q?=20at=20hive-task=20only=20for=20agents=20that=20have=20the=20M?= =?UTF-8?q?CP=20server?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every kick told its agent "The hive-task MCP server is connected for this launch. Call context_bundle first". The pointer was gated only on the hive having a task MCP URL, which it always has, but only a Claude Code launch is given that server. Agents on every other backend were pointed at a tool they do not have, and task_mcp.drop_stuffed_context cut their work lists down to bare refs as well. The pointer and the elision now need the agent to launch as Claude Code (inference backends and gateway names included). The scheduler asks the agent runtime for the backend, so a provider-rotation override counts. A hive without a dashboard token mints no launch token and its endpoint refuses every call, so the scheduler is not given the endpoint there. Co-Authored-By: Claude Fable 5.1 Signed-off-by: Danathar --- ...ed-task-mcp-pointer-only-when-connected.md | 1 + src/cmd/hive/main.go | 2 +- src/cmd/hive/task_mcp_kick_wire.go | 40 ++++ src/cmd/hive/task_mcp_kick_wire_test.go | 100 ++++++++++ src/docs/agent-configuration.md | 8 +- src/docs/design/task-mcp.md | 13 +- src/hive.yaml.example | 3 +- src/pkg/scheduler/kick_layout.go | 4 +- src/pkg/scheduler/kickmessage.go | 46 ++++- src/pkg/scheduler/scheduler.go | 18 ++ .../task_mcp_pointer_connected_test.go | 184 ++++++++++++++++++ .../task_mcp_pointer_runtime_backend_test.go | 86 ++++++++ 12 files changed, 493 insertions(+), 12 deletions(-) create mode 100644 changelog.d/fixed-task-mcp-pointer-only-when-connected.md create mode 100644 src/cmd/hive/task_mcp_kick_wire.go create mode 100644 src/cmd/hive/task_mcp_kick_wire_test.go create mode 100644 src/pkg/scheduler/task_mcp_pointer_connected_test.go create mode 100644 src/pkg/scheduler/task_mcp_pointer_runtime_backend_test.go diff --git a/changelog.d/fixed-task-mcp-pointer-only-when-connected.md b/changelog.d/fixed-task-mcp-pointer-only-when-connected.md new file mode 100644 index 0000000000..9d6a03ceb9 --- /dev/null +++ b/changelog.d/fixed-task-mcp-pointer-only-when-connected.md @@ -0,0 +1 @@ +- Kicks: the "Task context MCP" pointer is now sent only to agents that have the `hive-task` MCP server. Every kick told its agent "The `hive-task` MCP server is connected for this launch. Call `context_bundle` first", but only a Claude Code launch is given that server, so agents on copilot, codex, gemini, goose, omp, pi, agy, bob, cline and the other non-Claude backends were told on every kick to call a tool they do not have. With `task_mcp.drop_stuffed_context: true` their issue and PR lists were also cut down to bare `repo#N` refs, leaving them with neither the lists nor the server. The pointer and the elision now apply only to an agent that launches as Claude Code (an inference backend or a model gateway counts, and an agent that provider rotation moved to another backend is judged by the backend it runs on) on a hive with a dashboard token; without that token no launch token is minted and the endpoint refuses every call, so no agent on such a hive is pointed at it. Every other agent gets the kick it had before the pointer existed. diff --git a/src/cmd/hive/main.go b/src/cmd/hive/main.go index ffaffbcd24..de1caccda2 100644 --- a/src/cmd/hive/main.go +++ b/src/cmd/hive/main.go @@ -1496,7 +1496,7 @@ func (b *boot) bootGovernor() { // one (#3498). Explicit thresholds are unaffected. b.gov.SetRepoCount(b.cfg.Project.RepoCount()) b.sched = scheduler.New(b.cfg, b.logger) - b.sched.SetTaskMCPURL(b.taskMCPURLForAgents()) + b.wireSchedulerTaskMCP() b.sched.SetSurgeDuration(b.gov.SurgeDuration) // A kick_template that resolves nowhere used to fail silently: the kick // fell through to the pack/convention template with no log line, and the diff --git a/src/cmd/hive/task_mcp_kick_wire.go b/src/cmd/hive/task_mcp_kick_wire.go new file mode 100644 index 0000000000..0c63762edc --- /dev/null +++ b/src/cmd/hive/task_mcp_kick_wire.go @@ -0,0 +1,40 @@ +package main + +import "strings" + +// Task MCP kick-pointer wiring. A kick tells the agent that the `hive-task` +// MCP server is connected for its launch, and with +// task_mcp.drop_stuffed_context it also cuts the work lists down to refs +// (pkg/scheduler). Both are only right for a launch that was handed the +// connection and a token the endpoint accepts, so the scheduler is given the +// two facts it cannot read from an agent's config. + +// wireSchedulerTaskMCP hands the scheduler the task MCP endpoint its kicks may +// point at and the runtime's backend lookup. +func (b *boot) wireSchedulerTaskMCP() { + b.sched.SetTaskMCPURL(b.taskMCPURLForKicks()) + b.sched.SetAgentBackendLookup(b.agentLaunchBackend) +} + +// taskMCPURLForKicks is taskMCPURLForAgents as the scheduler should see it: +// empty when no launch token can be minted. Without a dashboard token +// taskMCPLaunchTokenForAgents returns nothing, the launch carries the bare URL +// and the endpoint refuses every call, so no kick may point at it. The token +// is read once at boot, like the dashboard server's own copy of it. +func (b *boot) taskMCPURLForKicks() string { + if b == nil || b.cfg == nil || strings.TrimSpace(b.cfg.Dashboard.AuthToken) == "" { + return "" + } + return b.taskMCPURLForAgents() +} + +// agentLaunchBackend is the backend the runtime launches an agent on, with a +// backend override applied (provider rotation sets one without touching the +// agent's config). ok is false before the agent manager exists and for an +// agent it does not know; the scheduler then reads the configured backend. +func (b *boot) agentLaunchBackend(name string) (string, bool) { + if b == nil || b.agentMgr == nil { + return "", false + } + return b.agentMgr.EffectiveBackend(name) +} diff --git a/src/cmd/hive/task_mcp_kick_wire_test.go b/src/cmd/hive/task_mcp_kick_wire_test.go new file mode 100644 index 0000000000..eb0079ad2a --- /dev/null +++ b/src/cmd/hive/task_mcp_kick_wire_test.go @@ -0,0 +1,100 @@ +package main + +import ( + "path/filepath" + "strings" + "testing" + + "github.com/hivecommons/hive/crux" + "github.com/hivecommons/hive/crux/cruxtest" + "github.com/hivecommons/hive/crux/taskmcp" + "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/github" +) + +// kickTaskMCPClaim is how a kick tells an agent it has the hive-task server. +const kickTaskMCPClaim = "The `hive-task` MCP server is connected for this launch" + +// taskMCPKickBoot runs bootGovernor for a hive with one claude agent and the +// given dashboard token; "" is an open or allowlist-only spoke. +func taskMCPKickBoot(t *testing.T, dashboardToken string) *boot { + t.Helper() + cfg := &config.Config{} + cfg.Project.Org = "acme" + cfg.Project.Repos = []string{"acme/widgets"} + cfg.Dashboard.PublicURL = "https://hive.example" + cfg.Dashboard.AuthToken = dashboardToken + cfg.Agents = map[string]config.AgentConfig{"scanner": {Backend: "claude", Enabled: true}} + b, _ := newDepsTestBoot(t, cfg) + b.bootGovernor() + return b +} + +// taskMCPKickSaysConnected builds the scanner's kick and reports whether it +// claims the hive-task server. +func taskMCPKickSaysConnected(t *testing.T, b *boot) bool { + t.Helper() + work := &github.ActionableResult{Issues: github.IssueResultFromItems([]github.Issue{{Repo: "acme/widgets", Number: 7, Title: "a task"}})} + kick := b.sched.BuildAgentMessage("scanner", work.Issues.Items, work) + if kick == "" { + t.Fatal("scheduler built an empty kick") + } + return strings.Contains(kick, kickTaskMCPClaim) +} + +func TestKickPointsAtTaskMCPOnlyWhenALaunchTokenCanBeMinted(t *testing.T) { + scope := taskmcp.LaunchScope{TaskID: "scanner:acme/widgets#0:1", Repo: "acme/widgets", Agent: "scanner", Generation: 1} + + // No dashboard token: agents are still launched with the endpoint, but no + // launch token is minted for it and the endpoint refuses every call. + open := taskMCPKickBoot(t, "") + if open.taskMCPURLForAgents() == "" || open.taskMCPLaunchTokenForAgents(scope) != "" { + t.Fatalf("fixture: want a task MCP URL and no launch token, got url=%q token minted=%v", + open.taskMCPURLForAgents(), open.taskMCPLaunchTokenForAgents(scope) != "") + } + if taskMCPKickSaysConnected(t, open) { + t.Error("a hive that cannot mint a launch token told its agent the hive-task server is connected") + } + + // Control: with a dashboard token the same agent is pointed at it. + secured := taskMCPKickBoot(t, "dashboard-secret") + if secured.taskMCPLaunchTokenForAgents(scope) == "" { + t.Fatal("fixture: no launch token minted with a dashboard token set") + } + if !taskMCPKickSaysConnected(t, secured) { + t.Error("a claude agent with a mintable launch token was not pointed at the hive-task server") + } +} + +func TestKickTaskMCPPointerFollowsRuntimeBackendOverride(t *testing.T) { + b := taskMCPKickBoot(t, "dashboard-secret") + // Before the agent manager exists the configured backend decides. + if !taskMCPKickSaysConnected(t, b) { + t.Fatal("claude agent not pointed at the hive-task server before the agent manager exists") + } + + b.agentMgr = cruxtest.NewRuntime(b.cfg.Agents, b.logger, crux.ProjectContext{}, + cruxtest.WithUIDMapPath(filepath.Join(t.TempDir(), "uid-map.json"))) + if !taskMCPKickSaysConnected(t, b) { + t.Fatal("claude agent not pointed at the hive-task server once the agent manager exists") + } + + // Provider rotation moves an agent with SetBackendOverride and leaves its + // configured backend alone; a copilot launch gets no MCP configuration. + if err := b.agentMgr.SetBackendOverride("scanner", "copilot"); err != nil { + t.Fatalf("SetBackendOverride: %v", err) + } + if got := b.cfg.Agents["scanner"].Backend; got != "claude" { + t.Fatalf("fixture: configured backend = %q, want it left at claude", got) + } + if taskMCPKickSaysConnected(t, b) { + t.Error("an agent moved to copilot at runtime is still told the hive-task server is connected") + } + + if err := b.agentMgr.SetBackendOverride("scanner", "claude"); err != nil { + t.Fatalf("SetBackendOverride: %v", err) + } + if !taskMCPKickSaysConnected(t, b) { + t.Error("an agent moved back to claude is no longer pointed at the hive-task server") + } +} diff --git a/src/docs/agent-configuration.md b/src/docs/agent-configuration.md index 97f84f585e..d90ff7aff1 100644 --- a/src/docs/agent-configuration.md +++ b/src/docs/agent-configuration.md @@ -296,10 +296,14 @@ spec omits `launch_cmd`, Hive still builds the backend command normally. # Prompt text only — it authorizes repos, it does # NOT clone, mount, or provision anything on disk. task_mcp: - drop_stuffed_context: false # default false. When the hub gives this agent a - # task MCP URL, render ISSUE_LIST/PR_LIST and + drop_stuffed_context: false # default false. When this agent has the hive-task + # MCP server, render ISSUE_LIST/PR_LIST and # MERGE_ELIGIBLE as repo#N refs only and rely on # context_bundle / related_work for full context. + # Only an agent launched as Claude Code has the + # server (docs/design/task-mcp.md); on any other + # backend the flag is ignored and the lists stay + # complete. repos: [console] # WHICH repos this agent serves. Omit (the default) for # the whole hive. Naming repos makes the agent a # specialist: it is only handed work on these, its diff --git a/src/docs/design/task-mcp.md b/src/docs/design/task-mcp.md index 474264cf08..9809101c8c 100644 --- a/src/docs/design/task-mcp.md +++ b/src/docs/design/task-mcp.md @@ -2,11 +2,16 @@ Hive serves the Phase 1 task MCP endpoint on the dashboard mux at `POST /api/contribute/mcp`, under the existing contributor API prefix. The transport is streamable HTTP JSON-RPC 2.0 and is read-only. -Phase 1 was for hub-launched agents only. Hive injects the endpoint through agent `connections` as the `hive-task` MCP server so existing `connectionMCPFlags` launch handling can pass it to supported CLIs. +Phase 1 was for hub-launched agents only. Hive injects the endpoint through agent `connections` as the `hive-task` MCP server so existing `connectionMCPFlags` launch handling can pass it to supported CLIs. Today the only supported CLI is Claude Code: a launch on any other backend is not given the server. Agents on an inference backend or a configured model gateway run the claude CLI, so they have it too. Scope resolution accepts `task_id`, `repo`, and `number` from the `X-Hive-Task-ID` header, tool arguments, then URL query parameters in that order. The per-launch `hive-task` URI carries those query parameters plus a per-launch `token` (see "Hub-launched scoping" below); it never carries the dashboard auth token. Dashboard lookup first checks active contributor relay connections for backward compatibility, then falls through to the agent manager's active hub-launched agents. The active-launch entry supplies the agent, repo, launch generation, and started-at timestamp; until the manager has a stable issue/bead id for a launch, Hive derives the task id deterministically as `:#:`. -Hub-launched kick prompts include one short pointer when the task MCP URL is configured: call `context_bundle` on `hive-task` first instead of re-reading the issue/PR and CI from scratch. Hives without a task MCP URL keep the old prompt text. +Hub-launched kick prompts include one short pointer for the agents that have the server: call `context_bundle` on `hive-task` first instead of re-reading the issue/PR and CI from scratch. An agent gets the pointer only when both of these hold: + +- It launches as Claude Code (see above). The scheduler asks the agent runtime which backend the agent launches on, so an agent that provider rotation moved to another backend is judged by the backend it runs on, not the one in its config. +- The hive can mint the launch token the endpoint requires, which needs a dashboard token (see "Hub-launched scoping"). Without one the endpoint refuses every agent call. + +Every other agent keeps the old prompt text: an agent on any other backend, and every agent on a hive without a dashboard token. This is the **agent-facing** MCP surface. An operator-facing admin MCP — hive-wide, read/write, authenticated with the dashboard token, served both as its own endpoint and as a @@ -67,7 +72,7 @@ Phase 3 keeps the same read-only, cache/state-only invariant: request handling d Phase 1 measures the token delta on `context_bundle()`, not on each individual tool. For one real lane over a week, record the assignment prompt tokens before the measured hub-launched kick-prompt pointer above and after replacing stuffed context with that pointer. Compare the median per-task prompt-token count and keep the lane, backend, model, and date range with the measurement so Phase 2 can judge whether remote-contributor wiring is worth the added lease-auth surface. -The per-agent flag `agents..task_mcp.drop_stuffed_context: true` enables the replacement only when the hub supplies a task MCP URL. With the flag active, `${ISSUE_LIST}`, `${PR_LIST}`, and `${MERGE_ELIGIBLE}` keep their caps but render as `repo#N` refs only, and the pointer tells agents that `context_bundle` / `related_work` is the source of truth for titles, labels, age, annotations, and related context. Scheduler kick logs include `full_bytes` and `elided_bytes`; record the post-change week-long lane measurement in this section once one lane has run with the flag enabled. +The per-agent flag `agents..task_mcp.drop_stuffed_context: true` enables the replacement only for an agent that gets the pointer (see above). For any other agent the flag is ignored and the lists stay complete, because that agent has no server to read the missing context from. With the flag active, `${ISSUE_LIST}`, `${PR_LIST}`, and `${MERGE_ELIGIBLE}` keep their caps but render as `repo#N` refs only, and the pointer tells agents that `context_bundle` / `related_work` is the source of truth for titles, labels, age, annotations, and related context. Scheduler kick logs include `full_bytes` and `elided_bytes`; record the post-change week-long lane measurement in this section once one lane has run with the flag enabled. ### First live measurement (2026-09-22) @@ -82,3 +87,5 @@ Spoke `hive-hosted-hosted-kubestellar-console-4vkt` (kubestellar/console, 6 repo | Whole scanner kick / whole sec-check kick | 12168 / 10185 | 3042 / 2546 | Reading: today the pointer is **additive** (`addTaskMCPPointer` appends; `${ISSUE_LIST}`/`${PR_LIST}` still render), so on a quiet spoke the delta is negative (+54 tokens per kick, +169 per bundle call, against ≈48 tokens of stuffed lists). The stuffed lists only break even against pointer+bundle at roughly 6–9 queue lines, and only once the stuffed sections are actually dropped when a task MCP URL is set. That conditional-drop is the follow-up (#8261); the MCP path itself is verified end-to-end (tools/list 200, scoped bundle, refusal for non-matching generations, all seven tools answering). + +This spoke ran `copilot`. When it was measured the pointer was added to every hub kick; it is now sent only to agents that have the `hive-task` connection (see above), so a `copilot` agent's kick no longer carries those 215 bytes. diff --git a/src/hive.yaml.example b/src/hive.yaml.example index 3cee013b92..89d7cc2528 100644 --- a/src/hive.yaml.example +++ b/src/hive.yaml.example @@ -271,7 +271,8 @@ agents: include_repos: true # Append repos section to kicks (prompt text only — # authorizes repos, does not clone them) # task_mcp: - # drop_stuffed_context: false # When a hub task MCP URL is present, render + # drop_stuffed_context: false # When this agent has the hive-task MCP server + # (Claude Code launches only), render # ISSUE_LIST/PR_LIST/MERGE_ELIGIBLE as # repo#N refs only; default false. # repos: [repo-one] # WHICH repos this agent serves. Omit (the default) diff --git a/src/pkg/scheduler/kick_layout.go b/src/pkg/scheduler/kick_layout.go index 58f4b43f2f..a2ca9664c1 100644 --- a/src/pkg/scheduler/kick_layout.go +++ b/src/pkg/scheduler/kick_layout.go @@ -22,7 +22,7 @@ import ( // 5. workflow push ceiling static per agent mode // 6. formal quality capability static per role + config // 7. work tracker section static per work-source config -// 7b. task context MCP pointer static per agent task_mcp config +// 7b. task context MCP pointer static per agent backend + task_mcp config // 8. static text, then ${ISSUE_LIST}/${PR_LIST}/… where the template puts them // 9. REPO-SCOPED CADENCE TARGET semi-static (repo-scoped kicks only) // 10. AUTHORIZED REPOS semi-static (include_repos) @@ -90,7 +90,7 @@ func (s *Scheduler) assembleKick(a kickAssembly, message string) string { func(m string) string { return s.addWorkflowPushCeiling(a.agent, m) }, func(m string) string { return s.addFormalQualityCapability(a.agent, m) }, s.addWorkTrackerSection, - func(m string) string { return s.addTaskMCPPointer(m, a.elideStuffed) }, + func(m string) string { return s.addTaskMCPPointer(a.agent, m, a.elideStuffed) }, } for i := len(staticSeams) - 1; i >= 0; i-- { message = staticSeams[i](message) diff --git a/src/pkg/scheduler/kickmessage.go b/src/pkg/scheduler/kickmessage.go index ee16bd261d..3826055f09 100644 --- a/src/pkg/scheduler/kickmessage.go +++ b/src/pkg/scheduler/kickmessage.go @@ -682,7 +682,7 @@ func (s *Scheduler) reposSection() string { } func (s *Scheduler) dropStuffedContext(agentName string) bool { - if !s.hasTaskMCPURL() { + if !s.taskMCPConnected(agentName) { return false } if agentCfg, ok := s.cfg.Agents[agentName]; ok { @@ -694,8 +694,48 @@ func (s *Scheduler) dropStuffedContext(agentName string) bool { return false } -func (s *Scheduler) addTaskMCPPointer(message string, elideStuffed bool) string { - if message == "" || !s.hasTaskMCPURL() { +// taskMCPConnected reports whether agentName's CLI is really launched with the +// `hive-task` MCP server, which the kick pointer asserts and the elided work +// lists depend on. The hive must have an endpoint agents can use +// (SetTaskMCPURL), and the agent must launch as Claude Code: that is the only +// CLI the launcher builds an MCP configuration for (connectionMCPFlags in +// crux/agent), and an inference backend or a configured gateway name launches +// as "claude" too (launchInTmux). An agent on any other backend has no MCP +// server, so its kick must neither point at one nor drop the lists it replaces. +func (s *Scheduler) taskMCPConnected(agentName string) bool { + if !s.hasTaskMCPURL() { + return false + } + backend := s.launchBackend(agentName) + if backend == "" { + return false + } + return backend == "claude" || config.IsInferenceBackend(backend) || s.cfg.Governor.ResolveGateway(backend) != nil +} + +// launchBackend is the backend agentName launches on: the runtime's answer +// when a lookup is attached and knows the agent, else the configured backend +// with the same replica fallback as dropStuffedContext. +func (s *Scheduler) launchBackend(agentName string) string { + s.mu.RLock() + lookup := s.agentBackend + s.mu.RUnlock() + if lookup != nil { + if backend, ok := lookup(agentName); ok { + return backend + } + } + if agentCfg, ok := s.cfg.Agents[agentName]; ok { + return agentCfg.Backend + } + if agentCfg, ok := s.cfg.Agents[s.cfg.BaseAgentName(agentName)]; ok { + return agentCfg.Backend + } + return "" +} + +func (s *Scheduler) addTaskMCPPointer(agentName, message string, elideStuffed bool) string { + if message == "" || !s.taskMCPConnected(agentName) { return message } section := "## Task context MCP\n\nThe `hive-task` MCP server is connected for this launch. Call `context_bundle` first for the assigned task, related work, and CI summary instead of re-reading the issue/PR and CI from scratch.\n\n" diff --git a/src/pkg/scheduler/scheduler.go b/src/pkg/scheduler/scheduler.go index f03f1c6d48..b3192fd0c1 100644 --- a/src/pkg/scheduler/scheduler.go +++ b/src/pkg/scheduler/scheduler.go @@ -46,6 +46,7 @@ type Scheduler struct { questionAutocloser QuestionAutocloser lifecycle timeline.Recorder taskMCPURL string + agentBackend AgentBackendLookup laneDepths map[string]int scanned bool deferredKicks map[string]func(string) @@ -125,6 +126,9 @@ func New(cfg *config.Config, logger *slog.Logger) *Scheduler { } } +// SetTaskMCPURL records the task MCP endpoint hub-launched agents can really +// use. The host leaves it empty when it cannot mint the per-launch token the +// endpoint requires, and kicks then carry no task MCP pointer for any agent. func (s *Scheduler) SetTaskMCPURL(raw string) { s.mu.Lock() defer s.mu.Unlock() @@ -137,6 +141,20 @@ func (s *Scheduler) hasTaskMCPURL() bool { return strings.TrimSpace(s.taskMCPURL) != "" } +// AgentBackendLookup reports the backend an agent launches on once runtime +// overrides are applied. ok is false when the runtime does not know the agent. +type AgentBackendLookup func(agentName string) (backend string, ok bool) + +// SetAgentBackendLookup attaches the agent runtime's view of each agent's +// backend, where a backend override (provider rotation, a restored switch) +// wins over the configured one. Without it the scheduler reads the configured +// backend only. +func (s *Scheduler) SetAgentBackendLookup(fn AgentBackendLookup) { + s.mu.Lock() + defer s.mu.Unlock() + s.agentBackend = fn +} + // SetGitHubPromptResolver attaches a resolver used to fetch an agent's kick // prompt from a GitHub repo (agent.prompt_source). When nil, agents with a // prompt_source silently fall back to their inline kick template. diff --git a/src/pkg/scheduler/task_mcp_pointer_connected_test.go b/src/pkg/scheduler/task_mcp_pointer_connected_test.go new file mode 100644 index 0000000000..fa76bf8fd6 --- /dev/null +++ b/src/pkg/scheduler/task_mcp_pointer_connected_test.go @@ -0,0 +1,184 @@ +package scheduler + +import ( + "strings" + "testing" + + "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/github" +) + +// The kick's "## Task context MCP" section tells the agent the hive-task +// server is connected, and task_mcp.drop_stuffed_context cuts the work lists +// down to refs because that server replaces them. Both are only true for an +// agent launched as Claude Code, the one CLI the launcher builds an MCP +// configuration for (connectionMCPFlags in crux/agent); these tests pin which +// agents that is. + +// taskMCPPointerClaim is how a kick tells the agent it has the server. +const taskMCPPointerClaim = "The `hive-task` MCP server is connected for this launch" + +// taskMCPElidedNote is what the pointer adds once the lists are refs only. +const taskMCPElidedNote = "Stuffed work lists in this prompt were elided" + +const taskMCPTestURL = "http://hub/api/contribute/mcp" + +func taskMCPPointerConfig(agents map[string]config.AgentConfig) *config.Config { + canaries := false + cfg := &config.Config{} + cfg.Project = config.ProjectConfig{Org: "hivecommons", Repos: []string{"hivecommons/hive"}, PrimaryRepo: "hive"} + cfg.Agents = agents + cfg.Ioscan = config.IoscanConfig{Canaries: &canaries} + return cfg +} + +func taskMCPPointerWork() *github.ActionableResult { + return &github.ActionableResult{ + Issues: github.IssueResultFromItems([]github.Issue{{ + Repo: "hivecommons/hive", Number: 8261, Title: "stuffed issue title", AgeMinutes: 17, Labels: []string{"kind/feature"}, + }}), + PRs: github.PRResult{ + Count: 1, + Items: []github.PullRequest{{Repo: "hivecommons/hive", Number: 8262, Title: "stuffed pr title", Author: "alice"}}, + }, + } +} + +// taskMCPKick builds agent's governor kick from cfg, with or without a task +// MCP URL on the scheduler. +func taskMCPKick(t *testing.T, cfg *config.Config, agent string, withURL bool) string { + t.Helper() + s := New(cfg, testLogger()) + if withURL { + s.SetTaskMCPURL(taskMCPTestURL) + } + msgs := s.BuildKickMessages(taskMCPPointerWork(), []string{agent}) + if len(msgs) != 1 || msgs[0].Message == "" { + t.Fatalf("agent %s: got %d kick messages, want one non-empty kick", agent, len(msgs)) + } + return msgs[0].Message +} + +func TestTaskMCPPointerOnlyForBackendsThatLaunchClaude(t *testing.T) { + // An inference backend or a configured gateway name is launched as the + // claude CLI, so it has the server too. Nothing else does. + const gateway = "corp-gateway" + connected := map[string]bool{"claude": true, gateway: true} + for _, backend := range config.InferenceBackends { + connected[backend] = true + } + backends := append(config.SupportedBackends(), gateway, "unconfigured-gateway", "") + told, notTold := 0, 0 + for _, backend := range backends { + cfg := taskMCPPointerConfig(map[string]config.AgentConfig{"scanner": {Backend: backend}}) + cfg.Governor.Gateways = []config.GatewayConfig{{Name: gateway, Endpoint: "https://gateway.example/v1"}} + s := New(cfg, testLogger()) + s.SetTaskMCPURL(taskMCPTestURL) + work := taskMCPPointerWork() + msg := s.BuildAgentMessage("scanner", work.Issues.Items, work) + if msg == "" { + t.Fatalf("backend %q: empty kick", backend) + } + got := strings.Contains(msg, taskMCPPointerClaim) + if got != connected[backend] { + t.Errorf("backend %q: kick says the hive-task server is connected = %v, want %v", backend, got, connected[backend]) + } + if connected[backend] { + told++ + } else { + notTold++ + } + } + // Guard the table itself: claude, the inference backends and the gateway + // on one side, every other CLI backend plus the two non-backends on the + // other, so a backend added to either canonical list is covered too. + wantTold, wantNotTold := len(config.InferenceBackends)+2, len(config.CLIBackends)-1+2 + if told != wantTold || notTold != wantNotTold { + t.Fatalf("table covered %d connected and %d unconnected backends, want %d and %d", told, notTold, wantTold, wantNotTold) + } +} + +func TestTaskMCPDropStuffedContextNeedsTheConnection(t *testing.T) { + withFlag := func(backend string) *config.Config { + return taskMCPPointerConfig(map[string]config.AgentConfig{ + "scanner": {Backend: backend, TaskMCP: &config.AgentTaskMCPConfig{DropStuffedContext: true}}, + }) + } + for _, backend := range []string{"copilot", "codex", "cline"} { + kick := taskMCPKick(t, withFlag(backend), "scanner", true) + for _, forbidden := range []string{taskMCPPointerClaim, taskMCPElidedNote, "context_bundle"} { + if strings.Contains(kick, forbidden) { + t.Errorf("backend %s: kick mentions the task MCP (%q) though this agent has no MCP server", backend, forbidden) + } + } + for _, want := range []string{"stuffed issue title", "stuffed pr title"} { + if !strings.Contains(kick, want) { + t.Errorf("backend %s: drop_stuffed_context cut %q out of the work lists, leaving bare refs and no MCP to read them from", backend, want) + } + } + // The strongest form: the task MCP URL changes nothing for this agent. + if old := taskMCPKick(t, withFlag(backend), "scanner", false); kick != old { + t.Errorf("backend %s: a hive-wide task MCP URL changed the kick of an agent that cannot use it", backend) + } + } + + // Control: the flag still elides for an agent that has the server. + kick := taskMCPKick(t, withFlag("claude"), "scanner", true) + if !strings.Contains(kick, taskMCPPointerClaim) || !strings.Contains(kick, taskMCPElidedNote) { + t.Fatalf("claude: kick is missing the task MCP pointer or its elision note:\n%s", kick) + } + if strings.Contains(kick, "stuffed issue title") || strings.Contains(kick, "stuffed pr title") { + t.Fatalf("claude: drop_stuffed_context left stuffed titles in the kick:\n%s", kick) + } +} + +// An agent the hive holds no config for cannot be shown to have the server. +func TestTaskMCPPointerNotForUnconfiguredAgent(t *testing.T) { + cfg := taskMCPPointerConfig(map[string]config.AgentConfig{"scanner": {Backend: "claude"}}) + if kick := taskMCPKick(t, cfg, "helper", true); strings.Contains(kick, taskMCPPointerClaim) { + t.Error("an agent with no configured backend is told the hive-task server is connected") + } + // Control: the configured claude agent beside it still is. + if kick := taskMCPKick(t, cfg, "scanner", true); !strings.Contains(kick, taskMCPPointerClaim) { + t.Fatalf("claude agent not pointed at the hive-task server:\n%s", kick) + } +} + +func TestTaskMCPPointerForReplicasAndReviewHeads(t *testing.T) { + drop := &config.AgentTaskMCPConfig{DropStuffedContext: true} + codexHead := config.ReviewHead{Backend: "codex", Model: "gpt-5", Alias: "codex"} + claudeHead := config.ReviewHead{Backend: "claude", Model: "claude-sonnet-5", Alias: "claude"} + // Which base carries the heads does not matter here: a head is a derived + // agent marked ReplicaOf its base that runs a backend of its own. + cfg := taskMCPPointerConfig(map[string]config.AgentConfig{ + "scanner": {Backend: "claude", Replicas: 2, TaskMCP: drop, ReviewHeads: []config.ReviewHead{codexHead}}, + "quality": {Backend: "copilot", Replicas: 2, TaskMCP: drop, ReviewHeads: []config.ReviewHead{claudeHead}}, + }) + if err := cfg.ExpandAgentReplicas(); err != nil { + t.Fatalf("ExpandAgentReplicas: %v", err) + } + + for _, tc := range []struct { + agent string + connected bool + why string + }{ + {"scanner", true, "a claude agent"}, + {"scanner-2", true, "a replica of a claude agent"}, + {"quality", false, "a copilot agent"}, + {"quality-2", false, "a replica of a copilot agent"}, + {config.ReviewHeadAgentName("scanner", codexHead, 1), false, "a codex review head of a claude base"}, + {config.ReviewHeadAgentName("quality", claudeHead, 1), true, "a claude review head of a copilot base"}, + } { + if _, ok := cfg.Agents[tc.agent]; !ok { + t.Fatalf("%s: ExpandAgentReplicas did not materialize %s", tc.why, tc.agent) + } + kick := taskMCPKick(t, cfg, tc.agent, true) + if got := strings.Contains(kick, taskMCPPointerClaim); got != tc.connected { + t.Errorf("%s (%s): kick says the hive-task server is connected = %v, want %v", tc.agent, tc.why, got, tc.connected) + } + if got := strings.Contains(kick, taskMCPElidedNote); got != tc.connected { + t.Errorf("%s (%s): work lists elided = %v, want %v", tc.agent, tc.why, got, tc.connected) + } + } +} diff --git a/src/pkg/scheduler/task_mcp_pointer_runtime_backend_test.go b/src/pkg/scheduler/task_mcp_pointer_runtime_backend_test.go new file mode 100644 index 0000000000..561e69f0ac --- /dev/null +++ b/src/pkg/scheduler/task_mcp_pointer_runtime_backend_test.go @@ -0,0 +1,86 @@ +package scheduler + +import ( + "strings" + "testing" + + "github.com/hivecommons/hive/pkg/config" +) + +// Provider rotation (and a restored backend switch) change the backend an +// agent launches on without touching its config, so the task MCP pointer +// follows the agent runtime's answer when the host attaches one. +func TestTaskMCPPointerFollowsRuntimeBackend(t *testing.T) { + drop := &config.AgentTaskMCPConfig{DropStuffedContext: true} + newConfig := func() *config.Config { + cfg := taskMCPPointerConfig(map[string]config.AgentConfig{ + "scanner": {Backend: "claude", Replicas: 2, TaskMCP: drop}, + "quality": {Backend: "copilot", TaskMCP: drop}, + }) + if err := cfg.ExpandAgentReplicas(); err != nil { + t.Fatalf("ExpandAgentReplicas: %v", err) + } + return cfg + } + + for _, tc := range []struct { + name string + // runtime maps an agent to the backend the runtime launches it on; an + // agent missing from it is unknown to the runtime. + runtime map[string]string + agent string + connected bool + }{ + {"claude agent moved to copilot", map[string]string{"scanner": "copilot"}, "scanner", false}, + {"copilot agent moved to claude", map[string]string{"quality": "claude"}, "quality", true}, + {"copilot agent moved to an inference backend", map[string]string{"quality": "litellm"}, "quality", true}, + {"runtime does not know the agent, configured claude", nil, "scanner", true}, + {"runtime does not know the agent, configured copilot", nil, "quality", false}, + {"replica moved on its own", map[string]string{"scanner-2": "codex"}, "scanner-2", false}, + {"a moved replica leaves its base alone", map[string]string{"scanner-2": "codex"}, "scanner", true}, + } { + t.Run(tc.name, func(t *testing.T) { + s := New(newConfig(), testLogger()) + s.SetTaskMCPURL(taskMCPTestURL) + s.SetAgentBackendLookup(func(agent string) (string, bool) { + backend, ok := tc.runtime[agent] + return backend, ok + }) + msgs := s.BuildKickMessages(taskMCPPointerWork(), []string{tc.agent}) + if len(msgs) != 1 || msgs[0].Message == "" { + t.Fatalf("got %d kick messages, want one non-empty kick", len(msgs)) + } + kick := msgs[0].Message + if got := strings.Contains(kick, taskMCPPointerClaim); got != tc.connected { + t.Errorf("kick says the hive-task server is connected = %v, want %v", got, tc.connected) + } + if got := strings.Contains(kick, taskMCPElidedNote); got != tc.connected { + t.Errorf("work lists elided = %v, want %v", got, tc.connected) + } + }) + } +} + +// A hive with no usable task MCP endpoint points no agent at it, so it has +// nothing to ask the runtime (a sidecar runtime answers over HTTP). +func TestTaskMCPPointerDoesNotAskRuntimeWithoutEndpoint(t *testing.T) { + cfg := taskMCPPointerConfig(map[string]config.AgentConfig{ + "scanner": {Backend: "claude", TaskMCP: &config.AgentTaskMCPConfig{DropStuffedContext: true}}, + }) + s := New(cfg, testLogger()) + asked := 0 + s.SetAgentBackendLookup(func(string) (string, bool) { + asked++ + return "claude", true + }) + msgs := s.BuildKickMessages(taskMCPPointerWork(), []string{"scanner"}) + if len(msgs) != 1 { + t.Fatalf("got %d kick messages, want 1", len(msgs)) + } + if strings.Contains(msgs[0].Message, taskMCPPointerClaim) { + t.Fatal("kick points at the hive-task server though the hive has no task MCP URL") + } + if asked != 0 { + t.Fatalf("runtime backend lookup called %d times with no task MCP URL, want 0", asked) + } +}