diff --git a/changelog.d/added-admin-mcp-activity-monitor.md b/changelog.d/added-admin-mcp-activity-monitor.md new file mode 100644 index 0000000000..90766e1f91 --- /dev/null +++ b/changelog.d/added-admin-mcp-activity-monitor.md @@ -0,0 +1 @@ +- Admin MCP reads and acts on the Activity monitor: `stage_tracker_read` returns the board (stages, what each item waits on, decision options, linked items, blockers) with the monitor's filters and search, `delegated_decision_status` reads a "Let hive decide" job, and the `repository.rescan` and `repository.item_*` write operations are the monitor's row actions (accept triage, needs-human, blocker re-check / hand-off / partial close, Decide answers, Let hive decide) — never the merge answers, and a delegated decision sent through admin MCP never queues an auto-merge. On the HTTP endpoint a confirmed write now runs as the caller the hive verified (session or hub proxy), bound to whoever previewed it, so hub-proxied callers can write and their writes are attributed to them. diff --git a/src/cmd/hive-admin-mcp/main.go b/src/cmd/hive-admin-mcp/main.go index 5b0c36d103..47eeca5621 100644 --- a/src/cmd/hive-admin-mcp/main.go +++ b/src/cmd/hive-admin-mcp/main.go @@ -360,6 +360,11 @@ func (p readProvider) Read(ctx context.Context, tool string, args map[string]any return nil, err } } + if tool == adminmcp.ToolDelegatedDecisionStatus { + if _, err := adminmcp.DelegatedDecisionStatusPath(args); err != nil { + return nil, err + } + } path, ok := readPath(tool, args) if !ok { return nil, &unsupportedToolError{tool: tool} @@ -379,6 +384,12 @@ func (p readProvider) Read(ctx context.Context, tool string, args map[string]any if tool == adminmcp.ToolIssuesByBand || tool == adminmcp.ToolPrsByBand { return adminmcp.BandReadResult(tool, data, args) } + if tool == adminmcp.ToolStageTrackerRead { + return adminmcp.StageTrackerReadResult(data, args) + } + if tool == adminmcp.ToolDelegatedDecisionStatus { + return data, nil + } if tool == adminmcp.ToolGovernorSetup { return adminmcp.GovernorSetupProposal(data) } @@ -550,6 +561,13 @@ func readPath(tool string, args map[string]any) (string, bool) { if tool == adminmcp.ToolAdvisorRecords { return adminmcp.AdvisorRecordsReadPath(args), true } + if tool == adminmcp.ToolStageTrackerRead { + return adminmcp.StageTrackerReadPath(), true + } + if tool == adminmcp.ToolDelegatedDecisionStatus { + path, err := adminmcp.DelegatedDecisionStatusPath(args) + return path, err == nil + } return adminmcp.ReadPath(tool, adminmcp.LimitFromArgs(args)) } diff --git a/src/docs/admin-mcp.md b/src/docs/admin-mcp.md index c8d8527ec8..fcf2205b33 100644 --- a/src/docs/admin-mcp.md +++ b/src/docs/admin-mcp.md @@ -1,39 +1,116 @@ # Admin MCP -The admin MCP lets you administer a hive by conversation from any MCP client -(Claude Code, omp, and others): ask about fleet status, agents, leases, plans, -spend and audit history, and — when you switch it on — pause an agent, approve -a plan or change a budget through a two-step confirmation. +The admin MCP lets you run a hive by conversation from any MCP client, such as +Claude Code or omp. You can ask about fleet status, agents, leases, plans, +spend and audit history. When writes are switched on, you can also make +changes, such as pausing an agent, approving a plan or changing a budget. Every +write takes a two-step confirmation. -It is available on the `v6` line only. There are two ways to reach it: +It is available on the `v6` line only. -| Transport | Where it runs | Use it when | -|-----------|---------------|-------------| -| **HTTP** (recommended) | `POST /api/admin/mcp` on the dashboard | Your client accepts a plain JSON-RPC HTTP endpoint. The running hub serves the tool catalogue, so it never drifts and there is nothing to rebuild after an upgrade. One entry per hive. | -| **Stdio** | the `hive-admin-mcp` binary on your machine | Your client cannot use the HTTP endpoint, or you manage several hives from one entry (`select_hive` is stdio-only). The catalogue is compiled into the binary, so re-extract or rebuild it after each hub upgrade. | +**On this page:** [Quick start](#quick-start) · +[Authentication](#authentication) · [Connect your client](#connect-your-client) · +[HTTP endpoint](#http-endpoint) · [Stdio binary](#stdio-binary) · +[Several hives](#several-hives) · [Tools](#tools) · [Writes](#writes) · +[Troubleshooting](#troubleshooting) -Use HTTP whenever your client supports it. +## Two ways to connect + +| Transport | Where it runs | Use it when | +| ---------------------- | ------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | +| **HTTP** (recommended) | `POST /api/admin/mcp` on the dashboard | Your client accepts a plain JSON-RPC HTTP endpoint. Add one entry per hive. | +| **Stdio** | the `hive-admin-mcp` binary on your machine | Your client cannot use the HTTP endpoint, or you want one entry for several hives (`select_hive` is stdio-only). | + +Use HTTP whenever your client supports it. The running hub serves the HTTP tool +catalogue, so it never drifts and there is nothing to rebuild after an upgrade. +The stdio binary has the catalogue compiled in, so you must re-extract or +rebuild it after each hub upgrade. ## Quick start -1. **Get the token.** The admin MCP uses the same dashboard token as - [`hivectl`](hivectl.md): `HIVE_DASHBOARD_TOKEN` or `dashboard.auth_token`. - See [Generating and rotating `HIVE_DASHBOARD_TOKEN`](env-vars.md#generating-and-rotating-hive_dashboard_token). -2. **Pick a transport** (HTTP if your client supports it) and paste the matching client config below. -3. **Run one tool.** Ask the client to call `hive_status`. A JSON status - summary back means you are connected. +1. **Find out which credential your hive takes** (see [Authentication](#authentication)). + A hive hosted by the hub takes **your GitHub token**, and you act as yourself. + A self-hosted hive takes its **dashboard token**, which acts as the owner. +2. **Pick a transport** (HTTP if your client supports it) and paste the + matching config from [Connect your client](#connect-your-client). +3. **Run one tool.** Ask the client to call `hive_status`. If you get a JSON + status summary back, you are connected. + +## Authentication + +How the hive is deployed decides which credential works, not the client. The +endpoint accepts whatever the dashboard accepts: + +| Your hive | Credential | Header | You act as | +| --------------------------------------------------------------------- | ------------------------------------------------------- | ----------------------------------------- | ---------------------------------------------------- | +| Hosted by the hub (`https://.hive.hivecommons.dev`) | Your GitHub token | `Authorization: Bearer ` | Yourself, at your role on that hive | +| Self-hosted, `dashboard.auth_token` set, no `authorized_users` | The dashboard token | `Authorization: Bearer ` | The owner (the configured owner's login, or `owner`) | +| Self-hosted spoke with an `authorized_users` allowlist (direct-route) | Your per-user session from `hivectl --server URL login` | `Cookie: hive_session=` | Yourself, at your allowlist role | + +### Hosted by the hub: your GitHub token + +- **How it is checked.** The hub asks GitHub who the token belongs to + (`GET /user`, cached for five minutes). It lets you in only if your login has + a role on that hive. It then passes your login and role to the hive, so your + reads, your writes and the audit log are all yours. +- **Which token to use.** The token only proves who you are. Give the MCP a + **fine-grained token with no repository permissions** + (), not your everyday + `gh` login, which can usually push code. +- **Where to keep it.** Keep it in a file only you can read, and have the client + read that file at connect time, so the token never sits in the client's + config. +- `gh auth token` also works, but it sends that broader token to the hub on + every connection. + +### Self-hosted: the dashboard token + +The dashboard token is `HIVE_DASHBOARD_TOKEN` or `dashboard.auth_token`. See +[Generating and rotating `HIVE_DASHBOARD_TOKEN`](env-vars.md#generating-and-rotating-hive_dashboard_token). + +**The dashboard token is the owner credential.** Anyone holding it acts as the +hive's owner, with no personal identity. That is why a spoke with an allowlist +refuses it. Use it only on a self-hosted hive you run. + +### Allowlist spokes: a per-user session + +These spokes accept only a per-user session. Send it the same way +[`hivectl`](hivectl.md#credentials) does, as a `Cookie` header. This path is not +yet verified with an MCP client. + +## Connect your client + +Replace the addresses below with your own hive's or dashboard's. + +### Claude Code + +**Hosted by the hub.** Put the server in `~/.claude.json` or a project +`.mcp.json` with a `headersHelper`: a command Claude Code runs at connect time +to produce the headers. In this example the fine-grained token is kept in +`~/.config/hive/github-mcp-token` (mode `0600`): + +```json +{ + "mcpServers": { + "hive": { + "type": "http", + "url": "https://.hive.hivecommons.dev/api/admin/mcp", + "headersHelper": "printf '{\"Authorization\":\"Bearer %s\"}' \"$(cat ~/.config/hive/github-mcp-token)\"" + } + } +} +``` -### Client config: HTTP +To use your `gh` login instead, replace the `cat …` with `gh auth token`. -Claude Code: +**Self-hosted, with the dashboard token.** From the command line: ```bash claude mcp add --transport http hive http://127.0.0.1:3001/api/admin/mcp \ --header "Authorization: Bearer $HIVE_DASHBOARD_TOKEN" ``` -Or in an MCP JSON config (for example a project `.mcp.json`; omp has its own -config paths, see [omp](#omp)): +Or in an MCP JSON config, such as a project `.mcp.json`: ```json { @@ -47,18 +124,30 @@ config paths, see [omp](#omp)): } ``` -Replace the address with your dashboard's. The endpoint is stateless (see -[HTTP endpoint](#http-endpoint)). omp is verified to work with it. A strict -streamable-HTTP client that insists on SSE or a session id may refuse it; if -you have not checked your client, try HTTP first and fall back to stdio if it -is refused. +### omp + +omp has its own config paths. It reads `~/.omp/agent/mcp.json` (user scope) or +`.omp/mcp.json` (one project), and reads a root `.mcp.json` only as a fallback. -#### omp +Keep the token out of the file. Use either an environment variable, such as +`${HIVE_DASHBOARD_TOKEN}`, or a `!command` header value, which omp runs at +connect time. -omp reads `~/.omp/agent/mcp.json` (user scope) or `.omp/mcp.json` (one -project). It only reads a root `.mcp.json` as a fallback. Keep the token out of -the file: use `${HIVE_DASHBOARD_TOKEN}`, or a `!command` header value that omp -runs at connect time: +**Hosted by the hub, with your GitHub token:** + +```json +{ + "mcpServers": { + "hive-admin": { + "type": "http", + "url": "https://.hive.hivecommons.dev/api/admin/mcp", + "headers": { "Authorization": "!printf 'Bearer %s' \"$(cat ~/.config/hive/github-mcp-token)\"" } + } + } +} +``` + +**Self-hosted, with the dashboard token:** ```json { @@ -72,20 +161,31 @@ runs at connect time: } ``` +Or read the token from a stdio roster file with a `!command`: + ```json "headers": { "Authorization": "!jq -r '\"Bearer \" + (.[] | select(.name==\"local\").token)' /path/to/hives.json" } ``` -omp 18.8.9 is verified against the stateless endpoint (`hive_status`, -`issues_by_band` and `prs_by_band` all returned data). The hub answers -`notifications/initialized` with `200` and `{"jsonrpc":"2.0","result":{}}` -rather than a bare `202`, which omp accepts. `GET` returns `405`, and omp -disables its optional SSE listener without an error. +**Verified.** omp 18.8.9 works against the stateless endpoint: `hive_status`, +`issues_by_band` and `prs_by_band` all returned data. + +- The hub answers `notifications/initialized` with `200` and + `{"jsonrpc":"2.0","result":{}}` rather than a bare `202`, which omp accepts. +- `GET` returns `405`, and omp turns off its optional SSE listener without an + error. + +### Other HTTP clients + +The endpoint is stateless (see [HTTP endpoint](#http-endpoint)). A strict +streamable-HTTP client that insists on SSE or a session id may refuse it. If you +have not checked your client, try HTTP first, and fall back to stdio if it is +refused. -### Client config: stdio +### Stdio clients -First get the binary onto the host (see [Getting the binary](#getting-the-binary)), -then: +First get the binary onto the host (see [Getting the binary](#getting-the-binary)). +Then: ```json { @@ -100,7 +200,7 @@ then: } ``` -Claude Code equivalent: +The same with the Claude Code command line: ```bash claude mcp add hive-admin \ @@ -110,26 +210,30 @@ claude mcp add hive-admin \ ## HTTP endpoint -`POST /api/admin/mcp` is always registered on v6; there is no enable flag. +`POST /api/admin/mcp` is always registered on v6. There is no flag to turn it +on. -- Stateless JSON-RPC 2.0: one request per POST, no SSE, no session id. -- `ping` is answered with an empty result. A notification (any - `notifications/...` method) is acknowledged with `200` and +- **Protocol:** stateless JSON-RPC 2.0. One request per POST, no SSE, no + session id. `GET` returns 405. +- **Ping and notifications:** `ping` is answered with an empty result. A + notification (any `notifications/...` method) is acknowledged with `200` and `{"jsonrpc":"2.0","result":{}}`, never with an error. -- `GET` returns 405. -- Request bodies are capped at 64 KiB. -- Authenticate with `Authorization: Bearer `. A `?token=` query - parameter is rejected. -- Do not send `X-Hive-User`, `X-Hive-Role` or `X-Hive-Owner-Role-Verified`. -- A spoke with an `authorized_users` allowlist refuses the shared token, so a - token client cannot administer it. +- **Size:** request bodies are capped at 64 KiB. +- **Credential:** as in [Authentication](#authentication). Send + `Authorization: Bearer` with your GitHub token (hosted by the hub) or the + dashboard token (self-hosted), or a `Cookie` session on an allowlist spoke. A + `?token=` query parameter is rejected. A spoke with an `authorized_users` + allowlist refuses the dashboard token. +- **Identity headers:** do not send `X-Hive-User`, `X-Hive-Role` or + `X-Hive-Owner-Role-Verified`. The hive strips them; your identity comes only + from the credential. ## Stdio binary ### Getting the binary -The image carries it at `/usr/local/share/hive/hive-admin-mcp`. There is no -separate release artifact today. Copy it out of the container: +The image carries the binary at `/usr/local/share/hive/hive-admin-mcp`. There is +no separate release artifact today. Copy it out of the container: ```bash podman create --name hive-admin-mcp-extract ghcr.io/hivecommons/hive:edge @@ -137,64 +241,89 @@ podman cp hive-admin-mcp-extract:/usr/local/share/hive/hive-admin-mcp ~/.local/b podman rm hive-admin-mcp-extract ``` -The image tag must match the hive's own release line: use `:edge` for v6 (today's -v6 publishing channel), `:stable` once v6 is promoted to stable, etc. The binary -warns on build skew with the hub it talks to, so matching lines ensures they -agree on the protocol. - -Or build it from a checkout of the `v6` branch: `cd src && go build -o hive-admin-mcp ./cmd/hive-admin-mcp`. - -The tool catalogue is compiled into the binary, so re-extract or rebuild it after each hub upgrade (HTTP has no such step). `version_read` shows the binary's own `stdio_build` and a `skew` flag next to the hub build, and `initialize` reports `serverInfo.version` as `+`. Over HTTP, `version_read` returns the recorded last-seen stdio build (`last_seen_stdio_build`) and timestamp (`last_seen_stdio_at`) alongside `hub_build`. - -The stdio binary sends `User-Agent: hive-admin-mcp/+` on every hub request. The hub records the last-seen stdio client build and the time it was seen from that header on the REST paths the binary's read tools call — `GET /api/version`, `GET /api/status` and `GET /api/status/summary` — and on HTTP admin MCP read tool calls (`/api/admin/mcp`). Only a well-formed `hive-admin-mcp/+<7–40 hex short sha|unknown>` of at most 64 bytes is recorded; any other User-Agent (browsers, `curl`, the regular `hivectl` CLI's default `hivectl/0.1`) is ignored and never overwrites a recorded sighting. The dashboard displays this in the Version menu under **Stdio client** next to the hub build, with a warning badge (`⚠ build skew`) when the short SHAs differ. +Use the image tag for the hive's own release line: `:edge` for v6 (today's v6 +publishing channel), `:stable` once v6 is promoted to stable, and so on. The +binary warns when its build differs from the hub's, so matching lines keep them +agreeing on the protocol. + +Or build it from a checkout of the `v6` branch: +`cd src && go build -o hive-admin-mcp ./cmd/hive-admin-mcp`. + +### Keeping it current + +The tool catalogue is compiled into the binary, so re-extract or rebuild it +after each hub upgrade. (HTTP has no such step.) Three places show which build +you have: + +- `version_read` shows the binary's own `stdio_build` and a `skew` flag next to + the hub build. +- `initialize` reports `serverInfo.version` as `+`. +- Over HTTP, `version_read` returns the last stdio build the hub saw + (`last_seen_stdio_build`) and when (`last_seen_stdio_at`), alongside + `hub_build`. + +**How the hub records the stdio build.** The binary sends +`User-Agent: hive-admin-mcp/+` on every hub request (the +same value as `serverInfo.version`), instead of hivectl's `hivectl/0.1`. + +- The hub records the build, and when it saw it, from that header on the REST + paths the binary's read tools call (`GET /api/version`, `GET /api/status` and + `GET /api/status/summary`) and on HTTP admin MCP read tool calls + (`/api/admin/mcp`). +- Only a well-formed `hive-admin-mcp/+<7–40 hex short sha|unknown>` of + at most 64 bytes is recorded. Any other User-Agent (browsers, `curl`, the + regular `hivectl` CLI's default `hivectl/0.1`) is ignored and never overwrites + a recorded sighting. +- The dashboard shows it in the Version menu under **Stdio client**, next to the + hub build, with a warning badge (`⚠ build skew`) when the short SHAs differ. ### Skew notice The binary also tells the agent when it is out of step with the hub, so a stale -binary no longer fails tools with no hint. At startup it fetches -`/api/version` from the active hive (3-second timeout), and again whenever -`select_hive` switches hives. When its short SHA differs from the hub's, it -builds a one-line notice that names both SHAs and points here: re-extract or -rebuild the binary as described in [Getting the binary](#getting-the-binary). - -- **`initialize`:** if skew is found at startup, the notice is sent as the - server `instructions`, which MCP clients put into the agent's context. - Instructions are fixed at `initialize`, so skew found after `select_hive` - only shows up in errors. -- **Tool errors:** the notice is appended to errors the binary raises itself - (`unsupported admin MCP read tool`, `unknown tool`) and to hub 404s on read - tools. Other errors are not changed. - -There is no notice when either SHA is `unknown`, when the hub cannot be -reached, or when the builds match; errors are then exactly as before. Binaries -built before this notice existed cannot warn, so keep re-extracting or +binary no longer fails tools with no hint. + +- **When it checks:** at startup it fetches `/api/version` from the active hive + (3-second timeout), and again whenever `select_hive` switches hives. +- **What it says:** when its short SHA differs from the hub's, it builds a + one-line notice that names both SHAs and points here: re-extract or rebuild + the binary as described in [Getting the binary](#getting-the-binary). +- **Where it appears:** + - **`initialize`:** if skew is found at startup, the notice is sent as the + server `instructions`, which MCP clients put into the agent's context. + Instructions are fixed at `initialize`, so skew found after `select_hive` + shows up only in errors. + - **Tool errors:** the notice is added to errors the binary raises itself + (`unsupported admin MCP read tool`, `unknown tool`) and to hub 404s on read + tools. Other errors are not changed. +- **When it stays quiet:** there is no notice when either SHA is `unknown`, when + the hub cannot be reached, or when the builds match. Errors are then exactly + as before. + +Binaries built before this notice existed cannot warn, so keep re-extracting or rebuilding after each hub upgrade. -Requests from the binary send `User-Agent: hive-admin-mcp/+` -(the same value as `serverInfo.version`) instead of hivectl's `hivectl/0.1`. - ### Environment variables -| Variable | Required | Meaning | -|----------|----------|---------| -| `HIVE_ADMIN_MCP_HIVES` | Yes | JSON array of `{"name","address","token"}`. All three fields are required and names must be unique. The binary exits with an error otherwise. | -| `HIVE_ADMIN_MCP_ACTIVE` | No | Name of the hive active at start. Defaults to the first entry; an unknown name is an error. | -| `HIVE_ADMIN_MCP_ENABLE_WRITES` | No | `1`, `true`, `yes` or `on` turns write tools on. Anything else leaves them off. | -| `HIVE_ADMIN_MCP_PENDING_FILE` | No | Where pending write confirmations are stored. Default on stdio: `/hive/admin-mcp-pending-confirmations.json`. Default on the HTTP endpoint: `/data/admin-mcp-pending-confirmations.json`. | +| Variable | Required | Meaning | +| ------------------------------ | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `HIVE_ADMIN_MCP_HIVES` | Yes | JSON array of `{"name","address","token"}`. All three fields are required and names must be unique. The binary exits with an error otherwise. | +| `HIVE_ADMIN_MCP_ACTIVE` | No | Name of the hive active at start. Defaults to the first entry; an unknown name is an error. | +| `HIVE_ADMIN_MCP_ENABLE_WRITES` | No | `1`, `true`, `yes` or `on` turns write tools on. Anything else leaves them off. | +| `HIVE_ADMIN_MCP_PENDING_FILE` | No | Where pending write confirmations are stored. Default on stdio: `/hive/admin-mcp-pending-confirmations.json`. Default on the HTTP endpoint: `/data/admin-mcp-pending-confirmations.json`. | -`HIVE_ADMIN_MCP_ENABLE_WRITES` and `HIVE_ADMIN_MCP_PENDING_FILE` are also read -by the dashboard process for the HTTP endpoint. +The dashboard process also reads `HIVE_ADMIN_MCP_ENABLE_WRITES` and +`HIVE_ADMIN_MCP_PENDING_FILE` for the HTTP endpoint. ## Several hives - **HTTP:** the endpoint is the scope. Add one client entry per hive. -- **Stdio:** one binary holds a roster of hives and acts on one active hive at - a time. Ask the assistant to call `select_hive` with a roster name to switch. +- **Stdio:** one binary holds a roster of hives and acts on one active hive at a + time. To switch, ask the assistant to call `select_hive` with a roster name. There is no fan-out across hives. -`select_hive` first checks the hive with `GET /api/status/summary` and only -switches if that succeeds. It tells you whether the host is unreachable, the -token is wrong, or the spoke refuses the shared token. +`select_hive` first checks the hive with `GET /api/status/summary`, and switches +only if that succeeds. If it fails, it tells you whether the host is +unreachable, the token is wrong, or the spoke refuses the shared token. Pending write confirmations are bound to the hive name they were created on. Confirming one while a different hive is active fails. @@ -204,150 +333,232 @@ Confirming one while a different hive is active fails. Read tools take an optional `limit` (default 20, maximum 50). Text results are capped at 256 KiB. -| Tool | Returns | -|------|---------| -| `hive_status` | Hive status summary | -| `fleet_status` | Fleet state; `systemResources` also carries the container's memory limit (`memLimit`, `unlimited` when none is set, with `memLimitBytes`) and out-of-memory kill count (`oomKillCount`), see [Start records, crash traces and out-of-memory evidence](#start-records-crash-traces-and-out-of-memory-evidence) | -| `version_read` | Running build from `/api/version`: `hash` and `short` (the running commit), `branch`, `channel`, `commitsBehind`, `behind`; over stdio also `stdio_build` (`version`, `sha`, `short`, `branch`) and `skew` (true when the stdio and hub short SHAs are both known and differ); over HTTP also `last_seen_stdio_build` and `last_seen_stdio_at` alongside `hub_build` | -| `agents_list` | Agents | -| `runs_list` | Runs | -| `leases_list` | Leases | -| `claims_list` | Issue claims | -| `plans_list` | Plans | -| `audit_log` | Audit entries | -| `settings_read` | A dashboard Settings view, read through the endpoint the Settings page uses, as the caller; optional `section` (default `governor`) and `agent` for the per-agent sections. See [Settings sections](#settings-sections) | -| `autonomy_readiness` | Autonomy readiness | -| `spend_read` | Spend | -| `contributors_list` | Contributors | -| `knowledge_read` | Knowledge entries | -| `hive_advisor` | Hive advice | -| `advisor_records` | Advisor records | +**Status and version** + +| Tool | Returns | +| -------------------- | ------------------------------------------------------------------------ | +| `hive_status` | Hive status summary | +| `fleet_status` | Fleet state, including memory limit and out-of-memory kills (see note 1) | +| `version_read` | Running build from `/api/version` (see note 2) | +| `autonomy_readiness` | Autonomy readiness | +| `spend_read` | Spend | + +**Agents, runs and plans** + +| Tool | Returns | +| -------------------- | --------------------------------- | +| `agents_list` | Agents | +| `runs_list` | Runs | +| `leases_list` | Leases | +| `claims_list` | Issue claims | +| `plans_list` | Plans | +| `contributors_list` | Contributors | | `agent_nudge_status` | Outcome of a nudge; needs `agent` | -| `issues_by_band` | Issues grouped by band; optional `repo`, `band`, `stale`, `held`, `offset` | -| `prs_by_band` | Pull requests grouped by band; optional `repo`, `band`, `stale`, `held`, `offset` | -| `review_queue` | The your-turn items (the dashboard inbox's N plus M), parked issues included, in `inbox_rank` order, each with its verb, reason code and reason; optional `repo`, `offset` | -| `governor_setup_proposal` | Proposed governor setup, each setting with a reason and the write operation and args that apply it | -| `log_sources` | Log sources this hive can read, each available or not with a reason; `hive` is the default, plus `proxy`, `hive-output`, `litellm` and `requests` (see [design/admin-mcp.md](design/admin-mcp.md#output-and-request-log-sources)), and `starts` and `crash` (see [below](#start-records-crash-traces-and-out-of-memory-evidence)) | -| `log_read` | The hive's own log (or another `log_sources` source), newest matching lines oldest first, scrubbed; optional `source`, `lines` (default 100, max 1000), `since`/`until` (RFC 3339 with offset), `min_level`, `include`, `exclude`, `cursor`. Needs the read-write role. Not capped by `limit`; see [design/admin-mcp.md](design/admin-mcp.md#log-read) | + +**Issues, pull requests and the Activity monitor** + +| Tool | Returns | +| --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `issues_by_band` | Issues grouped by band; optional `repo`, `band`, `stale`, `held`, `offset` | +| `prs_by_band` | Pull requests grouped by band; optional `repo`, `band`, `stale`, `held`, `offset` | +| `stage_tracker_read` | The Activity monitor (see note 3) | +| `delegated_decision_status` | Status and outcome of the latest "Let hive decide" on one item; needs `owner`, `repo`, `number` | +| `review_queue` | The your-turn items (the dashboard inbox's N plus M), parked issues included, in `inbox_rank` order, each with its verb, reason code and reason; optional `repo`, `offset` | + +**Settings, knowledge and advice** + +| Tool | Returns | +| ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `settings_read` | A dashboard Settings view, read through the endpoint the Settings page uses, as the caller; optional `section` (default `governor`) and `agent` for the per-agent sections. See [Settings sections](#settings-sections) | +| `knowledge_read` | Knowledge entries | +| `hive_advisor` | Hive advice | +| `advisor_records` | Advisor records | +| `governor_setup_proposal` | Proposed governor setup: each setting with a reason, and the write operation and args that apply it | +| `audit_log` | Audit entries | + +**Logs** + +| Tool | Returns | +| ------------- | ------------------------------------------------------------------------------------------- | +| `log_sources` | The log sources this hive can read, each marked available or not with a reason (see note 4) | +| `log_read` | The hive's own log, or another `log_sources` source (see note 5). Needs the read-write role | + +**Notes** + +1. **`fleet_status`:** `systemResources` also carries the container's memory + limit (`memLimit`, `unlimited` when none is set, with `memLimitBytes`) and + out-of-memory kill count (`oomKillCount`). See + [Start records, crash traces and out-of-memory evidence](#start-records-crash-traces-and-out-of-memory-evidence). +2. **`version_read`:** returns `hash` and `short` (the running commit), + `branch`, `channel`, `commitsBehind` and `behind`. + - Over stdio it also returns `stdio_build` (`version`, `sha`, `short`, + `branch`) and `skew` (true when the stdio and hub short SHAs are both known + and differ). + - Over HTTP it also returns `last_seen_stdio_build` and `last_seen_stdio_at` + alongside `hub_build`. +3. **`stage_tracker_read`:** returns the items with their stage, reason, what + they wait on, decision question and options, linked pull requests and issues, + blocker and hold, plus `stages[]` with a count per stage. + - Filters (all optional): `repo`, `kind`, `number`, `q` (the monitor's search + box), `stage`, `needs_human`, `on_hold`, `waiting_on_you`. + - `view` is `summary` or `full`; `recent` adds recently merged and closed + items; `offset` pages. + - Before the monitor has built its first snapshot, it answers with a + `board_unavailable` refusal rather than an empty board. Retry shortly. +4. **`log_sources`:** `hive` is the default. The others are `proxy`, + `hive-output`, `litellm` and `requests` (see + [design/admin-mcp.md](design/admin-mcp.md#output-and-request-log-sources)), + and `starts` and `crash` (see + [below](#start-records-crash-traces-and-out-of-memory-evidence)). +5. **`log_read`:** returns the newest matching lines, oldest first, scrubbed. + - Optional: `source`, `lines` (default 100, max 1000), `since`/`until` + (RFC 3339 with offset), `min_level`, `include`, `exclude`, `cursor`. + - Not capped by `limit`. See + [design/admin-mcp.md](design/admin-mcp.md#log-read). + +**Meta tools** + +- `exclusion_catalogue` lists what the admin MCP will never do, and why. +- `refuse_operation` explains the refusal for a named operation. + +Write tools (`write_preview`, `write_confirm`) are always listed. When writes +are off, or not available to the caller, their `metadata.preview.enabled` is +`false` with a note saying why, and a call is refused. On stdio, `select_hive` +is also available. ### Settings sections -`settings_read` reaches every view the Settings dialog shows. It takes a -section name, never a path. Each section is the endpoint that Settings tab -reads, so the answer matches the page for the same caller: most sections need a -verified owner, as the tabs do. Secret values are never returned. Settings name -the environment variable, file or header that supplies a secret, and the answer -is scrubbed like every other read. `settings_read` takes no `limit`: a section -is returned whole, however many agents or entries it lists, bounded only by the -256 KiB text cap. - -- Global settings: `governor` (the default: modes, thresholds, labels, repos, - budget, notifications, health, sensing, logging, security, features, hub, - LiteLLM, watchdog, trajectory, classifier, release sentinel), `project`, +`settings_read` reaches every view the Settings dialog shows. + +- It takes a section name, never a path. +- Each section is the endpoint that Settings tab reads, so the answer matches + the page for the same caller. Most sections need a verified owner, as the tabs + do. +- Secret values are never returned. Settings name the environment variable, + file or header that supplies a secret, and the answer is scrubbed like every + other read. +- It takes no `limit`. A section is returned whole, however many agents or + entries it lists, bounded only by the 256 KiB text cap. + +The sections: + +- **Global settings:** `governor` (the default: modes, thresholds, labels, + repos, budget, notifications, health, sensing, logging, security, features, + hub, LiteLLM, watchdog, trajectory, classifier, release sentinel), `project`, `github_apps`, `authorized_users`, `dashboard`, `channels`, `escalation`, - `auto_merge`, `review`, `convergence`, `sla`, `triggers`, `advisor`, `advisory`, `replan`, - `question_autoclose`, `question_autoclose_schedule`, `fleet_report`, - `work_source`, `project_observability`, `general_advanced`, `cadence_scope`, - `threshold_scaling`, `backup`, `bob`, `inference_auth`, `gateways`, - `backends`, `variables`, `write_surface`, `stat_sources`. -- Knowledge: `knowledge_pipeline`, `knowledge_connectors`, + `auto_merge`, `review`, `convergence`, `sla`, `triggers`, `advisor`, + `advisory`, `replan`, `question_autoclose`, `question_autoclose_schedule`, + `fleet_report`, `work_source`, `project_observability`, `general_advanced`, + `cadence_scope`, `threshold_scaling`, `backup`, `bob`, `inference_auth`, + `gateways`, `backends`, `variables`, `write_surface`, `stat_sources`. +- **Knowledge:** `knowledge_pipeline`, `knowledge_connectors`, `knowledge_connectors_status`, `knowledge_agent_scopes`, `knowledge_public`. -- Panels the tabs load: `upstream_watch`, `linear_agent`, `compliance_status`, - `classifier_stats`, `watchdog_activity`. -- One agent (needs `agent`): `agent`, `agent_prompt`, `agent_variables`. Prompt - history is `prompt_history_read`. - -Not reachable: the raw configuration download and the full export (they carry -credentials; `config_effective_read` is the vetted view of the effective -configuration and its provenance), an agent's export bundle (the `agent` and -`agent_prompt` sections hold it), and the theme and sidebar, which are purely -presentational. A test fails when the dashboard serves a new `GET /api/config` -route that is neither a section nor one of these exclusions. +- **Panels the tabs load:** `upstream_watch`, `linear_agent`, + `compliance_status`, `classifier_stats`, `watchdog_activity`. +- **One agent** (needs `agent`): `agent`, `agent_prompt`, `agent_variables`. + Prompt history is `prompt_history_read`. + +Not reachable: + +- the raw configuration download and the full export, because they carry + credentials (`config_effective_read` is the vetted view of the effective + configuration and its provenance); +- an agent's export bundle (the `agent` and `agent_prompt` sections hold it); +- the theme and sidebar, which are purely presentational. + +A test fails when the dashboard serves a new `GET /api/config` route that is +neither a section nor one of these exclusions. ### What a read masks -Every read result is scrubbed in two ways. Strings are scrubbed by shape: -GitHub tokens, JWTs, bearer tokens, private keys and similar are replaced -wherever they appear. Values are also masked by key: a value under a key that -contains `token`, `secret`, `password`, `credential` or `authorization` is -replaced by `[masked:...]`, unless it cannot hold a credential: +Every read result is scrubbed in two ways. -- `true` or `false`, `null`, or an empty string, list or object; -- a timestamp (`token_expires_at`); -- a token count or rate (`totalTokens`, `tokens_per_coin`); -- the self-authorization hold settings (`selfAuthorizationHold`, - `repoSelfAuthorizationHold`), which are a merge policy and not a header. +- **By shape:** GitHub tokens, JWTs, bearer tokens, private keys and similar + are replaced in any string, wherever they appear. +- **By key:** a value under a key that contains `token`, `secret`, `password`, + `credential` or `authorization` is replaced by `[masked:...]`, unless it + cannot hold a credential: + - `true` or `false`, `null`, or an empty string, list or object; + - a timestamp (`token_expires_at`); + - a token count or rate (`totalTokens`, `tokens_per_coin`); + - the self-authorization hold settings (`selfAuthorizationHold`, + `repoSelfAuthorizationHold`), which are a merge policy and not a header. The name of an environment variable under a key such as `token_env` is a string like any other there, so it is masked too when it is set. -So `[masked:token]` means a value is there and was withheld, and an empty -value means nothing is set. A list or object with content under such a key is -masked whole (for example `credentialWarnings` when there are warnings); read -it on the dashboard. The one exception is a token count block, an object under -a count key such as `tokens`: it is read like any other object, and the keys -inside it are judged by the same rules. +How to read the result: -Meta tools: - -- `exclusion_catalogue` lists what the admin MCP will never do, and why. -- `refuse_operation` explains the refusal for a named operation. - -Write tools (`write_preview`, `write_confirm`) are always listed. When writes -are off, or not available to the caller, their `metadata.preview.enabled` is -`false` with a note saying why, and a call is refused. On stdio, `select_hive` -is also available. +- `[masked:token]` means a value is there and was withheld. An empty value + means nothing is set. +- A list or object with content under such a key is masked whole (for example + `credentialWarnings` when there are warnings); read it on the dashboard. +- The one exception is a token count block, an object under a count key such + as `tokens`: it is read like any other object, and the keys inside it are + judged by the same rules. ### Diagnostic reads -These read-only tools (#11943) show what an operator would otherwise need a shell -for. They work the same over HTTP and stdio. Each one wraps a dashboard endpoint -and keeps that endpoint's role. Every result is scrubbed the way `log_read` lines -are, stays under 128 KiB, and says what it cut. The shared `limit` does not apply. -Results carry the `untrusted_content` marker. - -| Tool | Wraps | Required role | Returns | -|------|-------|---------------|---------| -| `agent_log_read` | `GET /api/agents/{name}/log` | Any authenticated role | The agent's live terminal log: the newest `max_bytes` (default 64 KiB, max 128 KiB); needs `agent`, optional `explain` (`only`/`hide`) | -| `agent_kicks_list` | `GET /api/agents/{name}/kicks` | Any authenticated role | The agent's archived kick logs, newest first; needs `agent` | -| `agent_kick_read` | `GET /api/agents/{name}/kicks/{id}` | Any authenticated role | One archived kick log, same bounds as `agent_log_read`; needs `agent`, `kick_id` | -| `run_log_read` | `GET /api/runs/{key}/log` | Read | A run's stage log, same bounds; needs `run`, optional `stage`, `gen`, `tail` | -| `run_detail_read` | `GET /api/runs/{key}/detail` | Any authenticated role (pane tails need read-write) | A run's detail; the oldest events, stages, PRs and notes and the oldest raw log bytes are dropped first; needs `run` | -| `health_deep_read` | `GET /api/health/deep` | None (public) | The deep health check, whole | -| `prompt_history_read` | `GET /api/prompt-history` | Read-write | Delivered prompts, newest first; each prompt cut at 8 KiB (`cut`, `full_bytes`); optional `agent`, `window_hours` | -| `config_effective_read` | `GET /api/diag/config` (as `/api/config/provenance`) | Owner, verified by the hive | Every configuration key and environment name, with the layer that set it; optional `offset` | - -A plain-text log comes back as `{text, content_type, truncated, bytes_total, +These read-only tools (#11943) show what an operator would otherwise need a +shell for. + +- They work the same over HTTP and stdio. +- Each one wraps a dashboard endpoint and keeps that endpoint's role. +- Every result is scrubbed the way `log_read` lines are, stays under 128 KiB, + and says what it cut. The shared `limit` does not apply. +- Results carry the `untrusted_content` marker. + +| Tool | Wraps | Required role | Returns | +| ----------------------- | ---------------------------------------------------- | --------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | +| `agent_log_read` | `GET /api/agents/{name}/log` | Any authenticated role | The agent's live terminal log: the newest `max_bytes` (default 64 KiB, max 128 KiB); needs `agent`, optional `explain` (`only`/`hide`) | +| `agent_kicks_list` | `GET /api/agents/{name}/kicks` | Any authenticated role | The agent's archived kick logs, newest first; needs `agent` | +| `agent_kick_read` | `GET /api/agents/{name}/kicks/{id}` | Any authenticated role | One archived kick log, same bounds as `agent_log_read`; needs `agent`, `kick_id` | +| `run_log_read` | `GET /api/runs/{key}/log` | Read | A run's stage log, same bounds; needs `run`, optional `stage`, `gen`, `tail` | +| `run_detail_read` | `GET /api/runs/{key}/detail` | Any authenticated role (pane tails need read-write) | A run's detail; the oldest events, stages, PRs and notes and the oldest raw log bytes are dropped first; needs `run` | +| `health_deep_read` | `GET /api/health/deep` | None (public) | The deep health check, whole | +| `prompt_history_read` | `GET /api/prompt-history` | Read-write | Delivered prompts, newest first; each prompt cut at 8 KiB (`cut`, `full_bytes`); optional `agent`, `window_hours` | +| `config_effective_read` | `GET /api/diag/config` (as `/api/config/provenance`) | Owner, verified by the hive | Every configuration key and environment name, with the layer that set it; optional `offset` | + +**Plain-text logs** come back as `{text, content_type, truncated, bytes_total, bytes_returned, max_bytes, redactions}`. The dashboard's own plain-text -responses are not changed. A refused read returns the typed forbidden error. -The error never includes the hive's response body. - -`config_effective_read` shows values only for the keys and names below. These -are known not to hold secrets. Every other key or environment variable is shown -only as set or not set. A listed value is still scrubbed. A listed URL that -holds a login is withheld. The result also includes provenance: the layer that -set each key, any lower layers it overrode (`also_set_by`), a rejected overlay -and its reason, the last-good fallback, and the GitHub ratchet. The -configuration file itself is never returned. Over HTTP, the hive must itself -have authenticated the caller as owner, with the dashboard token or a verified -owner session. An owner role claimed only in request headers is refused with -the typed forbidden error `ErrOwnerUnverified`. - -- Configuration keys: `acmm_level`, `hive_id`, `project.org`, `project.name`, - `project.repos[*]`, `project.primary_repo`, `project.ai_author`, - `project.forge`, `hub.enabled`, `hub.url`, `hub.is_public`, `hub.hive_type`, - `hub.auto_upgrade`, `hub.auto_upgrade_mode`, `github.app_id`, - `github.installation_id`, `github.app_slug`, `github.api_url`, - `github.base_url`, `governor.eval_interval_s`, `governor.logging.dir`, - `governor.logging.level`, `governor.logging.max_size_mb`, - `governor.logging.max_age_days`, `governor.logging.max_backups`, - `governor.logging.compress`, `governor.logging.kick_log_source`, - `governor.logging.read_scan_max_mb`, `agents.*.backend`, `agents.*.model`, - `agents.*.enabled`, `agents.*.paused`, and the per-repository merge policy: - `auto_merge.squash_only[*]`, `auto_merge.require_current_base[*]` and - `auto_merge.human_merge_paths.*[*]` (the path globs listed under each - `owner/repo`). A `*` segment is one map key and `[*]` any list index. -- Environment names: `HIVE_CONFIG`, `HIVE_ADMIN_MCP_ENABLE_WRITES`, +responses are not changed. + +**Refusals:** a refused read returns the typed forbidden error. The error never +includes the hive's response body. + +**`config_effective_read`:** + +- **Values shown:** only for the keys and names listed below, which are known + not to hold secrets. Every other key or environment variable is shown only as + set or not set. A listed value is still scrubbed, and a listed URL that holds + a login is withheld. +- **Provenance:** the layer that set each key, any lower layers it overrode + (`also_set_by`), a rejected overlay and its reason, the last-good fallback, + and the GitHub ratchet. +- **Never returned:** the configuration file itself. +- **Owner check:** over HTTP, the hive must itself have authenticated the caller + as owner, with the dashboard token or a verified owner session. An owner role + claimed only in request headers is refused with the typed forbidden error + `ErrOwnerUnverified`. + +The keys and names whose values are shown: + +- **Configuration keys:** `acmm_level`, `hive_id`, `project.org`, + `project.name`, `project.repos[*]`, `project.primary_repo`, + `project.ai_author`, `project.forge`, `hub.enabled`, `hub.url`, + `hub.is_public`, `hub.hive_type`, `hub.auto_upgrade`, `hub.auto_upgrade_mode`, + `github.app_id`, `github.installation_id`, `github.app_slug`, + `github.api_url`, `github.base_url`, `governor.eval_interval_s`, + `governor.logging.dir`, `governor.logging.level`, + `governor.logging.max_size_mb`, `governor.logging.max_age_days`, + `governor.logging.max_backups`, `governor.logging.compress`, + `governor.logging.kick_log_source`, `governor.logging.read_scan_max_mb`, + `agents.*.backend`, `agents.*.model`, `agents.*.enabled`, `agents.*.paused`, + and the per-repository merge policy: `auto_merge.squash_only[*]`, + `auto_merge.require_current_base[*]` and `auto_merge.human_merge_paths.*[*]` + (the path globs listed under each `owner/repo`). A `*` segment is one map key + and `[*]` any list index. +- **Environment names:** `HIVE_CONFIG`, `HIVE_ADMIN_MCP_ENABLE_WRITES`, `HIVE_ADMIN_MCP_PENDING_FILE`, `HOME`, `HOSTNAME`, `LANG`, `PATH`, `TZ`, `KUBERNETES_SERVICE_HOST`, `KUBERNETES_SERVICE_PORT` @@ -357,123 +568,156 @@ See [design/admin-mcp.md](design/admin-mcp.md#diagnostic-reads). These tell an operator with no host shell whether the hive crashed, was killed or ran out of memory (#11945). A hive whose process is down cannot be read -through the MCP at all; read the evidence after it is back. - -- **`starts` log source.** Read it with `log_read` and `source: starts`. Each - hive start writes one line: its short identifier (`start`, 8 hex characters), - its start time and how the previous run ended in `previous.verdict`: - - `clean`: it finished shutting down. - - `not-closed`: it stopped without finishing shutdown, for any reason. - Examples are SIGKILL, the out-of-memory killer, a crash or a fatal start-up - error. - - `self-upgrade-failed`: it exited after a failed self-upgrade. - - `unknown`: there is no record of a previous run. - - The line also gives `previous.last_seen_alive`, which is refreshed about every - 30 seconds. It gives `previous.memory`, the last memory and out-of-memory - reading taken before that run ended, so the count survives a container - restart that resets it. `previous.crash_trace` is set when that run left a - crash trace. Lines for `not-closed` and `self-upgrade-failed` are `WARN`, so - `min_level: warn` lists only the bad ends. A second hive process refused at - start-up records nothing. The newest 200 starts are kept. -- **Start identifier in the hive log.** Every line of the `hive` source carries - `"start":""`. Use `include` with the identifier to read one run. -- **`crash` log source.** When the hive process dies of an unrecovered panic or - a fatal Go runtime error, the runtime's trace is kept, one file per start. Each - file opens with a line naming its start. Anything after that line is the trace. - The last 10 traces are kept, each cut to at most 1 MiB. **A process killed by - SIGKILL or the out-of-memory killer leaves no trace**: it runs no code on the - way out. Its start then reads `not-closed` with no `crash_trace`. -- **`fleet_status`.** `systemResources` gains `oomKillCount`, the - out-of-memory kills counted by the container's memory controller (cgroup - `memory.events`, or `memory.oom_control` on cgroup v1). It also gains - `memLimit`, either a size such as `2048 MiB` or `unlimited`, or `unknown` - when no memory controller is readable. The existing fields, which the web UI - reads, are unchanged. A count that is missing means the controller does not - report one. - -The files live in `HIVE_OUTPUT_LOG_DIR` (default `/data/.hive/logs`). They are -`0600` in a `0700` directory owned by the hive's runtime user, so agent users -cannot read them. Nothing new is mounted, published or installed on the host. -The gateway and the container start-up script are unchanged. +through the MCP at all; read the evidence once it is back. + +**`starts` log source.** Read it with `log_read` and `source: starts`. Each hive +start writes one line, with its short identifier (`start`, 8 hex characters), +its start time, and how the previous run ended in `previous.verdict`: + +| `previous.verdict` | Meaning | +| --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | +| `clean` | It finished shutting down. | +| `not-closed` | It stopped without finishing shutdown, for any reason: for example SIGKILL, the out-of-memory killer, a crash or a fatal start-up error. | +| `self-upgrade-failed` | It exited after a failed self-upgrade. | +| `unknown` | There is no record of a previous run. | + +The line also gives: + +- `previous.last_seen_alive`, refreshed about every 30 seconds; +- `previous.memory`, the last memory and out-of-memory reading taken before that + run ended, so the count survives a container restart that resets it; +- `previous.crash_trace`, set when that run left a crash trace. + +Lines for `not-closed` and `self-upgrade-failed` are `WARN`, so +`min_level: warn` lists only the bad ends. A second hive process refused at +start-up records nothing. The newest 200 starts are kept. + +**Start identifier in the hive log.** Every line of the `hive` source carries +`"start":""`. Use `include` with the identifier to read one run. + +**`crash` log source.** When the hive process dies of an unrecovered panic or a +fatal Go runtime error, the runtime's trace is kept, one file per start. Each +file opens with a line naming its start; everything after that line is the +trace. The last 10 traces are kept, each cut to at most 1 MiB. + +**A process killed by SIGKILL or the out-of-memory killer leaves no trace**, +because it runs no code on the way out. Its start then reads `not-closed`, with +no `crash_trace`. + +**`fleet_status`.** `systemResources` gains two fields: + +- `oomKillCount`: the out-of-memory kills counted by the container's memory + controller (cgroup `memory.events`, or `memory.oom_control` on cgroup v1). A + missing count means the controller does not report one. +- `memLimit`: a size such as `2048 MiB`, or `unlimited`, or `unknown` when no + memory controller is readable. + +The existing fields, which the web UI reads, are unchanged. + +**Where the files live.** In `HIVE_OUTPUT_LOG_DIR` (default `/data/.hive/logs`). +They are `0600` in a `0700` directory owned by the hive's runtime user, so agent +users cannot read them. Nothing new is mounted, published or installed on the +host. The gateway and the container start-up script are unchanged. ### What still needs a host shell -Some evidence exists only outside the hive container. The admin MCP cannot +Some evidence exists only outside the hive container, and the admin MCP cannot read it. The table gives the closest in-container substitute. -| Host-only evidence | In-container substitute | -|---|---| -| Unit restart counts (`systemctl show hive -p NRestarts`, Quadlet) | `starts`: one line per start, with how the run before it ended | -| Container inspect (`podman inspect` / `docker inspect`: exit code, `OOMKilled`, restart count) | `starts` (`not-closed`, `self-upgrade-failed`, `previous.memory`) and `fleet_status` `systemResources.oomKillCount` / `memLimit` | -| Kubernetes describe and events (`kubectl describe pod`, `kubectl get events`: last termination reason, probe failures, scheduling) | `starts` for how each run ended, and `health_deep_read` for what the probes see. Scheduling and probe events have none | -| Node-level out-of-memory kills and evictions (kernel log, kubelet evictions) | `oomKillCount` counts kills inside the hive container only. A kill or eviction that ends the hive shows as `not-closed` in `starts`, with the last reading before it. Kills elsewhere on the node have none | -| SELinux denials (`ausearch -m avc`, the host audit log) | None. The refused operation's error may appear in the `hive` source | -| The gateway's own logs | None. `requests` shows what reached the dashboard; requests the gateway refused are not in it | -| The container start-up script's output | None for the script itself. `hive-output` keeps what the hive prints before its log is set up, and `proxy` keeps the auth proxy's output | -| The web terminal server's output | None. `agent_log_read` reads what the agent terminals show | +| Host-only evidence | In-container substitute | +| ---------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Unit restart counts (`systemctl show hive -p NRestarts`, Quadlet) | `starts`: one line per start, with how the run before it ended | +| Container inspect (`podman inspect` / `docker inspect`: exit code, `OOMKilled`, restart count) | `starts` (`not-closed`, `self-upgrade-failed`, `previous.memory`) and `fleet_status` `systemResources.oomKillCount` / `memLimit` | +| Kubernetes describe and events (`kubectl describe pod`, `kubectl get events`: last termination reason, probe failures, scheduling) | `starts` for how each run ended, and `health_deep_read` for what the probes see. Scheduling and probe events have none | +| Node-level out-of-memory kills and evictions (kernel log, kubelet evictions) | `oomKillCount` counts kills inside the hive container only. A kill or eviction that ends the hive shows as `not-closed` in `starts`, with the last reading before it. Kills elsewhere on the node have none | +| SELinux denials (`ausearch -m avc`, the host audit log) | None. The refused operation's error may appear in the `hive` source | +| The gateway's own logs | None. `requests` shows what reached the dashboard; requests the gateway refused are not in it | +| The container start-up script's output | None for the script itself. `hive-output` keeps what the hive prints before its log is set up, and `proxy` keeps the auth proxy's output | +| The web terminal server's output | None. `agent_log_read` reads what the agent terminals show | **The role gate does not limit dashboard-token holders.** Whoever holds the -dashboard token is the owner, and every read and write role check passes for -an owner. Treat the token as owner access to all of the evidence above. +dashboard token is the owner, and every read and write role check passes for an +owner. Treat the token as owner access to all of the evidence above. ## Writes Writes are off unless `HIVE_ADMIN_MCP_ENABLE_WRITES` is set on the process that -serves the MCP. They take two steps: - -1. `write_preview` with `operation` and `args`. Nothing changes. You get a - `confirmation_id`, an expiry and a description of what would happen. -2. `write_confirm` with the `confirmation_id`. The confirmation is single-use - and expires after 10 minutes. - -Registered operations: - -- `agent.pause`, `agent.resume`, `agent.nudge`, `agent.restart`, `agent.add`, - `agent.remove`, `agent.model`, `agent.backend`, `agent.effort`, - `agent.interaction_tier` -- `fleet.autonomy_level` -- `plan.propose`, `plan.approve`, `plan.reject` -- `governor.feature_settings`, `governor.thresholds`, - `governor.threshold_scaling` -- `repository.pause`, `repository.resume`, `repository.item_hold` -- `budget.update`, `budget.reset`, `budget.ignore` -- `contributor.trust`, `contributor.agent_role`, - `contributor.agent_role_grants`, `contributor.revoke`, - `contributor.requeue`, `contributor.delete` -- `backup.create` (the archive itself is not returned through MCP) -- `circuit_breaker.engage`, `circuit_breaker.release` - -Anything not on this list is refused; the assistant must not approximate it by +serves the MCP. Writes are also unavailable to a caller whose role on the hive +is read-only. + +Every write takes two steps: + +1. **`write_preview`** with `operation` and `args`. Nothing changes. You get a + `confirmation_id`, an expiry, and a description of what would happen. +2. **`write_confirm`** with the `confirmation_id`. The confirmation is + single-use and expires after 10 minutes. Only the caller who previewed a + write can confirm it. + +### Who a write runs as + +A confirmed write runs as you. + +- **On the HTTP endpoint**, that is the identity the hive verified on your + request: your login when you come through a dashboard session or the hub, at + your role on that hive. The endpoint's own permission checks apply to you, and + the audit log and any comment the write leaves name you. +- **Your own rights are the limit.** An operation can do no more than the same + button on the dashboard would let you do. For example, approving a pull + request or deciding an item needs write access to that repository, checked + against your own GitHub permission: with read access the approve is refused + and nothing is written. A read-only role on the hive cannot write at all. +- **With the dashboard token** (the stdio binary, or an HTTP client sending the + dashboard token), writes are recorded as the configured owner's login when + `dashboard.authorized_users` names an owner, and as `owner` otherwise. + +The audit log cannot tell an assistant-mediated write from a dashboard action. + +### Registered operations + +| Area | Operations | +| ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Agents | `agent.pause`, `agent.resume`, `agent.nudge`, `agent.restart`, `agent.add`, `agent.remove`, `agent.model`, `agent.backend`, `agent.effort`, `agent.interaction_tier` | +| Fleet | `fleet.autonomy_level` | +| Plans | `plan.propose`, `plan.approve`, `plan.reject` | +| Governor | `governor.feature_settings`, `governor.thresholds`, `governor.threshold_scaling` | +| Repositories | `repository.pause`, `repository.resume`, `repository.item_hold` | +| Activity monitor row actions | see below | +| Budget | `budget.update`, `budget.reset`, `budget.ignore` | +| Contributors | `contributor.trust`, `contributor.agent_role`, `contributor.agent_role_grants`, `contributor.revoke`, `contributor.requeue`, `contributor.delete` | +| Backup | `backup.create` (the archive itself is not returned through MCP) | +| Circuit breaker | `circuit_breaker.engage`, `circuit_breaker.release` | + +The Activity monitor's row actions: + +| Operation | Button | +| --------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | +| `repository.rescan` | Re-evaluate now | +| `repository.item_accept_triage` | Accept triage | +| `repository.item_needs_human` | Mark needs-human | +| `repository.item_blocker_recheck` | Re-check permissions | +| `repository.item_blocker_handoff` | Hand to workflows lane | +| `repository.item_blocker_close_partial` | Mark partially-addressed and close | +| `repository.item_decision` | Decide: approve, direction, close-superseded, close-wontfix, close-read, close-issue, adopt, adopt-now, re-author, reroute | +| `repository.item_delegate` | Let hive decide; read the outcome with `delegated_decision_status` | + +The merge answers are not available, and a delegated decision made here never +queues an auto-merge. + +Anything not listed is refused. The assistant must not approximate it by combining other operations. -Every write is recorded in the audit log as the configured owner's login when -`dashboard.authorized_users` names an owner, and as `owner` otherwise, whoever -confirmed it. The audit log cannot tell an assistant-mediated write from a -dashboard action. - -Confirmed writes re-authenticate with your `Authorization: Bearer` token. A -caller admitted another way (dashboard session, hub proxy, internal header) -can preview but not confirm, so on the HTTP endpoint writes are reported -unavailable for that caller. Writes are likewise unavailable on a spoke that -enforces per-user direct-route authorization. - ## Troubleshooting -- **401 on `write_confirm` after a successful preview.** The request was - admitted without the bearer token (session, hub proxy or internal header). - Connect with the dashboard token in the `Authorization` header. -- **Write tools missing, or "writes unavailable".** Set - `HIVE_ADMIN_MCP_ENABLE_WRITES=1` on the serving process, or read the reason - returned by `exclusion_catalogue`: a per-user direct-route spoke, or a caller - not using the bearer token. -- **`select_hive` fails.** "unreachable host": check the address and network. - "wrong dashboard token": the roster token does not match that hive. "direct-route - spoke refused shared token": that spoke needs per-user access and cannot be - administered with a token. -- **405 on the HTTP endpoint.** You sent a GET; use POST. -- **Confirmation expired or wrong hive.** Run `write_preview` again on the hive - you want to change. +| Symptom | Cause and fix | +| -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| "confirmation was previewed by another caller" | Only the caller who ran `write_preview` can confirm it. Preview the write again yourself. | +| A write is refused, or `metadata.preview.enabled` is `false` | Read the note on the write tools, or the reason `exclusion_catalogue` returns. Set `HIVE_ADMIN_MCP_ENABLE_WRITES=1` on the serving process; otherwise the caller has a read-only role on this hive, or the request carries no verified identity. | +| `select_hive` fails: "unreachable host" | Check the address and network. | +| `select_hive` fails: "wrong dashboard token" | The roster token does not match that hive. | +| `select_hive` fails: "direct-route spoke refused shared token" | That spoke needs per-user access and cannot be administered with a token. | +| 401 or 403 from a hive hosted by the hub | The GitHub token is invalid or expired, or your login has no role on that hive. Check the token with `curl -sH "Authorization: Bearer " https://api.github.com/user`, and ask the hive's owner for access. | +| 405 on the HTTP endpoint | You sent a GET; use POST. | +| Confirmation expired, or wrong hive | Run `write_preview` again on the hive you want to change. | For the design record behind this feature, see [`design/admin-mcp.md`](design/admin-mcp.md). diff --git a/src/docs/design/admin-mcp.md b/src/docs/design/admin-mcp.md index 06bb90def3..9365f2f9e6 100644 --- a/src/docs/design/admin-mcp.md +++ b/src/docs/design/admin-mcp.md @@ -91,9 +91,11 @@ Phase 3 adds the reusable contract that phases 4–6 extend. The MCP exposes two Writes are disabled by default on both transports. Set `HIVE_ADMIN_MCP_ENABLE_WRITES=1` to enable them. Pending confirmations are durable: the dashboard endpoint stores them in `/data/admin-mcp-pending-confirmations.json` by default, and the stdio binary stores them under the user's config directory; both support `HIVE_ADMIN_MCP_PENDING_FILE` as an explicit path. The confirmation is not a capability for any other action: it is action-bound, hive-bound, one-use, and time-limited. -The write contract deliberately goes through existing dashboard REST endpoints and sends only the dashboard token. It never sends `X-Hive-User`, `X-Hive-Role`, or `X-Hive-Owner-Role-Verified`. A hive refusal from the underlying endpoint is returned as a `hive-refusal` result with the status and original response body preserved rather than rewritten as a client-side authorization decision. Audit attribution therefore falls back to the token-authenticated owner identity (the configured owner's login, or `owner`), as recorded below. +The write contract deliberately goes through existing dashboard REST endpoints. A client never sends `X-Hive-User`, `X-Hive-Role`, or `X-Hive-Owner-Role-Verified`. A hive refusal from the underlying endpoint is returned as a `hive-refusal` result with the status and original response body preserved rather than rewritten as a client-side authorization decision. -Because a confirmed write re-authenticates with the dashboard token alone, the endpoint checks up front whether that can succeed for the current caller. When the dashboard enforces authentication and the caller was admitted some other way (a per-user session, hub proxy proof, or the internal header) rather than with `Authorization: Bearer `, or when the spoke enforces direct-route authorization (which refuses the shared token), writes are reported as unavailable for that caller: `tools/list` and `exclusion_catalogue` show `writes_enabled: false` with the reason (`writes_unavailable_reason` in the catalogue), and `write_preview` refuses without minting a confirmation that could never execute. +**A confirmed write runs as the caller the hive verified.** The stdio binary sends the dashboard token, so its writes run as the token-authenticated owner identity (the configured owner's login, or `owner`), as recorded below. The dashboard endpoint serves the confirm in-process: `authenticate` has already verified the caller of the `/api/admin/mcp` request (dashboard token, per-user session, hub proxy proof or the internal header) and stripped any identity the client asserted, so the write runs under that verified user, role and verified-owner marker — the same ones the read tools already carry — without re-entering `authenticate`. A hub-proxied or session caller can therefore write; every role check (`canToggleRepoHold`, `requireOwnerRole`, `requireMergerOrOwnerRole`) sees that caller; and the write is attributed to them. A pending confirmation records the actor that previewed it, and `write_confirm` from any other actor is refused with the confirmation put back unused, so a write runs as the person who saw its preview. + +The endpoint still checks up front whether a write can succeed for the current caller. A caller whose role is `read`, or a request carrying no verified identity on a hive that enforces authentication, is reported as unable to write: `tools/list` and `exclusion_catalogue` show `writes_enabled: false` with the reason (`writes_unavailable_reason` in the catalogue), and `write_preview` refuses without minting a confirmation that could never execute. ### Configuring the stdio binary @@ -146,7 +148,10 @@ Two corollaries the client must honour: - It must never send `X-Hive-User`, `X-Hive-Role`, or `X-Hive-Owner-Role-Verified`. `authenticate` strips inbound copies of all three before auth precisely because they are - forgeable, so sending them cannot grant anything and marks the client as suspect. + forgeable, so sending them cannot grant anything and marks the client as suspect. This binds + the client. The dashboard endpoint itself runs a confirmed write as the identity + `authenticate` verified on the request (see the write contract above), which is not a + client assertion. - The token goes in the `Authorization` header only. A `?token=` query parameter is rejected outright by `writeQueryTokenRejected`. @@ -160,7 +165,8 @@ A token-bearing admin client therefore **cannot administer a direct-route spoke That is correct behaviour on Hive's side and a hard limit on the client's applicability, not a gap to work around. The client is expected to detect it at connect time and say so, distinguishing it from a merely wrong token. `hivectl` has the same limitation for the same -reason. +reason. The dashboard endpoint reached with a per-user session is not token-bearing: it reads +and writes as that signed-in user, at their allowlist role. ### Mode ladder — not a check, but the thing most worth previewing @@ -384,6 +390,25 @@ read and to retry, rather than answer from mixed snapshots. A hive that predates reports none on either export, which never counts as a mismatch. The same `adminmcp.ReadReviewQueue` serves the dashboard endpoint and the stdio server. +**`stage_tracker_read`** answers "what is on the Activity monitor?": it reads +`GET /api/stage-tracker`, the payload the dashboard's Activity monitor draws, and returns the +items with `stages[]` (number, slug, label, dwell, and how many items sit at each now) and the +board's counts (`open_issues`, `open_prs`, `needs_human`, `on_hold`, `waiting_on_human`). +Filters are applied in `pkg/adminmcp` after the read, so the stage counts always describe the +whole board: `repo`, `kind`, `number` (the item itself), `q` (the monitor's search box — a +number matches the item or a linked pull request or issue by number, other text matches +titles, as `tracker-filter.js` does), `stage`, `needs_human`, `on_hold` and `waiting_on_you`. +`view=summary` (the default) keeps the fields a row shows — stage, reason and caption, wait +kind, decision question and options, linked items, blocker, hold, Sentinel state, merge gate, +last operator action; `view=full` keeps every field, history and activity strips included. +`recent=true` adds `recently_merged` and `recently_closed`, capped by `limit`. Pages are +`limit` items from `offset`, with `next_offset` and `_admin_mcp.total` on a capped page. Before +the board's first snapshot the endpoint answers `{"status":"initializing"}`, and the tool +returns a `board_unavailable` refusal instead of an empty board; an item preview that cannot +read the board says so (`on_board: "unknown"`) rather than reporting the item as absent. +**`delegated_decision_status`** reads `GET .../items/{number}/decide-delegated`, the job a +"Let hive decide" starts, so the outcome of `repository.item_delegate` can be read back. + **`governor_setup_proposal`** (hive#10034) answers "set up these governors for me" for a new hive. It reads `GET /api/config/governor`, which already carries the repo count, cadence scope, scaling curve, effective and operator-pinned thresholds and budget, and returns one @@ -511,6 +536,12 @@ start-up script, its process launch, PIDs, signal handling and exit codes are un | feature settings | `PUT /api/config/governor/features` | `requireOwnerRole`; pointer fields, nil means unchanged | | repository pause / resume | `POST /api/repos/pause`, `/api/repos/resume` | `requireRepoPausePermission` → `canToggleRepoHold` | | item hold | `POST /api/repos/{owner}/{repo}/items/{number}/hold` | `canToggleRepoHold` | +| re-evaluate now | `POST /api/repos/rescan` | none beyond write access | +| accept triage | `POST /api/repos/{owner}/{repo}/items/{number}/accept-triage` | `canToggleRepoHold` | +| mark needs-human | `POST /api/review/pipeline/{owner}/{repo}/{number}/send-to-human` | `requireMergerOrOwnerRole`; needs a user | +| blocker re-check / hand-off / partial close | `POST /api/repos/{owner}/{repo}/items/{number}/blocker/{recheck,handoff,close-partial}` | `canToggleRepoHold`; needs a user | +| decide | `POST /api/repos/{owner}/{repo}/items/{number}/decision` | `canToggleRepoHold`; needs a user; `merge-now` / `queue-merge` refused client-side | +| let hive decide | `POST /api/repos/{owner}/{repo}/items/{number}/decide-delegated` → `GET` same path (`delegated_decision_status`) | `delegateDecisionEnabled`, `canToggleRepoHold`; needs a user; always `no_merge` | | spend | `PUT /api/config/governor/budget`, `POST /api/config/governor/budget/reset`, `POST /api/budget-ignore` | `requireOwnerRole` | | contributors | `PUT /api/contributors/{id}/trust`, `PUT /api/contributors/{id}/agent-role`, `PUT /api/contributors/{id}/agent-role-grants`, `POST /api/contributors/{id}/revoke`, `/requeue`, `DELETE /api/contributors/{id}` | `requireOwnerRole` except `/requeue`, which remains `requireContributorWrite` | | backup | `POST /api/backup` | `requireOwnerRole` | @@ -591,6 +622,33 @@ Phase 5 registers the fleet-level write operations under that contract: shallower queue, which raises agent cadence and spend — because the number alone does not tell an owner what it buys. +The Activity monitor's row actions are registered as the `repository.rescan` and +`repository.item_*` operations, each sending the request the dashboard's button sends +(`stageTrackerActionRequest` in `tracker-actions.js`): + +- `repository.rescan` ("Re-evaluate now"), `repository.item_accept_triage`, + `repository.item_needs_human` (a reason is required), + `repository.item_blocker_recheck`, `repository.item_blocker_handoff` and + `repository.item_blocker_close_partial`. Item hold is the existing + `repository.item_hold`. +- `repository.item_decision` is the Decide menu: `approve`, `direction` (needs the text), + `close-superseded`, `close-wontfix`, `close-read`, `close-issue`, `adopt`, `adopt-now` + (`adopt` with `force`), `re-author` and `reroute` (`to`, default `any`). The merge answers + `merge-now` and `queue-merge` are refused before any request; see the exclusions below. +- `repository.item_delegate` is "Let hive decide", with `prs` for an issue's nested pull + requests and `rerun` for a stuck decision. It always sends `no_merge`, which makes the + handler decide without the merger role: an approval the decider reaches is the + `/lgtm` + `/approve` path, never an Approve review queued for auto-merge. Without it, a + merger's delegated approval would be the excluded queue-automerge reached another way. The + job runs in the background; `delegated_decision_status` reads its outcome. + +Each item preview reads the item off the Activity monitor first and shows its kind, stage, +reason and decision question, so the confirm is against the state an operator would have +seen; an item not on the board is said to be so. The item kind (`type`) comes from the board +when the caller omits it. Decide, Let hive decide, the blocker actions and needs-human are +recorded as a person's decision, which is why they need the verified caller described in the +write contract: through the token path they would be recorded under the configured owner. + ### Diagnostic reads hivecommons/hive#11943 (child of #11941) adds read tools for the per-agent, per-run, health, @@ -745,6 +803,11 @@ explicitly not to. capability change previews as "these agents gain this authority", whereas this is "this pull request, merged, now". Worth revisiting if a preview can be made to show the diff and the checks being merged. +- **POST /api/repos/{owner}/{repo}/items/{number}/decision with merge-now or queue-merge.** + The Activity monitor's "Merge now as maintainer" and "Approve and let hive merge" answers are + the queue-automerge exclusion in another form: one merges at once, the other queues the + merge. repository.item_decision refuses both, and repository.item_delegate sends no_merge so + a delegated approval never queues one either. - **`PUT /api/config/agent/{name}/prompt`.** The kick hazard made permanent. Kick text reaches the CLI once and is confirmed verbatim for that reason; a prompt reaches it on *every* future kick, and Hive does not scan that path either. Verbatim confirmation is a reasonable @@ -783,6 +846,12 @@ explicitly not to. ## Known gap: attribution +**Narrowed for the dashboard endpoint.** A confirmed write over the HTTP endpoint now runs as +the caller the hive verified (see the write contract), so a session or hub-proxied caller's +write is audited under their own login. What follows still holds for the dashboard token — +the stdio binary, and an HTTP client that authenticates with the token — whose writes are +the token holder's by definition. + `requestUser` resolves the acting user from `X-Hive-User`, falling back to `"local"` only when that header is empty. The bearer-token middleware fills the header with the owner identity (`verifiedOwnerUser`), so a token-authenticated write never reaches that fallback. Because this diff --git a/src/pkg/adminmcp/adminmcp.go b/src/pkg/adminmcp/adminmcp.go index bb1c762364..4351b0f28f 100644 --- a/src/pkg/adminmcp/adminmcp.go +++ b/src/pkg/adminmcp/adminmcp.go @@ -109,6 +109,7 @@ var exclusions = []Exclusion{ {Operation: "POST /api/contribute/invite", Kind: RefusalKindMechanical, Reason: "`handleContributeInvite` resolves the caller's identity server-side via `resolveViewerUsername` and requires *that user's* contributor profile to hold a `trusted`, `merger` or `advisor` tier. Authority here is derived from who the caller is, not from the owner role, and there is no owner override. A credential carrying no personal identity gets 401.", WhatWouldNeedToChange: "Add an owner-authorized invite path that does not depend on per-user contributor identity."}, {Operation: "fan-out across hives", Kind: RefusalKindMechanical, Reason: "Exactly one hive is active at a time by design, so an all-hives mode would contradict the surface rather than extend it.", WhatWouldNeedToChange: "Replace the single-active-hive model with an explicit multi-hive design."}, {Operation: "POST /api/prs/{owner}/{repo}/{number}/queue-automerge", Kind: RefusalKindCategorical, Reason: "The only available action that directly causes a merge into real code, and the one a preview cannot meaningfully soften.", DoNotApproximate: doNotApproximate, Tracker: judgementTracker}, + {Operation: "POST /api/repos/{owner}/{repo}/items/{number}/decision with merge-now or queue-merge", Kind: RefusalKindCategorical, Reason: "The Activity monitor's \"Merge now as maintainer\" and \"Approve and let hive merge\" answers are the queue-automerge exclusion in another form: one merges at once, the other queues the merge. repository.item_decision refuses both, and repository.item_delegate sends no_merge so a delegated approval never queues one either.", DoNotApproximate: doNotApproximate, Tracker: judgementTracker}, {Operation: "PUT /api/config/agent/{name}/prompt", Kind: RefusalKindCategorical, Reason: "Kick text reaches the CLI once and is confirmed verbatim for that reason. A prompt reaches it on *every* future kick, and Hive does not scan that path either. Verbatim confirmation is a reasonable guard for one string and a weak one for a standing instruction.", DoNotApproximate: doNotApproximate, Tracker: judgementTracker}, {Operation: "POST /api/release-channel", Kind: RefusalKindCategorical, Reason: "Changes which code the hive runs at its next upgrade. The effect is deferred and invisible at the moment of the change, so a preview can say nothing useful about it.", DoNotApproximate: doNotApproximate, Tracker: judgementTracker}, {Operation: "knowledge writes", Kind: RefusalKindCategorical, Reason: "Agents read knowledge when they are handed work, so a write changes fleet behaviour with nothing in any fleet or agent view showing that it happened. Knowledge **reads** are in scope.", DoNotApproximate: doNotApproximate, Tracker: judgementTracker}, @@ -157,6 +158,10 @@ type Handler struct { // not authenticate. Preview fails fast instead of minting a confirmation // that can never be executed. WritesUnavailableReason string + // Actor is the caller the hive verified on this request. A confirmation + // records the actor that previewed it and only that actor may confirm + // it, so a write runs as the person who saw its preview. + Actor string } type HandlerOption func(*Handler) @@ -180,6 +185,9 @@ func WithConfirmationTTL(ttl time.Duration) HandlerOption { return func(h *Handler) { h.ConfirmationTTL = ttl } } func WithClock(now func() time.Time) HandlerOption { return func(h *Handler) { h.Now = now } } +func WithActor(actor string) HandlerOption { + return func(h *Handler) { h.Actor = strings.TrimSpace(actor) } +} func WithWritesUnavailable(reason string) HandlerOption { return func(h *Handler) { h.WritesUnavailableReason = strings.TrimSpace(reason) } } @@ -366,6 +374,8 @@ func toolDefs(writesEnabled bool, unavailableReason string) []map[string]any { {ToolAgentNudgeStatus, "Read the asynchronous delivery outcome for the latest nudge sent to one agent."}, {ToolIssuesByBand, "Read issues grouped by their Overview band (ready, in-progress, agent-filed, waiting, done), e.g. band=done for issues an agent has labelled hive/already-done, hive/covered-by-pr or hive/likely-done that a human has not verified and closed yet. hive/covered-by-pr only means an agent found an open PR that references the issue — check that the PR merged before closing."}, {ToolPrsByBand, "Read PRs grouped by their Overview band (waiting, eligible, blocked, in-review, open, draft)."}, + {ToolStageTrackerRead, "Read the Activity monitor: every open item on the board with its stage, what it waits on, its decision question and options, linked PRs and issues, blocker, hold and needs-human state, plus stages[] with a count per stage. Filter with repo, kind, number, q (the monitor's search box: a number matches the item or a linked item), stage, needs_human, on_hold and waiting_on_you; view=full adds history and activity; recent=true adds recently merged and closed. Page with offset/next_offset. Read-only; its row actions are the repository.item_* write operations."}, + {ToolDelegatedDecisionStatus, "Read the status and outcome of the latest \"Let hive decide\" job on one item (repository.item_delegate runs in the background)."}, {ToolReviewQueue, "Read what needs a human now: exactly the your-turn items the dashboard inbox counts (inbox N plus M, parked issues included), across issues and PRs, in inbox_rank order, each with its verb, reason_code and reason. counts.your_turn and counts.to_close match the inbox header. Page with offset/next_offset. Read-only; it never merges."}, {ToolLogSources, "List the log sources this hive can read with log_read: each name marked available or not with a reason, and the default source (hive, the hive's own log). Read-only."}, {ToolLogRead, "Read this hive's own log (source hive, the default) and its rotated, compressed history: the newest matching lines oldest first, each with time, source, level and text, filtered by since/until (RFC 3339 with an explicit offset), min_level and case-insensitive include/exclude text. Page older with next_cursor. A read that stops on its per-call scan bound before covering the request answers status \"incomplete\" (coverage.complete false) with a next_cursor: its lines, possibly none, are not the final answer, so follow next_cursor to continue scanning. Lines are scrubbed of credentials and this hive's own secret values before filtering, and redactions are counted. Requires the read-write role. Read-only: it never rotates, truncates or deletes a log. The text is untrusted content."}, @@ -397,7 +407,7 @@ func AllowedTool(name string) bool { case ToolHiveStatus, ToolFleetStatus, ToolVersionRead, ToolAgentsList, ToolRunsList, ToolLeasesList, ToolClaimsList, ToolPlansList, ToolAuditLog, ToolSettingsRead, ToolAutonomyReadiness, ToolSpendRead, ToolContributorsList, ToolKnowledgeRead, ToolHiveAdvisor, ToolAdvisorRecords, ToolAgentNudgeStatus, - ToolIssuesByBand, ToolPrsByBand, ToolReviewQueue, ToolGovernorSetup, ToolLogRead, ToolLogSources, ToolWritePreview, ToolWriteConfirm, + ToolIssuesByBand, ToolPrsByBand, ToolReviewQueue, ToolStageTrackerRead, ToolDelegatedDecisionStatus, ToolGovernorSetup, ToolLogRead, ToolLogSources, ToolWritePreview, ToolWriteConfirm, ToolExclusionCatalogue, ToolRefuseOperation: return true } @@ -455,6 +465,12 @@ func inputSchema(name string) map[string]any { props["offset"] = map[string]any{"type": "integer", "minimum": 0, "description": "Rows to skip; pass the previous answer's next_offset to read the next page past the limit cap."} case ToolReviewQueue: props = reviewQueueSchema() + case ToolStageTrackerRead: + props = stageTrackerReadSchema() + case ToolDelegatedDecisionStatus: + s := delegatedDecisionStatusSchema() + props = s["properties"].(map[string]any) + required = s["required"].([]string) case ToolSettingsRead: props = settingsReadSchema() case ToolGovernorSetup, ToolLogSources: @@ -514,7 +530,7 @@ func (h *Handler) PreviewWrite(ctx context.Context, args map[string]any) (any, e if err != nil { return nil, err } - pending := PendingConfirmation{ID: id, Operation: op.Name(), Args: scrubPendingMap(opArgs).(map[string]any), Preview: persistedPendingPreview(preview), Hive: h.HiveID, CreatedAt: now, ExpiresAt: now.Add(h.ConfirmationTTL)} + pending := PendingConfirmation{ID: id, Operation: op.Name(), Args: scrubPendingMap(opArgs).(map[string]any), Preview: persistedPendingPreview(preview), Hive: h.HiveID, Actor: h.Actor, CreatedAt: now, ExpiresAt: now.Add(h.ConfirmationTTL)} if err := h.PendingStore.Put(ctx, pending); err != nil { return nil, err } @@ -532,6 +548,17 @@ func (h *Handler) ConfirmWrite(ctx context.Context, args map[string]any) (any, e if id == "" { return nil, fmt.Errorf("confirmation_id is required") } + // Refuse another caller's confirmation before taking it, so a mismatched + // confirm can neither burn it nor race its owner's confirm. + listed, err := h.PendingStore.List(ctx) + if err != nil { + return nil, err + } + for _, p := range listed { + if p.ID == id && p.Actor != h.Actor { + return nil, ErrConfirmationActor + } + } pending, err := h.PendingStore.Take(ctx, id) if err != nil { return nil, err @@ -539,6 +566,11 @@ func (h *Handler) ConfirmWrite(ctx context.Context, args map[string]any) (any, e if pending.Hive != h.HiveID { return nil, fmt.Errorf("confirmation belongs to hive %q, not %q", pending.Hive, h.HiveID) } + if pending.Actor != h.Actor { + // Unreachable unless the store changed between List and Take; the + // actor never changes, so a confirmation taken here was never ours. + return nil, ErrConfirmationActor + } if !h.now().Before(pending.ExpiresAt) { return nil, ErrConfirmationExpired } diff --git a/src/pkg/adminmcp/tools_agent_ops.go b/src/pkg/adminmcp/tools_agent_ops.go index 8d5b6e81a8..6aab9292a0 100644 --- a/src/pkg/adminmcp/tools_agent_ops.go +++ b/src/pkg/adminmcp/tools_agent_ops.go @@ -30,6 +30,7 @@ func DefaultWriteOps() []WriteOp { } ops := append(agentOps, repoOpsWriteOps()...) ops = append(ops, fleetWriteOps()...) + ops = append(ops, stageTrackerWriteOps()...) return append(ops, governorWriteOps()...) } diff --git a/src/pkg/adminmcp/tools_stage_tracker.go b/src/pkg/adminmcp/tools_stage_tracker.go new file mode 100644 index 0000000000..6b092ea5d2 --- /dev/null +++ b/src/pkg/adminmcp/tools_stage_tracker.go @@ -0,0 +1,684 @@ +package adminmcp + +import ( + "context" + "fmt" + "net/http" + "net/url" + "slices" + "sort" + "strconv" + "strings" +) + +// The Activity monitor over admin MCP: stage_tracker_read reads the board the +// dashboard's Activity monitor draws (GET /api/stage-tracker), and the +// repository.item_* write ops are the monitor's row actions, each the same +// request the dashboard's button sends (tracker-actions.js +// stageTrackerActionRequest). The merge actions ("Approve and let hive merge", +// "Merge now as maintainer") are not offered: they are the queue-automerge +// exclusion in another form. +const ( + ToolStageTrackerRead = "stage_tracker_read" + ToolDelegatedDecisionStatus = "delegated_decision_status" + stageTrackerViewSummary = "summary" + stageTrackerViewFull = "full" + stageTrackerPath = "/api/stage-tracker" + stageTrackerDecisionMaxNotes = 4000 + + // RefusalKindBoardUnavailable is stage_tracker_read's answer while the + // Activity monitor has no snapshot to read. + RefusalKindBoardUnavailable = "board_unavailable" + + WriteOpRepositoryRescan = "repository.rescan" + WriteOpRepositoryItemAcceptTriage = "repository.item_accept_triage" + WriteOpRepositoryItemNeedsHuman = "repository.item_needs_human" + WriteOpRepositoryItemBlockerRecheck = "repository.item_blocker_recheck" + WriteOpRepositoryItemBlockerHandoff = "repository.item_blocker_handoff" + WriteOpRepositoryItemBlockerClosePart = "repository.item_blocker_close_partial" + WriteOpRepositoryItemDecision = "repository.item_decision" + WriteOpRepositoryItemDelegate = "repository.item_delegate" +) + +// stageTrackerSummaryKeys are the fields a summary row keeps: what the +// monitor's row shows (stage, wait, decision, links, blocker) without the +// activity strips, history and Sentinel detail. view=full keeps every field. +var stageTrackerSummaryKeys = []string{ + "repo", "number", "kind", "title", "url", "author", "author_kind", + "stage", "stage_slug", "stage_label", "stage_since", "reason", "caption", + "lane", "actor", "finisher", "finisher_reason", "claimant", "modifiers", "labels", + "needs_human", "on_hold", "hold", "waiting_on_you", "wait_kind", "human_attention", + "blocked_on", "blocked_on_pr", "blocker", "decision_needed", + "linked_prs", "linked_issues", "nested_under", "superseded_by", + "sentinel_alert", "sentinel_reason", "merge_gate", "soak_remaining_seconds", + "regressed_from", "regressed_to", "regressed_reason", + "last_operator_action", "decided", "updated_at", +} + +// stageTrackerDecisions are the Decide answers repository.item_decision +// sends, mapped to the dashboard's request. merge-now and queue-merge are +// absent on purpose. +var stageTrackerDecisions = []string{ + "approve", "direction", "close-superseded", "close-wontfix", "close-read", + "close-issue", "adopt", "adopt-now", "re-author", "reroute", +} + +var stageTrackerMergeDecisions = []string{"merge-now", "queue-merge"} + +func stageTrackerReadSchema() map[string]any { + return map[string]any{ + "limit": limitSchema(), + "offset": map[string]any{"type": "integer", "minimum": 0, "description": "Items to skip; pass the previous answer's next_offset to read the next page."}, + "repo": map[string]any{"type": "string", "description": "owner/name; unset reads every repo on the board."}, + "kind": map[string]any{"type": "string", "enum": []string{"issue", "pr"}}, + "number": map[string]any{"type": "integer", "minimum": 1, "description": "Only the item with this number (pair with repo when several repos share it)."}, + "q": map[string]any{"type": "string", "description": "The Activity monitor's search box: a number (\"488\" or \"#488\") matches the item or a linked PR or issue with that number; other text matches titles."}, + "stage": map[string]any{"type": "integer", "minimum": 0, "description": "Only items at this stage number (stages[] lists them)."}, + "needs_human": map[string]any{"type": "boolean"}, + "on_hold": map[string]any{"type": "boolean"}, + "waiting_on_you": map[string]any{"type": "boolean", "description": "Items parked on the operator or maintainers (a decision, a human merge, an approval), as the monitor's \"waiting on you\" view; wait_kind says which."}, + "view": map[string]any{"type": "string", "enum": []string{stageTrackerViewSummary, stageTrackerViewFull}, "description": "summary (default) keeps the row's fields; full keeps every field, history and activity included."}, + "recent": map[string]any{"type": "boolean", "description": "Also return recently_merged and recently_closed, capped by limit."}, + } +} + +func delegatedDecisionStatusSchema() map[string]any { + return itemTargetProps() +} + +// StageTrackerReadPath is the request stage_tracker_read makes. Filters are +// applied by StageTrackerReadResult so the stage counts always describe the +// whole board. +func StageTrackerReadPath() string { return stageTrackerPath } + +// DelegatedDecisionStatusPath is the GET a "Let hive decide" job is polled at. +func DelegatedDecisionStatusPath(args map[string]any) (string, error) { + owner, repo, number, err := itemTargetArgs(args) + if err != nil { + return "", err + } + return itemPath(owner, repo, number, "decide-delegated"), nil +} + +// StageTrackerReadResult filters, trims and pages a decoded GET +// /api/stage-tracker answer for stage_tracker_read. +func StageTrackerReadResult(data any, args map[string]any) (any, error) { + refuse := func(reason string) (any, error) { + return RefusalData{Type: "refusal", Operation: ToolStageTrackerRead, Kind: RefusalKindInvalidArgument, Reason: reason}, nil + } + body, ok := data.(map[string]any) + if !ok { + return CapResult(data, LimitFromArgs(args)), nil + } + // Before its first snapshot the endpoint answers {"status":"initializing"} + // with no items: that is "not built yet", never an empty board. + if _, hasItems := body["items"]; !hasItems { + status := stringField(body, "status") + if status == "" { + status = "unavailable" + } + return RefusalData{Type: "refusal", Operation: ToolStageTrackerRead, Kind: RefusalKindBoardUnavailable, Reason: "the Activity monitor is " + status + "; retry shortly"}, nil + } + offset, err := OffsetFromArgs(args) + if err != nil { + return refuse(err.Error()) + } + kind := strings.ToLower(stringArg(args, "kind")) + if kind != "" && kind != "issue" && kind != "pr" { + return refuse(fmt.Sprintf("unknown kind %q; valid kinds: issue, pr", kind)) + } + view := strings.ToLower(stringArg(args, "view")) + if view == "" { + view = stageTrackerViewSummary + } + if view != stageTrackerViewSummary && view != stageTrackerViewFull { + return refuse(fmt.Sprintf("unknown view %q; valid views: summary, full", view)) + } + number, hasNumber, err := optionalNonNegativeIntArg(args, "number") + if err != nil { + return refuse(err.Error()) + } + stage, hasStage, err := optionalNonNegativeIntArg(args, "stage") + if err != nil { + return refuse(err.Error()) + } + repo := stringArg(args, "repo") + q := strings.ToLower(stringArg(args, "q")) + items, _ := body["items"].([]any) + matched := make([]any, 0, len(items)) + for _, raw := range items { + item, ok := raw.(map[string]any) + if !ok { + continue + } + if repo != "" && !strings.EqualFold(stringField(item, "repo"), repo) { + continue + } + if kind != "" && stringField(item, "kind") != kind { + continue + } + if hasNumber && intField(item, "number") != number { + continue + } + if hasStage && intField(item, "stage") != stage { + continue + } + if q != "" && !stageTrackerQueryMatches(item, q) { + continue + } + if !boolFilterMatches(args, item, "needs_human") || !boolFilterMatches(args, item, "on_hold") || !boolFilterMatches(args, item, "waiting_on_you") { + continue + } + if view == stageTrackerViewSummary { + item = pickKeys(item, stageTrackerSummaryKeys) + } + matched = append(matched, item) + } + limit := LimitFromArgs(args) + total := len(matched) + start := min(offset, total) + end := min(start+limit, total) + out := map[string]any{ + "generated_at": body["generated_at"], + "source": body["source"], + "stages": stageTrackerStageCounts(body["stages"], items), + "items": matched[start:end], + "total_items": len(items), + "matched": total, + "offset": offset, + "view": view, + } + for _, k := range []string{"hive_id", "open_issues", "open_prs", "needs_human", "on_hold", "waiting_on_human"} { + if v, ok := body[k]; ok { + out[k] = v + } + } + if recent, _ := args["recent"].(bool); recent { + for _, k := range []string{"recently_merged", "recently_closed"} { + if list, ok := body[k].([]any); ok { + out[k] = list[:min(limit, len(list))] + } + } + } + if end < total { + out["next_offset"] = end + out["_admin_mcp"] = map[string]any{"truncated": true, "limit": limit, "total": total, "truncated_fields": []string{"items"}} + } + return out, nil +} + +// stageTrackerQueryMatches is the monitor's search box (tracker-filter.js +// stageTrackerMatches): a number matches the item or a linked PR or issue +// by number; any text matches the item's or a linked item's title. +func stageTrackerQueryMatches(item map[string]any, q string) bool { + num := strings.TrimPrefix(q, "#") + _, err := strconv.Atoi(num) + isNum := err == nil + matches := func(m map[string]any) bool { + if isNum && strconv.Itoa(intField(m, "number")) == num { + return true + } + return strings.Contains(strings.ToLower(stringField(m, "title")), q) + } + if matches(item) { + return true + } + for _, key := range []string{"linked_prs", "linked_issues"} { + list, _ := item[key].([]any) + for _, raw := range list { + if m, ok := raw.(map[string]any); ok && matches(m) { + return true + } + } + } + return false +} + +// stageTrackerStageCounts is stages[] trimmed to what a caller needs to read +// the board, each with how many items sit at it now. +func stageTrackerStageCounts(rawStages any, items []any) []map[string]any { + counts := map[int]int{} + for _, raw := range items { + if item, ok := raw.(map[string]any); ok { + counts[intField(item, "stage")]++ + } + } + stages, _ := rawStages.([]any) + out := make([]map[string]any, 0, len(stages)) + for _, raw := range stages { + st, ok := raw.(map[string]any) + if !ok { + continue + } + row := pickKeys(st, []string{"number", "slug", "label", "dwell_seconds"}) + row["count"] = counts[intField(st, "number")] + out = append(out, row) + } + sort.SliceStable(out, func(i, j int) bool { return intField(out[i], "number") < intField(out[j], "number") }) + return out +} + +func boolFilterMatches(args, item map[string]any, key string) bool { + want, ok := args[key].(bool) + if !ok { + return true + } + have, _ := item[key].(bool) + return have == want +} + +func pickKeys(m map[string]any, keys []string) map[string]any { + out := make(map[string]any, len(keys)) + for _, k := range keys { + if v, ok := m[k]; ok { + out[k] = v + } + } + return out +} + +func stringField(m map[string]any, key string) string { + s, _ := m[key].(string) + return s +} + +func intField(m map[string]any, key string) int { + switch v := m[key].(type) { + case float64: + return int(v) + case int: + return v + } + return 0 +} + +func stageTrackerWriteOps() []WriteOp { + return []WriteOp{ + repositoryRescanOp{}, + itemAcceptTriageOp{}, + itemNeedsHumanOp{}, + itemBlockerOp{name: WriteOpRepositoryItemBlockerRecheck, segment: "blocker/recheck", label: "Re-check permissions", effect: "The hive re-reads the GitHub App's installation permissions and releases the item's capability blocker if the permission is now granted."}, + itemBlockerOp{name: WriteOpRepositoryItemBlockerHandoff, segment: "blocker/handoff", label: "Hand to workflows lane", effect: "The item is routed to the lane that can push workflow files (`hive/workflows-lane`) and its workflows-permission blocker is released."}, + itemBlockerOp{name: WriteOpRepositoryItemBlockerClosePart, segment: "blocker/close-partial", label: "Mark partially-addressed and close", effect: "Posts your partially-addressed note on the issue and closes it as completed.", danger: true}, + itemDecisionOp{}, + itemDelegateOp{}, + } +} + +type repositoryRescanOp struct{} +type itemAcceptTriageOp struct{} +type itemNeedsHumanOp struct{} +type itemBlockerOp struct { + name, segment, label, effect string + danger bool +} +type itemDecisionOp struct{} +type itemDelegateOp struct{} + +func itemTargetProps() map[string]any { + return map[string]any{"type": "object", "properties": map[string]any{"owner": stringSchema(), "repo": stringSchema(), "number": map[string]any{"type": "integer", "minimum": 1}}, "required": []string{"owner", "repo", "number"}, "additionalProperties": false} +} + +func itemSchema(extra map[string]any, required ...string) map[string]any { + s := itemTargetProps() + props := s["properties"].(map[string]any) + for k, v := range extra { + props[k] = v + } + s["required"] = append(s["required"].([]string), required...) + return s +} + +func itemTargetArgs(args map[string]any) (owner, repo string, number int, err error) { + owner = stringArg(args, "owner") + repo = stringArg(args, "repo") + number, err = positiveIntArg(args, "number") + if err != nil { + return "", "", 0, err + } + if owner == "" || repo == "" { + return "", "", 0, fmt.Errorf("owner, repo and number are required") + } + return owner, repo, number, nil +} + +func itemPath(owner, repo string, number int, suffix string) string { + return "/api/repos/" + url.PathEscape(owner) + "/" + url.PathEscape(repo) + "/items/" + strconv.Itoa(number) + "/" + suffix +} + +func itemRef(owner, repo string, number int) string { + return owner + "/" + repo + "#" + strconv.Itoa(number) +} + +// boardRow is one item as a preview found it on the Activity monitor. read is +// false when the board itself could not be read (no provider, an error, or +// no snapshot yet), so a missing item is not mistaken for one that left. +type boardRow struct { + item map[string]any + read bool +} + +// stageTrackerItem reads one item off the Activity monitor for a preview: its +// row (full view) when it is on the board. +func stageTrackerItem(ctx context.Context, provider Provider, owner, repo string, number int) boardRow { + if provider == nil { + return boardRow{} + } + data, err := provider.Read(ctx, ToolStageTrackerRead, map[string]any{"repo": owner + "/" + repo, "number": number, "view": stageTrackerViewFull, "limit": MaxResultLimit}) + if err != nil { + return boardRow{} + } + body, ok := data.(map[string]any) + if !ok { + return boardRow{} + } + items, _ := body["items"].([]any) + for _, raw := range items { + if item, ok := raw.(map[string]any); ok && strings.EqualFold(stringField(item, "repo"), owner+"/"+repo) && intField(item, "number") == number { + return boardRow{item: item, read: true} + } + } + return boardRow{read: true} +} + +// boardDetails is what a preview says about the item as the monitor shows it, +// so the caller confirms against the state the operator would have seen. +func boardDetails(row boardRow, details map[string]any) []string { + item := row.item + if !row.read { + details["on_board"] = "unknown" + return []string{"The Activity monitor could not be read just now, so this preview cannot show the item's current state; the hive still decides whether the request applies."} + } + if item == nil { + details["on_board"] = false + return []string{"This item is not on the Activity monitor now, so the dashboard would not offer this action on it; the hive still decides whether the request applies."} + } + details["on_board"] = true + for _, k := range []string{"kind", "title", "stage", "stage_slug", "reason", "wait_kind"} { + if v, ok := item[k]; ok { + details[k] = v + } + } + if dn, ok := item["decision_needed"].(map[string]any); ok { + if q := stringField(dn, "question"); q != "" { + details["decision_question"] = q + } + } + return nil +} + +func itemKind(args map[string]any, item map[string]any) (string, error) { + kind := strings.ToLower(stringArg(args, "type")) + if kind == "" && item != nil { + kind = stringField(item, "kind") + } + switch kind { + case "": + return "", fmt.Errorf("type is required (issue or pr) when the item is not on the Activity monitor or the monitor cannot be read") + case "issue", "pr": + return kind, nil + } + return "", fmt.Errorf("type must be issue or pr, got %q", kind) +} + +// previewItemKind is itemKind for a preview. ConfirmWrite re-runs Preview +// with no provider and compares only the method and path, which the kind does +// not change, so there an unknown kind reads as issue; the request it executes +// is the one the provider-backed preview stored. +func previewItemKind(args map[string]any, item map[string]any, provider Provider) (string, error) { + kind, err := itemKind(args, item) + if err != nil && provider == nil && stringArg(args, "type") == "" { + return "issue", nil + } + return kind, err +} + +func (repositoryRescanOp) Name() string { return WriteOpRepositoryRescan } +func (repositoryRescanOp) Description() string { + return "Re-evaluate now: ask the hive to rescan its repositories through POST /api/repos/rescan (the Activity monitor's \"Re-evaluate now\")." +} +func (repositoryRescanOp) InputSchema() map[string]any { return emptySchema() } +func (repositoryRescanOp) Preview(_ context.Context, _ map[string]any) (WritePreview, error) { + return WritePreview{Operation: WriteOpRepositoryRescan, Summary: "Rescan every watched repository now", Target: "all watched repositories", Request: WriteRequest{Method: http.MethodPost, Path: "/api/repos/rescan", Body: map[string]any{}}, Effects: []string{"The hive re-reads issues and pull requests on its watched repositories now instead of on its next scheduled pass. If a rescan is already running, or one finished less than 30 seconds ago, nothing new is started: the hive answers in-progress or debounced (with retry_after_s) and the previous scan's counts, and no rescan is queued."}, WideningDisclosure: "Hive-wide: the rescan covers every watched repository, as the dashboard's button does, but changes no item by itself.", ConfirmationMessage: "Confirm rescanning the watched repositories now.", Details: map[string]any{}}, nil +} + +func (itemAcceptTriageOp) Name() string { return WriteOpRepositoryItemAcceptTriage } +func (itemAcceptTriageOp) Description() string { + return "Accept triage on one issue through POST /api/repos/{owner}/{repo}/items/{number}/accept-triage." +} +func (itemAcceptTriageOp) InputSchema() map[string]any { return itemTargetProps() } +func (op itemAcceptTriageOp) Preview(ctx context.Context, args map[string]any) (WritePreview, error) { + return op.PreviewWithProvider(ctx, args, nil) +} +func (itemAcceptTriageOp) PreviewWithProvider(ctx context.Context, args map[string]any, provider Provider) (WritePreview, error) { + owner, repo, number, err := itemTargetArgs(args) + if err != nil { + return WritePreview{}, err + } + target := itemRef(owner, repo, number) + details := map[string]any{"owner": owner, "repo": repo, "number": number} + row := stageTrackerItem(ctx, provider, owner, repo, number) + item := row.item + if item != nil && stringField(item, "kind") == "pr" { + return WritePreview{}, fmt.Errorf("%s is a pull request; triage is accepted on issues only", target) + } + effects := append([]string{"The issue gets the triage-accepted label and loses needs-triage; the hive takes it on its next pass."}, boardDetails(row, details)...) + return WritePreview{Operation: WriteOpRepositoryItemAcceptTriage, Summary: "Accept triage on " + target, Target: target, Request: WriteRequest{Method: http.MethodPost, Path: itemPath(owner, repo, number, "accept-triage"), Body: map[string]any{}}, Effects: effects, WideningDisclosure: "No widening: this operation targets exactly one issue.", ConfirmationMessage: "Confirm accepting triage on " + target + ".", Details: details}, nil +} + +func (itemNeedsHumanOp) Name() string { return WriteOpRepositoryItemNeedsHuman } +func (itemNeedsHumanOp) Description() string { + return "Mark one item needs-human with a reason through POST /api/review/pipeline/{owner}/{repo}/{number}/send-to-human. Needs the merger or owner role." +} +func (itemNeedsHumanOp) InputSchema() map[string]any { + return itemSchema(map[string]any{"reason": map[string]any{"type": "string", "minLength": 1, "maxLength": stageTrackerDecisionMaxNotes}}, "reason") +} +func (op itemNeedsHumanOp) Preview(ctx context.Context, args map[string]any) (WritePreview, error) { + return op.PreviewWithProvider(ctx, args, nil) +} +func (itemNeedsHumanOp) PreviewWithProvider(ctx context.Context, args map[string]any, provider Provider) (WritePreview, error) { + owner, repo, number, err := itemTargetArgs(args) + if err != nil { + return WritePreview{}, err + } + reason, err := requiredString(args, "reason") + if err != nil { + return WritePreview{}, err + } + if len(reason) > stageTrackerDecisionMaxNotes { + return WritePreview{}, fmt.Errorf("reason exceeds %d characters", stageTrackerDecisionMaxNotes) + } + target := itemRef(owner, repo, number) + details := map[string]any{"owner": owner, "repo": repo, "number": number, "reason": reason} + effects := append([]string{"The item gets the needs-human label with your reason; agents stop working it until a person clears the label."}, boardDetails(stageTrackerItem(ctx, provider, owner, repo, number), details)...) + path := "/api/review/pipeline/" + url.PathEscape(owner) + "/" + url.PathEscape(repo) + "/" + strconv.Itoa(number) + "/send-to-human" + return WritePreview{Operation: WriteOpRepositoryItemNeedsHuman, Summary: "Mark " + target + " needs-human", Target: target, Request: WriteRequest{Method: http.MethodPost, Path: path, Body: map[string]any{"reason": reason}}, Effects: effects, WideningDisclosure: "No widening: this operation targets exactly one repository item.", ConfirmationMessage: "Confirm marking " + target + " needs-human.", Details: details}, nil +} + +func (op itemBlockerOp) Name() string { return op.name } +func (op itemBlockerOp) Description() string { + return op.label + " on one issue's recorded blocker through POST /api/repos/{owner}/{repo}/items/{number}/" + op.segment + "." +} +func (itemBlockerOp) InputSchema() map[string]any { return itemTargetProps() } +func (op itemBlockerOp) Preview(ctx context.Context, args map[string]any) (WritePreview, error) { + return op.PreviewWithProvider(ctx, args, nil) +} +func (op itemBlockerOp) PreviewWithProvider(ctx context.Context, args map[string]any, provider Provider) (WritePreview, error) { + owner, repo, number, err := itemTargetArgs(args) + if err != nil { + return WritePreview{}, err + } + target := itemRef(owner, repo, number) + details := map[string]any{"owner": owner, "repo": repo, "number": number} + row := stageTrackerItem(ctx, provider, owner, repo, number) + item := row.item + if item != nil { + if stringField(item, "kind") == "pr" { + return WritePreview{}, fmt.Errorf("%s is a pull request; blocker actions apply to issues only", target) + } + if b, ok := item["blocker"].(map[string]any); ok { + details["blocker"] = b + } + } + effects := append([]string{op.effect}, boardDetails(row, details)...) + if op.danger { + details["danger"] = true + } + return WritePreview{Operation: op.name, Summary: op.label + " on " + target, Target: target, Request: WriteRequest{Method: http.MethodPost, Path: itemPath(owner, repo, number, op.segment), Body: map[string]any{}}, Effects: effects, WideningDisclosure: "No widening: this operation targets exactly one issue's blocker.", ConfirmationMessage: "Confirm " + strings.ToLower(op.label) + " on " + target + ".", Details: details}, nil +} + +func (itemDecisionOp) Name() string { return WriteOpRepositoryItemDecision } +func (itemDecisionOp) Description() string { + return "Answer one item's decision as the Activity monitor's Decide menu does, through POST /api/repos/{owner}/{repo}/items/{number}/decision: approve, direction (needs comment), close-superseded (optional superseded_by), close-wontfix, close-read, close-issue, adopt, adopt-now, re-author, or reroute (optional to, default any). The merge answers (merge-now, queue-merge) are excluded." +} +func (itemDecisionOp) InputSchema() map[string]any { + return itemSchema(map[string]any{ + "decision": map[string]any{"type": "string", "enum": stageTrackerDecisions}, + "type": map[string]any{"type": "string", "enum": []string{"issue", "pr"}, "description": "Read from the Activity monitor when omitted."}, + "comment": map[string]any{"type": "string", "maxLength": stageTrackerDecisionMaxNotes}, + "superseded_by": map[string]any{"type": "string", "description": "close-superseded only: \"458\", \"#458\", \"owner/repo#458\" or a GitHub URL."}, + "to": map[string]any{"type": "string", "description": "reroute only: the target clanker's login, or \"any\"."}, + }, "decision") +} +func (op itemDecisionOp) Preview(ctx context.Context, args map[string]any) (WritePreview, error) { + return op.PreviewWithProvider(ctx, args, nil) +} +func (itemDecisionOp) PreviewWithProvider(ctx context.Context, args map[string]any, provider Provider) (WritePreview, error) { + owner, repo, number, err := itemTargetArgs(args) + if err != nil { + return WritePreview{}, err + } + decision := strings.ToLower(stringArg(args, "decision")) + if slices.Contains(stageTrackerMergeDecisions, decision) { + return WritePreview{}, fmt.Errorf("decision %q merges the pull request and is excluded from admin MCP like POST /api/prs/{owner}/{repo}/{number}/queue-automerge; do not approximate it with other operations", decision) + } + if !slices.Contains(stageTrackerDecisions, decision) { + return WritePreview{}, fmt.Errorf("decision must be one of %s", strings.Join(stageTrackerDecisions, ", ")) + } + comment, _ := args["comment"].(string) + comment = strings.TrimSpace(comment) + if len(comment) > stageTrackerDecisionMaxNotes { + return WritePreview{}, fmt.Errorf("comment exceeds %d characters", stageTrackerDecisionMaxNotes) + } + if decision == "direction" && comment == "" { + return WritePreview{}, fmt.Errorf("a direction decision needs the direction text in comment") + } + target := itemRef(owner, repo, number) + row := stageTrackerItem(ctx, provider, owner, repo, number) + kind, err := previewItemKind(args, row.item, provider) + if err != nil { + return WritePreview{}, err + } + if decision == "close-issue" && kind != "issue" { + return WritePreview{}, fmt.Errorf("close-issue closes an issue; %s is a pull request", target) + } + body := map[string]any{"decision": decision, "comment": comment, "type": kind} + var effect string + danger := false + switch decision { + case "approve": + effect = "The issue is unparked with your approval and the hive resumes it." + if kind == "pr" { + effect = "Posts `/lgtm` and `/approve` as your decision; the pull request becomes merge-eligible, and the hive's merge sweep merges it once CI is green and the head has soaked." + } + case "direction": + effect = "Records your direction for the hive and unparks the item; the hive resumes with it." + case "close-superseded": + effect = "Closes the item as superseded, with your comment." + if by := stringArg(args, "superseded_by"); by != "" { + body["superseded_by"] = by + effect = "Closes the item as superseded by " + by + ", with your comment." + } + danger = true + case "close-wontfix": + effect, danger = "Closes the item as won't-fix (not planned), with your comment.", true + case "close-read": + effect, danger = "Closes the advisory issue as completed, as read.", true + case "close-issue": + effect, danger = "Closes only this issue as completed, with your comment.", true + case "adopt": + effect = "Asks the hive to adopt the pull request: a hive copy on its own branch, the original closed as superseded. Author presence, the grace window and maintainer_policy still apply." + case "adopt-now": + body["decision"], body["force"] = "adopt", true + effect, danger = "Adopts the pull request now, bypassing the author's presence, the grace window and maintainer_policy; the original is closed as superseded.", true + case "re-author": + effect = "The hive re-homes the commits on a hive-owned branch and opens a superseding pull request." + case "reroute": + to := stringArg(args, "to") + if to == "" { + to = "any" + } + body["to"] = to + effect = "Hands the item to another clanker (" + to + ")." + } + details := map[string]any{"owner": owner, "repo": repo, "number": number, "decision": decision, "type": kind} + if danger { + details["danger"] = true + } + effects := append([]string{effect, "Recorded as your decision, attributed to your login."}, boardDetails(row, details)...) + return WritePreview{Operation: WriteOpRepositoryItemDecision, Summary: "Decide " + decision + " on " + target, Target: target, Request: WriteRequest{Method: http.MethodPost, Path: itemPath(owner, repo, number, "decision"), Body: body}, Effects: effects, WideningDisclosure: "No widening: this operation targets exactly one repository item.", ConfirmationMessage: "Confirm deciding " + decision + " on " + target + ".", Details: details}, nil +} + +func (itemDelegateOp) Name() string { return WriteOpRepositoryItemDelegate } +func (itemDelegateOp) Description() string { + return "Let hive decide one item through POST /api/repos/{owner}/{repo}/items/{number}/decide-delegated, never merging: the request carries no_merge, so an approved pull request gets /lgtm + /approve rather than a review queued for auto-merge. Asynchronous; read delegated_decision_status for the outcome. prs (two or more) decides each of an issue's open pull requests; rerun re-runs a stuck decision." +} +func (itemDelegateOp) InputSchema() map[string]any { + return itemSchema(map[string]any{ + "type": map[string]any{"type": "string", "enum": []string{"issue", "pr"}, "description": "Read from the Activity monitor when omitted."}, + "prs": map[string]any{"type": "array", "items": map[string]any{"type": "integer", "minimum": 1}, "description": "Issue only: the open pull requests to decide one by one (two or more)."}, + "rerun": map[string]any{"type": "boolean", "description": "Re-run past the \"already recorded\" check on a stuck decision."}, + }) +} +func (op itemDelegateOp) Preview(ctx context.Context, args map[string]any) (WritePreview, error) { + return op.PreviewWithProvider(ctx, args, nil) +} +func (itemDelegateOp) PreviewWithProvider(ctx context.Context, args map[string]any, provider Provider) (WritePreview, error) { + owner, repo, number, err := itemTargetArgs(args) + if err != nil { + return WritePreview{}, err + } + target := itemRef(owner, repo, number) + row := stageTrackerItem(ctx, provider, owner, repo, number) + kind, err := previewItemKind(args, row.item, provider) + if err != nil { + return WritePreview{}, err + } + body := map[string]any{"type": kind, "no_merge": true} + // The row's own words for the park, as the dashboard sends them, so the + // decider sees what the operator saw; head keys the plan cache. + for _, k := range []string{"reason", "caption", "sentinel_reason"} { + body[k] = stringField(row.item, k) + } + if head := stringField(row.item, "head"); head != "" { + body["head"] = head + } + if raw, ok := args["prs"].([]any); ok && len(raw) > 0 { + if kind != "issue" { + return WritePreview{}, fmt.Errorf("prs applies to an issue's nested pull requests; %s is a pull request", target) + } + prs := make([]int, 0, len(raw)) + for _, v := range raw { + n, ok := v.(float64) + if !ok || n < 1 || n != float64(int(n)) { + return WritePreview{}, fmt.Errorf("prs must be positive integers") + } + prs = append(prs, int(n)) + } + if len(prs) < 2 { + return WritePreview{}, fmt.Errorf("prs needs two or more pull requests; decide a single one on its own number") + } + body["prs"] = prs + } + if rerun, _ := args["rerun"].(bool); rerun { + body["force"] = true + } + details := map[string]any{"owner": owner, "repo": repo, "number": number, "type": kind} + effects := []string{ + "The hive decides for you under its delegate policy and rails, and the outcome is recorded as your decision with an audit marker.", + "Never merges: no_merge is set, so an approved pull request gets `/lgtm` + `/approve` (merge-eligible for the hive's merge sweep) rather than an Approve review queued for auto-merge.", + "Runs in the background; read delegated_decision_status for the outcome.", + } + effects = append(effects, boardDetails(row, details)...) + return WritePreview{Operation: WriteOpRepositoryItemDelegate, Summary: "Let hive decide " + target, Target: target, Request: WriteRequest{Method: http.MethodPost, Path: itemPath(owner, repo, number, "decide-delegated"), Body: body}, Effects: effects, WideningDisclosure: "No widening: this operation targets one item (with prs, that issue's named pull requests).", ConfirmationMessage: "Confirm letting the hive decide " + target + ".", Details: details}, nil +} diff --git a/src/pkg/adminmcp/tools_stage_tracker_test.go b/src/pkg/adminmcp/tools_stage_tracker_test.go new file mode 100644 index 0000000000..0bd4bfefdc --- /dev/null +++ b/src/pkg/adminmcp/tools_stage_tracker_test.go @@ -0,0 +1,535 @@ +package adminmcp + +import ( + "context" + "encoding/json" + "errors" + "slices" + "strings" + "testing" + "time" +) + +// stageTrackerFixture is a /api/stage-tracker answer as JSON decodes it. +func stageTrackerFixture(t *testing.T) map[string]any { + t.Helper() + raw := `{ + "generated_at": "2026-11-06T02:00:00Z", "source": "fresh", "hive_id": "bluefin", + "open_issues": 2, "open_prs": 2, "needs_human": 1, "on_hold": 1, + "stages": [{"number": 40, "slug": "covered-by-pr", "label": "Covered by PR", "short": "PR", "dwell_seconds": 3600}, + {"number": 10, "slug": "actionable", "label": "Actionable", "dwell_seconds": 600}], + "items": [ + {"repo": "projectbluefin/utah-packages", "number": 488, "kind": "issue", "title": "Package the gimp batch", "stage": 40, + "linked_prs": [{"number": 892, "title": "gimp batch"}], "history": [{"number": 10}], "ci_activity": {"x": 1}}, + {"repo": "projectbluefin/utah-packages", "number": 892, "kind": "pr", "title": "gimp batch", "stage": 40, "head": "abc123", + "reason": "contributor-lane:review", "caption": "review pending", "sentinel_reason": "", "nested_under": 488, + "waiting_on_you": true, "wait_kind": "approve-needed"}, + {"repo": "projectbluefin/chairlift", "number": 639, "kind": "issue", "title": "Settings crash", "stage": 10, "needs_human": true, + "decision_needed": {"question": "Which fix?"}, "blocker": {"kind": "workflows"}}, + {"repo": "projectbluefin/chairlift", "number": 488, "kind": "pr", "title": "Unrelated", "stage": 10, "on_hold": true} + ], + "recently_merged": [{"number": 1}, {"number": 2}, {"number": 3}] + }` + var out map[string]any + if err := json.Unmarshal([]byte(raw), &out); err != nil { + t.Fatal(err) + } + return out +} + +func readBoard(t *testing.T, args map[string]any) map[string]any { + t.Helper() + got, err := StageTrackerReadResult(stageTrackerFixture(t), args) + if err != nil { + t.Fatal(err) + } + out, ok := got.(map[string]any) + if !ok { + t.Fatalf("result = %#v", got) + } + return out +} + +func boardRefs(out map[string]any) []string { + var refs []string + for _, raw := range out["items"].([]any) { + it := raw.(map[string]any) + refs = append(refs, stringField(it, "repo")+"#"+strings.TrimSpace(strings.Split(jsonString(it["number"]), ".")[0])) + } + return refs +} + +func jsonString(v any) string { b, _ := json.Marshal(v); return string(b) } + +func TestStageTrackerReadFilters(t *testing.T) { + cases := []struct { + name string + args map[string]any + want []string + }{ + {"all", map[string]any{}, []string{"projectbluefin/utah-packages#488", "projectbluefin/utah-packages#892", "projectbluefin/chairlift#639", "projectbluefin/chairlift#488"}}, + {"repo", map[string]any{"repo": "ProjectBluefin/Chairlift"}, []string{"projectbluefin/chairlift#639", "projectbluefin/chairlift#488"}}, + {"kind", map[string]any{"kind": "pr"}, []string{"projectbluefin/utah-packages#892", "projectbluefin/chairlift#488"}}, + {"number is the item only", map[string]any{"number": float64(892)}, []string{"projectbluefin/utah-packages#892"}}, + {"number across repos", map[string]any{"number": float64(488)}, []string{"projectbluefin/utah-packages#488", "projectbluefin/chairlift#488"}}, + // The search box: a number also matches a linked item. + {"q number matches linked pr", map[string]any{"q": "#892"}, []string{"projectbluefin/utah-packages#488", "projectbluefin/utah-packages#892"}}, + {"q title", map[string]any{"q": "CRASH"}, []string{"projectbluefin/chairlift#639"}}, + {"stage", map[string]any{"stage": float64(10)}, []string{"projectbluefin/chairlift#639", "projectbluefin/chairlift#488"}}, + {"needs_human", map[string]any{"needs_human": true}, []string{"projectbluefin/chairlift#639"}}, + {"on_hold false", map[string]any{"on_hold": false, "repo": "projectbluefin/chairlift"}, []string{"projectbluefin/chairlift#639"}}, + {"waiting_on_you", map[string]any{"waiting_on_you": true}, []string{"projectbluefin/utah-packages#892"}}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + out := readBoard(t, tc.args) + if got := boardRefs(out); !slices.Equal(got, tc.want) { + t.Fatalf("items = %v, want %v", got, tc.want) + } + if out["matched"] != len(tc.want) || out["total_items"] != 4 { + t.Fatalf("matched=%v total=%v", out["matched"], out["total_items"]) + } + }) + } +} + +func TestStageTrackerReadStageCountsDescribeWholeBoard(t *testing.T) { + out := readBoard(t, map[string]any{"repo": "projectbluefin/chairlift"}) + stages := out["stages"].([]map[string]any) + if len(stages) != 2 || intField(stages[0], "number") != 10 || stages[0]["count"] != 2 || stages[1]["count"] != 2 { + t.Fatalf("stages = %#v", stages) + } + if _, ok := stages[1]["short"]; ok { + t.Fatalf("stage rows keep only number, slug, label, dwell and count: %#v", stages[1]) + } + if out["hive_id"] != "bluefin" || out["needs_human"] != float64(1) { + t.Fatalf("board counts missing: %#v", out) + } +} + +func TestStageTrackerReadSummaryAndFullViews(t *testing.T) { + summary := readBoard(t, map[string]any{"number": float64(488), "repo": "projectbluefin/utah-packages"}) + item := summary["items"].([]any)[0].(map[string]any) + if _, ok := item["history"]; ok { + t.Fatalf("summary keeps history: %#v", item) + } + if _, ok := item["linked_prs"]; !ok { + t.Fatalf("summary drops linked_prs: %#v", item) + } + full := readBoard(t, map[string]any{"number": float64(488), "repo": "projectbluefin/utah-packages", "view": "full"}) + item = full["items"].([]any)[0].(map[string]any) + if _, ok := item["history"]; !ok || full["view"] != "full" { + t.Fatalf("full view drops history: %#v", item) + } +} + +func TestStageTrackerReadPagesAndRecent(t *testing.T) { + first := readBoard(t, map[string]any{"limit": float64(3), "recent": true}) + if len(first["items"].([]any)) != 3 || first["next_offset"] != 3 { + t.Fatalf("first page = %#v", first) + } + if len(first["recently_merged"].([]any)) != 3 { + t.Fatalf("recent = %#v", first["recently_merged"]) + } + second := readBoard(t, map[string]any{"limit": float64(3), "offset": float64(3)}) + if got := boardRefs(second); !slices.Equal(got, []string{"projectbluefin/chairlift#488"}) { + t.Fatalf("second page = %v", got) + } + if _, ok := second["next_offset"]; ok { + t.Fatalf("last page has next_offset: %#v", second) + } + if _, ok := second["recently_merged"]; ok { + t.Fatal("recently_merged returned without recent") + } +} + +func TestStageTrackerReadRefusesBadArguments(t *testing.T) { + for _, args := range []map[string]any{{"kind": "epic"}, {"view": "wide"}, {"offset": float64(-1)}, {"number": "x"}} { + got, err := StageTrackerReadResult(stageTrackerFixture(t), args) + if err != nil { + t.Fatal(err) + } + if r, ok := got.(RefusalData); !ok || r.Kind != RefusalKindInvalidArgument { + t.Fatalf("args %v: result = %#v", args, got) + } + } +} + +// boardProvider serves stage_tracker_read from the fixture, as both transports +// do, so a preview reads the item off the board. +type boardProvider struct { + t *testing.T + err error + calls int +} + +func (p *boardProvider) Read(_ context.Context, tool string, args map[string]any) (any, error) { + p.calls++ + if tool != ToolStageTrackerRead { + p.t.Fatalf("preview read %q", tool) + } + if p.err != nil { + return nil, p.err + } + return StageTrackerReadResult(stageTrackerFixture(p.t), args) +} + +func previewOp(t *testing.T, name string, args map[string]any, provider Provider) (WritePreview, error) { + t.Helper() + op, ok := DefaultWriteRegistry().Get(name) + if !ok { + t.Fatalf("%s is not registered", name) + } + if po, ok := op.(providerPreviewOp); ok { + return po.PreviewWithProvider(context.Background(), args, provider) + } + return op.Preview(context.Background(), args) +} + +func itemArgs(repo string, number int, extra map[string]any) map[string]any { + owner, name, _ := strings.Cut(repo, "/") + args := map[string]any{"owner": owner, "repo": name, "number": float64(number)} + for k, v := range extra { + args[k] = v + } + return args +} + +func TestStageTrackerWriteOpsAreRegistered(t *testing.T) { + reg := DefaultWriteRegistry() + for _, name := range []string{WriteOpRepositoryRescan, WriteOpRepositoryItemAcceptTriage, WriteOpRepositoryItemNeedsHuman, WriteOpRepositoryItemBlockerRecheck, WriteOpRepositoryItemBlockerHandoff, WriteOpRepositoryItemBlockerClosePart, WriteOpRepositoryItemDecision, WriteOpRepositoryItemDelegate} { + if _, ok := reg.Get(name); !ok { + t.Fatalf("%s not registered", name) + } + } + for _, tool := range []string{ToolStageTrackerRead, ToolDelegatedDecisionStatus} { + if !AllowedTool(tool) { + t.Fatalf("%s not allowed", tool) + } + found := false + for _, def := range Tools() { + if def["name"] == tool { + found = true + } + } + if !found { + t.Fatalf("%s missing from tools/list", tool) + } + } +} + +func TestItemOpsSendTheDashboardRequests(t *testing.T) { + p := &boardProvider{t: t} + cases := []struct { + op string + args map[string]any + path string + body map[string]any + }{ + {WriteOpRepositoryRescan, map[string]any{}, "/api/repos/rescan", map[string]any{}}, + {WriteOpRepositoryItemAcceptTriage, itemArgs("projectbluefin/chairlift", 639, nil), "/api/repos/projectbluefin/chairlift/items/639/accept-triage", map[string]any{}}, + {WriteOpRepositoryItemNeedsHuman, itemArgs("projectbluefin/chairlift", 639, map[string]any{"reason": "owner call"}), "/api/review/pipeline/projectbluefin/chairlift/639/send-to-human", map[string]any{"reason": "owner call"}}, + {WriteOpRepositoryItemBlockerRecheck, itemArgs("projectbluefin/chairlift", 639, nil), "/api/repos/projectbluefin/chairlift/items/639/blocker/recheck", map[string]any{}}, + {WriteOpRepositoryItemBlockerHandoff, itemArgs("projectbluefin/chairlift", 639, nil), "/api/repos/projectbluefin/chairlift/items/639/blocker/handoff", map[string]any{}}, + {WriteOpRepositoryItemBlockerClosePart, itemArgs("projectbluefin/chairlift", 639, nil), "/api/repos/projectbluefin/chairlift/items/639/blocker/close-partial", map[string]any{}}, + } + for _, tc := range cases { + t.Run(tc.op, func(t *testing.T) { + pv, err := previewOp(t, tc.op, tc.args, p) + if err != nil { + t.Fatal(err) + } + if pv.Request.Method != "POST" || pv.Request.Path != tc.path || jsonString(pv.Request.Body) != jsonString(tc.body) { + t.Fatalf("request = %+v", pv.Request) + } + if err := rejectUnpersistablePreview(tc.op, tc.args, pv); err != nil { + t.Fatalf("preview cannot be stored for confirmation: %v", err) + } + }) + } +} + +func TestItemPreviewShowsTheBoard(t *testing.T) { + pv, err := previewOp(t, WriteOpRepositoryItemBlockerRecheck, itemArgs("projectbluefin/chairlift", 639, nil), &boardProvider{t: t}) + if err != nil { + t.Fatal(err) + } + if pv.Details["on_board"] != true || pv.Details["decision_question"] != "Which fix?" || pv.Details["blocker"] == nil { + t.Fatalf("details = %#v", pv.Details) + } + off, err := previewOp(t, WriteOpRepositoryItemBlockerRecheck, itemArgs("projectbluefin/chairlift", 9999, nil), &boardProvider{t: t}) + if err != nil { + t.Fatal(err) + } + if off.Details["on_board"] != false || !strings.Contains(strings.Join(off.Effects, " "), "not on the Activity monitor") { + t.Fatalf("off-board preview = %#v", off) + } +} + +func TestIssueOnlyOpsRefusePullRequests(t *testing.T) { + for _, op := range []string{WriteOpRepositoryItemAcceptTriage, WriteOpRepositoryItemBlockerRecheck, WriteOpRepositoryItemBlockerHandoff, WriteOpRepositoryItemBlockerClosePart} { + if _, err := previewOp(t, op, itemArgs("projectbluefin/utah-packages", 892, nil), &boardProvider{t: t}); err == nil || !strings.Contains(err.Error(), "pull request") { + t.Fatalf("%s on a PR: err = %v", op, err) + } + } +} + +func TestNeedsHumanRequiresReason(t *testing.T) { + if _, err := previewOp(t, WriteOpRepositoryItemNeedsHuman, itemArgs("projectbluefin/chairlift", 639, nil), nil); err == nil { + t.Fatal("needs-human without a reason previewed") + } +} + +func TestItemDecisionRequests(t *testing.T) { + p := &boardProvider{t: t} + cases := []struct { + name string + args map[string]any + body map[string]any + }{ + {"approve issue", itemArgs("projectbluefin/chairlift", 639, map[string]any{"decision": "approve"}), map[string]any{"decision": "approve", "comment": "", "type": "issue"}}, + {"approve pr reads kind off the board", itemArgs("projectbluefin/utah-packages", 892, map[string]any{"decision": "approve"}), map[string]any{"decision": "approve", "comment": "", "type": "pr"}}, + {"direction", itemArgs("projectbluefin/chairlift", 639, map[string]any{"decision": "direction", "comment": "use option B"}), map[string]any{"decision": "direction", "comment": "use option B", "type": "issue"}}, + {"close superseded", itemArgs("projectbluefin/chairlift", 639, map[string]any{"decision": "close-superseded", "superseded_by": "#700"}), map[string]any{"decision": "close-superseded", "comment": "", "type": "issue", "superseded_by": "#700"}}, + {"adopt now", itemArgs("projectbluefin/utah-packages", 892, map[string]any{"decision": "adopt-now"}), map[string]any{"decision": "adopt", "force": true, "comment": "", "type": "pr"}}, + {"reroute defaults to any", itemArgs("projectbluefin/utah-packages", 892, map[string]any{"decision": "reroute"}), map[string]any{"decision": "reroute", "to": "any", "comment": "", "type": "pr"}}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + pv, err := previewOp(t, WriteOpRepositoryItemDecision, tc.args, p) + if err != nil { + t.Fatal(err) + } + if !strings.HasSuffix(pv.Request.Path, "/decision") || jsonString(pv.Request.Body) != jsonString(tc.body) { + t.Fatalf("request = %s %s", pv.Request.Path, jsonString(pv.Request.Body)) + } + if err := rejectUnpersistablePreview(WriteOpRepositoryItemDecision, tc.args, pv); err != nil { + t.Fatalf("preview cannot be stored for confirmation: %v", err) + } + }) + } +} + +func TestItemDecisionRefusals(t *testing.T) { + p := &boardProvider{t: t} + for _, tc := range []struct { + name string + args map[string]any + want string + }{ + {"merge-now", itemArgs("projectbluefin/utah-packages", 892, map[string]any{"decision": "merge-now"}), "queue-automerge"}, + {"queue-merge", itemArgs("projectbluefin/utah-packages", 892, map[string]any{"decision": "queue-merge"}), "queue-automerge"}, + {"unknown", itemArgs("projectbluefin/utah-packages", 892, map[string]any{"decision": "ship-it"}), "must be one of"}, + {"direction needs text", itemArgs("projectbluefin/chairlift", 639, map[string]any{"decision": "direction"}), "direction text"}, + {"close-issue on a pr", itemArgs("projectbluefin/utah-packages", 892, map[string]any{"decision": "close-issue"}), "pull request"}, + {"off board needs type", itemArgs("projectbluefin/chairlift", 9999, map[string]any{"decision": "approve"}), "type is required"}, + {"bad type", itemArgs("projectbluefin/chairlift", 639, map[string]any{"decision": "approve", "type": "epic"}), "issue or pr"}, + {"comment too long", itemArgs("projectbluefin/chairlift", 639, map[string]any{"decision": "direction", "comment": strings.Repeat("x", 4001)}), "exceeds"}, + } { + t.Run(tc.name, func(t *testing.T) { + _, err := previewOp(t, WriteOpRepositoryItemDecision, tc.args, p) + if err == nil || !strings.Contains(err.Error(), tc.want) { + t.Fatalf("err = %v, want %q", err, tc.want) + } + }) + } + if p.calls == 0 { + t.Fatal("decision previews never read the board") + } +} + +// ConfirmWrite re-runs Preview with no provider and compares the path: an +// item whose kind came off the board must still preview there. +func TestItemDecisionConfirmRecheckNeedsNoBoard(t *testing.T) { + args := itemArgs("projectbluefin/utah-packages", 892, map[string]any{"decision": "approve"}) + withBoard, err := previewOp(t, WriteOpRepositoryItemDecision, args, &boardProvider{t: t}) + if err != nil { + t.Fatal(err) + } + op, _ := DefaultWriteRegistry().Get(WriteOpRepositoryItemDecision) + bare, err := op.Preview(context.Background(), args) + if err != nil { + t.Fatal(err) + } + if bare.Request.Path != withBoard.Request.Path || bare.Request.Method != withBoard.Request.Method { + t.Fatalf("re-check path %s != %s", bare.Request.Path, withBoard.Request.Path) + } +} + +func TestItemDelegateNeverMerges(t *testing.T) { + args := itemArgs("projectbluefin/utah-packages", 892, nil) + pv, err := previewOp(t, WriteOpRepositoryItemDelegate, args, &boardProvider{t: t}) + if err != nil { + t.Fatal(err) + } + body := pv.Request.Body.(map[string]any) + want := map[string]any{"type": "pr", "no_merge": true, "reason": "contributor-lane:review", "caption": "review pending", "sentinel_reason": "", "head": "abc123"} + if jsonString(body) != jsonString(want) || !strings.HasSuffix(pv.Request.Path, "/decide-delegated") { + t.Fatalf("request = %s %s", pv.Request.Path, jsonString(body)) + } + if !strings.Contains(strings.Join(pv.Effects, " "), "Never merges") { + t.Fatalf("effects = %v", pv.Effects) + } + if err := rejectUnpersistablePreview(WriteOpRepositoryItemDelegate, args, pv); err != nil { + t.Fatalf("preview cannot be stored for confirmation: %v", err) + } + // The provider-less re-check still sends no_merge. + op, _ := DefaultWriteRegistry().Get(WriteOpRepositoryItemDelegate) + bare, err := op.Preview(context.Background(), itemArgs("projectbluefin/utah-packages", 892, nil)) + if err != nil || bare.Request.Body.(map[string]any)["no_merge"] != true { + t.Fatalf("bare preview = %+v err=%v", bare.Request, err) + } +} + +func TestItemDelegateNestedPRsAndRerun(t *testing.T) { + p := &boardProvider{t: t} + pv, err := previewOp(t, WriteOpRepositoryItemDelegate, itemArgs("projectbluefin/utah-packages", 488, map[string]any{"prs": []any{float64(892), float64(893)}, "rerun": true}), p) + if err != nil { + t.Fatal(err) + } + body := pv.Request.Body.(map[string]any) + if jsonString(body["prs"]) != "[892,893]" || body["force"] != true || body["type"] != "issue" { + t.Fatalf("body = %s", jsonString(body)) + } + for _, tc := range []struct { + args map[string]any + want string + }{ + {itemArgs("projectbluefin/utah-packages", 488, map[string]any{"prs": []any{float64(892)}}), "two or more"}, + {itemArgs("projectbluefin/utah-packages", 488, map[string]any{"prs": []any{1.5, float64(2)}}), "positive integers"}, + {itemArgs("projectbluefin/utah-packages", 892, map[string]any{"prs": []any{float64(1), float64(2)}}), "pull request"}, + } { + if _, err := previewOp(t, WriteOpRepositoryItemDelegate, tc.args, p); err == nil || !strings.Contains(err.Error(), tc.want) { + t.Fatalf("args %v: err = %v", tc.args, err) + } + } +} + +func TestBoardReadFailureNeedsExplicitType(t *testing.T) { + p := &boardProvider{t: t, err: errors.New("stage tracker unavailable")} + if _, err := previewOp(t, WriteOpRepositoryItemDelegate, itemArgs("projectbluefin/chairlift", 639, nil), p); err == nil || !strings.Contains(err.Error(), "type is required") { + t.Fatalf("err = %v", err) + } + pv, err := previewOp(t, WriteOpRepositoryItemDelegate, itemArgs("projectbluefin/chairlift", 639, map[string]any{"type": "issue"}), p) + if err != nil || pv.Details["on_board"] != "unknown" || !strings.Contains(strings.Join(pv.Effects, " "), "could not be read") { + t.Fatalf("explicit type: %+v %v err=%v", pv.Details, pv.Effects, err) + } +} + +// Before its first snapshot the endpoint answers {"status":"initializing"}: +// the read tool says so instead of reporting an empty board, and a preview +// says the board could not be read instead of "not on the board". +func TestStageTrackerNotBuiltYet(t *testing.T) { + got, err := StageTrackerReadResult(map[string]any{"status": "initializing"}, map[string]any{}) + if err != nil { + t.Fatal(err) + } + r, ok := got.(RefusalData) + if !ok || r.Kind != RefusalKindBoardUnavailable || !strings.Contains(r.Reason, "initializing") { + t.Fatalf("result = %#v", got) + } + empty := readBoardFrom(t, map[string]any{"items": []any{}, "stages": []any{}}, map[string]any{}) + if empty["matched"] != 0 { + t.Fatalf("a real empty board is still a board: %#v", empty) + } + p := initializingProvider{} + pv, err := previewOp(t, WriteOpRepositoryItemBlockerRecheck, itemArgs("projectbluefin/chairlift", 639, nil), p) + if err != nil || pv.Details["on_board"] != "unknown" { + t.Fatalf("preview = %+v err=%v", pv.Details, err) + } + if _, err := previewOp(t, WriteOpRepositoryItemDecision, itemArgs("projectbluefin/chairlift", 639, map[string]any{"decision": "approve"}), p); err == nil || !strings.Contains(err.Error(), "cannot be read") { + t.Fatalf("decision without type on an unreadable board: err = %v", err) + } +} + +type initializingProvider struct{} + +func (initializingProvider) Read(_ context.Context, _ string, args map[string]any) (any, error) { + return StageTrackerReadResult(map[string]any{"status": "initializing"}, args) +} + +func readBoardFrom(t *testing.T, data map[string]any, args map[string]any) map[string]any { + t.Helper() + got, err := StageTrackerReadResult(data, args) + if err != nil { + t.Fatal(err) + } + out, ok := got.(map[string]any) + if !ok { + t.Fatalf("result = %#v", got) + } + return out +} + +func TestDelegatedDecisionStatusPath(t *testing.T) { + path, err := DelegatedDecisionStatusPath(itemArgs("projectbluefin/chair lift", 7, nil)) + if err != nil || path != "/api/repos/projectbluefin/chair%20lift/items/7/decide-delegated" { + t.Fatalf("path = %q err=%v", path, err) + } + if _, err := DelegatedDecisionStatusPath(map[string]any{"owner": "o", "repo": "r"}); err == nil { + t.Fatal("missing number accepted") + } +} + +type recordingWriter struct{ reqs []WriteRequest } + +func (w *recordingWriter) ExecuteWrite(_ context.Context, req WriteRequest) (any, error) { + w.reqs = append(w.reqs, req) + return map[string]any{"ok": true}, nil +} + +// A confirmation runs as the actor that previewed it: another caller's +// confirm is refused and leaves it usable by its owner. +func TestConfirmationIsBoundToThePreviewingActor(t *testing.T) { + store := NewMemoryPendingStore() + writer := &recordingWriter{} + now := time.Now().UTC() + as := func(actor string) *Handler { + return NewHandler(nil, WithWritesEnabled(true), WithPendingStore(store), WithWriteClient(writer), WithActor(actor), WithClock(func() time.Time { return now })) + } + res, err := as("alice").PreviewWrite(context.Background(), map[string]any{"operation": WriteOpRepositoryRescan, "args": map[string]any{}}) + if err != nil { + t.Fatal(err) + } + id := res.(map[string]any)["confirmation_id"].(string) + if _, err := as("bob").ConfirmWrite(context.Background(), map[string]any{"confirmation_id": id}); !errors.Is(err, ErrConfirmationActor) { + t.Fatalf("bob's confirm err = %v", err) + } + if _, err := as("").ConfirmWrite(context.Background(), map[string]any{"confirmation_id": id}); !errors.Is(err, ErrConfirmationActor) { + t.Fatalf("anonymous confirm err = %v", err) + } + if len(writer.reqs) != 0 { + t.Fatalf("a refused confirm wrote: %v", writer.reqs) + } + if _, err := as("alice").ConfirmWrite(context.Background(), map[string]any{"confirmation_id": id}); err != nil { + t.Fatalf("alice's confirm err = %v", err) + } + if len(writer.reqs) != 1 || writer.reqs[0].Path != "/api/repos/rescan" { + t.Fatalf("writes = %v", writer.reqs) + } +} + +func TestPendingActorPersists(t *testing.T) { + store := NewFilePendingStore(t.TempDir() + "/pending.json") + if err := store.Put(context.Background(), PendingConfirmation{ID: "a", Actor: "alice", Hive: "h", ExpiresAt: time.Now().Add(time.Minute)}); err != nil { + t.Fatal(err) + } + got, err := store.Take(context.Background(), "a") + if err != nil || got.Actor != "alice" { + t.Fatalf("got %+v err=%v", got, err) + } +} + +// The rescan handler never queues a second scan: a running or just-finished +// one answers in-progress or debounced (api_repos_rescan.go), so the preview +// must not promise a queued rescan. +func TestRescanPreviewDoesNotPromiseAQueuedRescan(t *testing.T) { + pv, err := previewOp(t, WriteOpRepositoryRescan, map[string]any{}, &boardProvider{t: t}) + if err != nil { + t.Fatal(err) + } + effects := strings.Join(pv.Effects, " ") + if strings.Contains(effects, "the next one is queued") || !strings.Contains(effects, "no rescan is queued") || !strings.Contains(effects, "debounced") { + t.Fatalf("rescan preview effects = %q", effects) + } +} diff --git a/src/pkg/adminmcp/write_contract.go b/src/pkg/adminmcp/write_contract.go index f193c0473d..2f9e34a270 100644 --- a/src/pkg/adminmcp/write_contract.go +++ b/src/pkg/adminmcp/write_contract.go @@ -33,6 +33,7 @@ var ( ErrWritesDisabled = errors.New("admin MCP writes are disabled") ErrConfirmationExpired = errors.New("admin MCP confirmation expired") ErrConfirmationMissing = errors.New("admin MCP confirmation not found") + ErrConfirmationActor = errors.New("admin MCP confirmation was previewed by another caller; preview it again yourself") ) type WriteClient interface { @@ -123,6 +124,7 @@ type PendingConfirmation struct { Args map[string]any `json:"args"` Preview WritePreview `json:"preview"` Hive string `json:"hive"` + Actor string `json:"actor,omitempty"` CreatedAt time.Time `json:"created_at"` ExpiresAt time.Time `json:"expires_at"` } diff --git a/src/pkg/dashboard/admin_mcp.go b/src/pkg/dashboard/admin_mcp.go index e9f97aff18..f20b460402 100644 --- a/src/pkg/dashboard/admin_mcp.go +++ b/src/pkg/dashboard/admin_mcp.go @@ -15,6 +15,7 @@ import ( "time" "github.com/hivecommons/hive/pkg/adminmcp" + "github.com/hivecommons/hive/pkg/config" ) type dashboardAdminMCPProvider struct { @@ -70,27 +71,27 @@ func (s *Server) handleAdminMCP(w http.ResponseWriter, r *http.Request) { } adminmcp.NewHandler(provider, adminmcp.WithWritesEnabled(adminMCPWritesEnabled()), - adminmcp.WithWritesUnavailable(s.adminMCPWritesUnavailableReason(provider.authorization)), + adminmcp.WithWritesUnavailable(s.adminMCPWritesUnavailableReason(provider)), + adminmcp.WithActor(provider.user), adminmcp.WithPendingStore(adminmcp.NewFilePendingStore(adminMCPPendingPath())), adminmcp.WithHiveID("dashboard"), ).ServeHTTP(w, r) } // adminMCPWritesUnavailableReason reports why a confirmed write could not -// authenticate for this caller. ExecuteWrite re-enters authenticate carrying -// only the caller's Authorization header (the write contract never forwards -// identity headers), so a caller admitted by session, hub proof or the internal -// header would preview successfully and then get 401 on confirm. -func (s *Server) adminMCPWritesUnavailableReason(authorization string) string { - directRoute := s.directRouteAuthzEnabled() - if s.authToken == "" && !directRoute { - return "" - } - if directRoute { - return "this spoke enforces per-user direct-route authorization, which refuses the shared dashboard token that admin MCP writes authenticate with" +// succeed for this caller. A confirmed write runs as the identity this hive +// verified on the request (adminMCPWriteRequest), so it needs one, with a role +// that may change things; a read-only caller is told so up front instead of +// previewing a write every endpoint would refuse. +func (s *Server) adminMCPWritesUnavailableReason(p dashboardAdminMCPProvider) string { + if strings.TrimSpace(p.user) == "" || strings.TrimSpace(p.role) == "" { + if s.authToken == "" && !s.directRouteAuthzEnabled() { + return "" + } + return "this request carries no identity the hive verified, so a confirmed write would have no one to run as" } - if !secureCompare(strings.TrimSpace(authorization), "Bearer "+s.authToken) { - return "admin MCP writes re-authenticate with the dashboard token (Authorization: Bearer); this request was admitted another way (session, hub proxy or internal header), so a confirmed write would be refused with 401" + if !config.RoleAtLeast(p.role, config.RoleReadWrite) { + return "your role on this hive (" + p.role + ") is read-only, so changes are not allowed" } return "" } @@ -119,6 +120,20 @@ func (p dashboardAdminMCPProvider) Read(_ context.Context, tool string, args map if adminmcp.DiagTool(tool) { return p.readDiag(tool, args) } + if tool == adminmcp.ToolStageTrackerRead { + data, err := p.get(tool, adminmcp.StageTrackerReadPath()) + if err != nil { + return nil, err + } + return adminmcp.StageTrackerReadResult(data, args) + } + if tool == adminmcp.ToolDelegatedDecisionStatus { + path, err := adminmcp.DelegatedDecisionStatusPath(args) + if err != nil { + return nil, err + } + return p.get(tool, path) + } if tool == adminmcp.ToolSettingsRead { // An unknown section or a missing agent is refused with its reason. path, err := adminmcp.SettingsReadPath(args) @@ -268,10 +283,7 @@ func (p dashboardAdminMCPProvider) ExecuteWrite(_ context.Context, req adminmcp. if req.Body != nil { httpReq.Header.Set("Content-Type", "application/json") } - if strings.TrimSpace(p.authorization) != "" { - httpReq.Header.Set("Authorization", p.authorization) - } - p.server.authenticate(p.server.roleEnforcement(p.server.securityHeaders(p.server.mux))).ServeHTTP(rec, httpReq) + p.adminMCPWriteRequest(httpReq).ServeHTTP(rec, httpReq) status := rec.statusCode() if status < http.StatusOK || status >= http.StatusMultipleChoices { body := rec.bodyBytes() @@ -295,6 +307,34 @@ func (p dashboardAdminMCPProvider) ExecuteWrite(_ context.Context, req adminmcp. return data, nil } +// adminMCPWriteRequest prepares a confirmed write to run as the caller and +// returns the handler chain to serve it. With no verified identity on the +// outer request (an open spoke, or a hand-built provider in a test) the write +// re-enters authenticate with the caller's Authorization header, as before. +// Otherwise it runs as the identity authenticate verified on the outer +// /api/admin/mcp request — the same user, role and verified-owner marker the +// read tools already carry — so a hub-proxied or session caller can write, +// every role check sees that caller, and the write is attributed to them +// rather than to the configured owner. authenticate is not re-entered: +// it strips identity headers by design, and the identity here is the one it +// already verified, never one the client asserted (inbound copies were +// stripped before the outer request reached this handler). +func (p dashboardAdminMCPProvider) adminMCPWriteRequest(req *http.Request) http.Handler { + inner := p.server.roleEnforcement(p.server.securityHeaders(p.server.mux)) + if strings.TrimSpace(p.user) == "" || strings.TrimSpace(p.role) == "" { + if strings.TrimSpace(p.authorization) != "" { + req.Header.Set("Authorization", p.authorization) + } + return p.server.authenticate(inner) + } + req.Header.Set("X-Hive-User", p.user) + req.Header.Set("X-Hive-Role", p.role) + if p.ownerVerified && isOwnerRole(p.role) { + req.Header.Set(ownerRoleVerifiedHeader, "true") + } + return inner +} + type writeRecorder interface { http.ResponseWriter statusCode() int diff --git a/src/pkg/dashboard/admin_mcp_activity_test.go b/src/pkg/dashboard/admin_mcp_activity_test.go new file mode 100644 index 0000000000..02affc71a8 --- /dev/null +++ b/src/pkg/dashboard/admin_mcp_activity_test.go @@ -0,0 +1,194 @@ +package dashboard + +import ( + "context" + "encoding/json" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/hivecommons/hive/pkg/adminmcp" + "github.com/hivecommons/hive/pkg/config" +) + +type mcpCaller func(body string) string + +// adminMCPAs returns a caller that posts JSON-RPC to the admin MCP endpoint +// through the full auth chain with hdr set, and returns the tool text (or +// the raw body when the call failed). +func adminMCPAs(t *testing.T, h http.Handler, hdr map[string]string) mcpCaller { + t.Helper() + return func(body string) string { + t.Helper() + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, adminmcp.EndpointPath, strings.NewReader(body)) + for k, v := range hdr { + req.Header.Set(k, v) + } + h.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("admin MCP status = %d body=%s", rec.Code, rec.Body.String()) + } + var resp struct { + Result struct { + Content []struct { + Text string `json:"text"` + } `json:"content"` + } `json:"result"` + } + if json.Unmarshal(rec.Body.Bytes(), &resp) == nil && len(resp.Result.Content) == 1 { + return resp.Result.Content[0].Text + } + return rec.Body.String() + } +} + +func confirmationID(t *testing.T, text string) string { + t.Helper() + var out struct { + Data struct { + ID string `json:"confirmation_id"` + } `json:"data"` + } + if err := json.Unmarshal([]byte(text), &out); err != nil || out.Data.ID == "" { + t.Fatalf("no confirmation in %s", text) + } + return out.Data.ID +} + +const rescanPreview = `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"write_preview","arguments":{"operation":"repository.rescan","args":{}}}}` + +func rescanConfirm(id string) string { + return `{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"write_confirm","arguments":{"confirmation_id":"` + id + `"}}}` +} + +// A hub-proxied caller (the hub's proof plus its identity headers) writes as +// that caller: the endpoint sees their login and role, not the configured +// owner, and only they can confirm what they previewed. +func TestAdminMCPWritesRunAsVerifiedCaller(t *testing.T) { + t.Setenv("HIVE_ADMIN_MCP_ENABLE_WRITES", "1") + t.Setenv("HIVE_ADMIN_MCP_PENDING_FILE", t.TempDir()+"/pending.json") + s := NewServerWithAuth(0, "secret", slog.New(slog.NewTextHandler(io.Discard, nil))) + var seen []string + s.mux.HandleFunc("POST /api/repos/rescan", func(w http.ResponseWriter, r *http.Request) { + seen = append(seen, r.Header.Get("X-Hive-User")+"/"+r.Header.Get("X-Hive-Role")+"/"+r.Header.Get(ownerRoleVerifiedHeader)) + _ = json.NewEncoder(w).Encode(map[string]any{"status": "started"}) + }) + h := s.authenticate(s.roleEnforcement(s.securityHeaders(s.mux))) + hub := func(user, role string) mcpCaller { + return adminMCPAs(t, h, map[string]string{"X-Hive-User": user, "X-Hive-Role": role, proxyAuthHeader: "secret"}) + } + alice, bob := hub("alice", config.RoleReadWrite), hub("bob", config.RoleReadWrite) + + id := confirmationID(t, alice(rescanPreview)) + if got := bob(rescanConfirm(id)); !strings.Contains(got, "previewed by another caller") { + t.Fatalf("bob confirmed alice's write: %s", got) + } + if got := alice(rescanConfirm(id)); !strings.Contains(got, `"write_result"`) { + t.Fatalf("alice's confirm = %s", got) + } + if len(seen) != 1 || seen[0] != "alice/"+config.RoleReadWrite+"/" { + t.Fatalf("write ran as %v, want alice at her own role, unverified as owner", seen) + } + + // The dashboard token still writes as the configured owner identity. + bearer := adminMCPAs(t, h, map[string]string{"Authorization": "Bearer secret"}) + if got := bearer(rescanConfirm(confirmationID(t, bearer(rescanPreview)))); !strings.Contains(got, `"write_result"`) { + t.Fatalf("bearer confirm = %s", got) + } + if len(seen) != 2 || seen[1] != dashboardFallbackOwnerUser+"/"+config.RoleOwner+"/true" { + t.Fatalf("bearer write ran as %v", seen) + } + + // Admitted through the internal header: previously refused up front. + internal := adminMCPAs(t, h, map[string]string{"X-Hive-Internal": "secret"}) + if got := internal(rescanConfirm(confirmationID(t, internal(rescanPreview)))); !strings.Contains(got, `"write_result"`) { + t.Fatalf("internal confirm = %s", got) + } +} + +func TestAdminMCPWritesUnavailableReason(t *testing.T) { + s := NewServerWithAuth(0, "secret", slog.New(slog.NewTextHandler(io.Discard, nil))) + for _, tc := range []struct { + name string + p dashboardAdminMCPProvider + want string + }{ + {"read-write", dashboardAdminMCPProvider{user: "alice", role: config.RoleReadWrite}, ""}, + {"owner", dashboardAdminMCPProvider{user: "owner", role: config.RoleOwner}, ""}, + {"read-only", dashboardAdminMCPProvider{user: "carol", role: "read"}, "read-only"}, + {"no identity", dashboardAdminMCPProvider{}, "no identity"}, + } { + t.Run(tc.name, func(t *testing.T) { + got := s.adminMCPWritesUnavailableReason(tc.p) + if (tc.want == "") != (got == "") || !strings.Contains(got, tc.want) { + t.Fatalf("reason = %q, want %q", got, tc.want) + } + }) + } + open := NewServerWithAuth(0, "", slog.New(slog.NewTextHandler(io.Discard, nil))) + if got := open.adminMCPWritesUnavailableReason(dashboardAdminMCPProvider{}); got != "" { + t.Fatalf("open spoke reason = %q", got) + } +} + +// The verified-owner marker rides along only when the outer request was +// verified as owner, never on a claimed role. +func TestAdminMCPWriteCarriesOwnerMarkerOnlyWhenVerified(t *testing.T) { + s := NewServerWithAuth(0, "secret", slog.New(slog.NewTextHandler(io.Discard, nil))) + var marker []string + s.mux.HandleFunc("POST /api/admin-mcp-test/who", func(w http.ResponseWriter, r *http.Request) { + marker = append(marker, r.Header.Get(ownerRoleVerifiedHeader)) + _ = json.NewEncoder(w).Encode(map[string]any{"ok": true}) + }) + for _, p := range []dashboardAdminMCPProvider{ + {server: s, user: "jo", role: config.RoleOwner, ownerVerified: true}, + {server: s, user: "jo", role: config.RoleOwner}, + {server: s, user: "jo", role: config.RoleReadWrite, ownerVerified: true}, + } { + if _, err := p.ExecuteWrite(context.Background(), adminmcp.WriteRequest{Method: http.MethodPost, Path: "/api/admin-mcp-test/who"}); err != nil { + t.Fatal(err) + } + } + if strings.Join(marker, ",") != "true,," { + t.Fatalf("owner markers = %v", marker) + } +} + +func TestAdminMCPStageTrackerRead(t *testing.T) { + s := NewServerWithAuth(0, "secret", slog.New(slog.NewTextHandler(io.Discard, nil))) + s.mux.HandleFunc("GET /api/stage-tracker", func(w http.ResponseWriter, r *http.Request) { + _, _ = io.WriteString(w, `{"stages":[{"number":40,"slug":"covered-by-pr","label":"Covered"}],"items":[ + {"repo":"o/r","number":488,"kind":"issue","title":"gimp","stage":40,"linked_prs":[{"number":892}],"history":[{}]}, + {"repo":"o/r","number":5,"kind":"issue","title":"other","stage":40}]}`) + }) + s.mux.HandleFunc("GET /api/repos/o/r/items/488/decide-delegated", func(w http.ResponseWriter, r *http.Request) { + _, _ = io.WriteString(w, `{"status":"done","requester":"`+r.Header.Get("X-Hive-User")+`"}`) + }) + p := dashboardAdminMCPProvider{server: s, user: "alice", role: config.RoleReadWrite} + got, err := p.Read(context.Background(), adminmcp.ToolStageTrackerRead, map[string]any{"q": "892"}) + if err != nil { + t.Fatal(err) + } + out := got.(map[string]any) + items := out["items"].([]any) + if out["matched"] != 1 || len(items) != 1 || items[0].(map[string]any)["number"] != float64(488) { + t.Fatalf("stage_tracker_read = %#v", out) + } + if _, ok := items[0].(map[string]any)["history"]; ok { + t.Fatal("summary view kept history") + } + status, err := p.Read(context.Background(), adminmcp.ToolDelegatedDecisionStatus, map[string]any{"owner": "o", "repo": "r", "number": float64(488)}) + if err != nil { + t.Fatal(err) + } + if m := status.(map[string]any); m["status"] != "done" || m["requester"] != "alice" { + t.Fatalf("delegated_decision_status = %#v", status) + } + if _, err := p.Read(context.Background(), adminmcp.ToolDelegatedDecisionStatus, map[string]any{"owner": "o"}); err == nil { + t.Fatal("delegated_decision_status without an item succeeded") + } +} diff --git a/src/pkg/dashboard/admin_mcp_approve_permission_test.go b/src/pkg/dashboard/admin_mcp_approve_permission_test.go new file mode 100644 index 0000000000..5a2a32e5bf --- /dev/null +++ b/src/pkg/dashboard/admin_mcp_approve_permission_test.go @@ -0,0 +1,47 @@ +package dashboard + +import ( + "strings" + "testing" + + "github.com/hivecommons/hive/pkg/config" +) + +// An approve sent through the admin MCP is held to the caller's own rights, +// exactly as the dashboard's Approve button is: the write runs as the +// verified caller and the decision route checks that caller's permission on +// the repository. A caller with read access is refused and nothing is +// written; a caller with write access approves, and the approval names them. +func TestAdminMCPApproveIsHeldToTheCallersRepoPermission(t *testing.T) { + t.Setenv("HIVE_ADMIN_MCP_ENABLE_WRITES", "1") + t.Setenv("HIVE_ADMIN_MCP_PENDING_FILE", t.TempDir()+"/pending.json") + mock := &repoItemDecisionMock{} + srv := newRepoItemDecisionServer(t, mock) + srv.authToken = "secret" + h := srv.authenticate(srv.roleEnforcement(srv.securityHeaders(srv.mux))) + hub := func(user string) mcpCaller { + return adminMCPAs(t, h, map[string]string{"X-Hive-User": user, "X-Hive-Role": config.RoleReadWrite, proxyAuthHeader: "secret"}) + } + const preview = `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"write_preview","arguments":{"operation":"repository.item_decision","args":{"owner":"testorg","repo":"testrepo","number":8,"type":"pr","decision":"approve"}}}}` + confirm := func(id string) string { + return `{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"write_confirm","arguments":{"confirmation_id":"` + id + `"}}}` + } + + reader := hub("reader") + got := reader(confirm(confirmationID(t, reader(preview)))) + if !strings.Contains(got, "write permission required") { + t.Fatalf("a read-only caller's approve = %s, want the decision route's permission refusal", got) + } + if len(mock.comments) != 0 || len(mock.reviews) != 0 { + t.Fatalf("a refused approve wrote to GitHub: comments=%q reviews=%v", mock.comments, mock.reviews) + } + + writer := hub("writer") + got = writer(confirm(confirmationID(t, writer(preview)))) + if !strings.Contains(got, `"write_result"`) || strings.Contains(got, "permission required") { + t.Fatalf("a writer's approve = %s", got) + } + if len(mock.comments) != 2 || !strings.HasPrefix(mock.comments[0], "/lgtm\n") || !strings.Contains(mock.comments[0], "@writer") { + t.Fatalf("the approval must be recorded as @writer: %q", mock.comments) + } +} diff --git a/src/pkg/dashboard/admin_mcp_test.go b/src/pkg/dashboard/admin_mcp_test.go index 2dcac85f08..5a7a791366 100644 --- a/src/pkg/dashboard/admin_mcp_test.go +++ b/src/pkg/dashboard/admin_mcp_test.go @@ -125,36 +125,6 @@ func TestAdminMCPAgentNudgeStatusReadPath(t *testing.T) { } } -func TestAdminMCPWritePreviewFailsFastWithoutDashboardBearer(t *testing.T) { - t.Setenv("HIVE_ADMIN_MCP_ENABLE_WRITES", "1") - t.Setenv("HIVE_ADMIN_MCP_PENDING_FILE", t.TempDir()+"/pending.json") - s := NewServerWithAuth(0, "secret", slog.New(slog.NewTextHandler(io.Discard, nil))) - h := s.authenticate(s.roleEnforcement(s.securityHeaders(s.mux))) - preview := `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"write_preview","arguments":{"operation":"agent.pause","args":{"agent":"scanner"}}}}` - - // Admitted as owner through the internal header, which ExecuteWrite does not - // forward: confirm would 401, so preview must refuse instead of minting a - // confirmation. - internal := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, adminmcp.EndpointPath, strings.NewReader(preview)) - req.Header.Set("X-Hive-Internal", "secret") - h.ServeHTTP(internal, req) - if internal.Code != http.StatusOK { - t.Fatalf("internal status = %d body=%s", internal.Code, internal.Body.String()) - } - if strings.Contains(internal.Body.String(), "confirmation_id") || !strings.Contains(internal.Body.String(), "Authorization: Bearer") { - t.Fatalf("preview without bearer = %s", internal.Body.String()) - } - - bearer := httptest.NewRecorder() - req = httptest.NewRequest(http.MethodPost, adminmcp.EndpointPath, strings.NewReader(preview)) - req.Header.Set("Authorization", "Bearer secret") - h.ServeHTTP(bearer, req) - if !strings.Contains(bearer.Body.String(), "confirmation_id") { - t.Fatalf("preview with bearer = %s", bearer.Body.String()) - } -} - func TestAdminMCPAdvisorRecordsMatchesREST(t *testing.T) { s := advisorTestServer(t) // provider.Read serves through s.mux, so the REST routes must be registered. diff --git a/src/pkg/dashboard/api_repo_item_decide_delegated.go b/src/pkg/dashboard/api_repo_item_decide_delegated.go index 40d1c9c75c..ff974004b7 100644 --- a/src/pkg/dashboard/api_repo_item_decide_delegated.go +++ b/src/pkg/dashboard/api_repo_item_decide_delegated.go @@ -93,6 +93,12 @@ type delegatedDecisionRequest struct { // Head is the PR head the tracker row showed; it only keys the // preview's plan cache, so a push asks GitHub afresh. Head string `json:"head,omitempty"` + // NoMerge decides without the merger role, so an approval is the + // `/lgtm` + `/approve` path and never an Approve review queued for + // auto-merge. Admin MCP always sends it (repository.item_delegate): + // queueing a merge is excluded there. It can only narrow what the + // caller's role allows. + NoMerge bool `json:"no_merge,omitempty"` } // delegatedDecisionJob is the wire shape of one job. @@ -279,7 +285,7 @@ func (s *Server) handleRepoItemDecideDelegated(w http.ResponseWriter, r *http.Re jsonResponse(w, snapshot) return } - mergerRole := config.RoleAtLeast(r.Header.Get("X-Hive-Role"), config.RoleMerger) && + mergerRole := !body.NoMerge && config.RoleAtLeast(r.Header.Get("X-Hive-Role"), config.RoleMerger) && (!isOwnerRole(r.Header.Get("X-Hive-Role")) || r.Header.Get(ownerRoleVerifiedHeader) == "true") run := func() { ctx := context.Background() diff --git a/src/pkg/dashboard/delegated_approval_ordering_test.go b/src/pkg/dashboard/delegated_approval_ordering_test.go index 4a675d215e..1de881b206 100644 --- a/src/pkg/dashboard/delegated_approval_ordering_test.go +++ b/src/pkg/dashboard/delegated_approval_ordering_test.go @@ -259,3 +259,30 @@ func TestDelegatedRejectedDecisionDoesNotRecordNativeApproval(t *testing.T) { t.Fatal("rejected decision recorded approval") } } + +// no_merge (admin MCP's repository.item_delegate) decides as a writer even +// for a merger: the approval is the /lgtm + /approve path, and no Approve +// review is recorded and queued for auto-merge. +func TestDelegatedNoMergeNeverQueuesApproval(t *testing.T) { + prev := repoItemDecisionChangeRequests + t.Cleanup(func() { repoItemDecisionChangeRequests = prev }) + path := filepath.Join(t.TempDir(), "approvals.json") + repoItemDecisionChangeRequests = func() review.HumanChangeRequestStore { return review.NewHumanChangeRequests(path) } + mock := &repoItemDecisionMock{} + s := newDelegatedServer(t, mock) + withDecider(s, &fakeDecider{err: errors.New("use deterministic default")}, true) + job := decodeDelegatedJob(t, postDelegated(t, s, 8, "writer", `{"type":"pr","no_merge":true}`, map[string]string{"X-Hive-Role": "merger"})) + if job.Status != delegatedJobStatusDone || job.Decision == nil || job.Decision.Verdict != delegatedecision.VerdictApprove { + t.Fatalf("job = %+v", job) + } + if job.ApprovalRecordedAt != nil { + t.Fatalf("no_merge recorded a native approval for auto-merge: %+v", job) + } + if _, ok := repoItemDecisionChangeRequests().For("testorg/testrepo", 8, delegatedOrderingHead); ok { + t.Fatal("no_merge stored an approval") + } + all := strings.Join(mock.comments, "\n") + if !strings.Contains(all, "/lgtm") || !strings.Contains(all, "/approve") { + t.Fatalf("no_merge approval did not take the /lgtm + /approve path: %v", mock.comments) + } +}