diff --git a/changelog.d/added-adminmcp-cadences-writeback-kinds.md b/changelog.d/added-adminmcp-cadences-writeback-kinds.md new file mode 100644 index 0000000000..d03f1099ee --- /dev/null +++ b/changelog.d/added-adminmcp-cadences-writeback-kinds.md @@ -0,0 +1 @@ +- An owner can now change an agent's per-mode cadences (`agent.cadences`) and the write-back gate's per-kind overrides (`writeback.kind_policy`) through admin MCP preview and confirm, the same settings the dashboard's agent Cadences and Settings → Features controls save. The cadence preview says when an agent would run more often and that the mode becomes operator-owned; the write-back preview sends every existing override with the change merged in, so the endpoint's whole-map replace keeps the kinds you did not name, and it names any kind that would write at a lower level or without the opt-in label. diff --git a/src/docs/admin-mcp.md b/src/docs/admin-mcp.md index eaaed09cb8..254969ef04 100644 --- a/src/docs/admin-mcp.md +++ b/src/docs/admin-mcp.md @@ -705,23 +705,24 @@ 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`, `agent.github_api_hourly_cap` | -| GitHub | `github.agent_api_hourly_cap` | -| Fleet | `fleet.autonomy_level` | -| Plans | `plan.propose`, `plan.approve`, `plan.reject` | -| Governor | `governor.feature_settings`, `governor.thresholds`, `governor.threshold_scaling` | -| Issue filter | `project.issue_filter` | -| Sentinel | `sentinel.settings` | -| Merge settings | `auto_merge.update` | -| Let hive decide | `decisions.delegate_settings` | -| 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` | +| Area | Operations | +| ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Agents | `agent.pause`, `agent.resume`, `agent.nudge`, `agent.restart`, `agent.add`, `agent.remove`, `agent.model`, `agent.backend`, `agent.effort`, `agent.interaction_tier`, `agent.github_api_hourly_cap`, `agent.cadences` | +| GitHub | `github.agent_api_hourly_cap` | +| Fleet | `fleet.autonomy_level` | +| Plans | `plan.propose`, `plan.approve`, `plan.reject` | +| Governor | `governor.feature_settings`, `governor.thresholds`, `governor.threshold_scaling` | +| Issue filter | `project.issue_filter` | +| Sentinel | `sentinel.settings` | +| Write-back | `writeback.kind_policy` | +| Merge settings | `auto_merge.update` | +| Let hive decide | `decisions.delegate_settings` | +| 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 two GitHub API cap operations change the API proxy's per-agent hourly cap, the same settings as the dashboard's Forge App and agent General @@ -795,6 +796,59 @@ Neither operation itself adds or removes a label, approves, or merges anything. Turning reporter trust on does make later scans mark each held issue as waiting for triage, with a label and a one-time comment. +`agent.cadences` and `writeback.kind_policy` change two more settings an +owner otherwise changes on the dashboard, through the endpoints those +controls save with. Only the hive's owner can confirm them: the endpoint +refuses any other role. + +- `agent.cadences` sets one agent's cadence in one or more governor modes, + through `PUT /api/config/agent/{name}/cadences` (the agent's Cadences + settings). It takes `agent` and `modes`, an object with any of `surge`, + `busy`, `quiet` and `idle`, each a duration such as `1h` or `90m`, or + `pause`. Modes you do not name keep their cadence. A mode the hive does not + configure is refused, because the endpoint would skip it. Time-of-day and + cron schedules are still set on the dashboard. Each mode it sets becomes + operator-owned (`governor.cadence_owners`), as a dashboard edit does, so a + later ACMM level change (`fleet.autonomy_level`) or pack apply no longer + resets it to the pack default. The preview says so. +- `writeback.kind_policy` changes the write-back gate's per-kind overrides + (`writeback.kinds.`: `min_level`, `require_label`, + `unlabeled_min_level` and `own_only`), through + `PUT /api/config/governor/features` (Settings → Features). `kinds` maps a + kind to the fields to set, with `null` for a field dropping it, or to `null` + to remove that kind's override. An unknown kind or field is refused. That + endpoint replaces the whole override map it is sent, so the preview reads + the current overrides and sends them all with the change merged in: kinds + you do not name keep their override. + +For example, to run the scanner hourly when the queue is busy or surging, and +to let the stale-red branch refresh reach pull requests without the opt-in +label at L6: + +```json +{"operation": "agent.cadences", + "args": {"agent": "scanner", "modes": {"surge": "1h", "busy": "1h"}}} +``` + +```json +{"operation": "writeback.kind_policy", + "args": {"kinds": {"base_refresh": {"unlabeled_min_level": 6}}}} +``` + +The preview shows each mode or kind before and after. It names as widening a +cadence that gets shorter ("scanner runs more often in surge: more spend"), +and a kind that would write at a lower level, without the opt-in label, or on +items the hive did not author. If the agent's cadences or the overrides +change between the preview and the confirm, the confirm is refused; preview +again. Neither operation kicks an agent, labels, approves or merges anything +itself. + +The dashboard's write-back kind table edits only `min_level` and +`require_label`, and saving an edit there rewrites every kind's override from +the table, which drops `unlabeled_min_level` and `own_only`. The +`writeback.kind_policy` preview warns when an override it writes carries +either. + `auto_merge.update` changes merge settings, the same settings as the dashboard's merge controls, through `PATCH /api/config/auto-merge`. It is owner only. diff --git a/src/docs/api-reference.md b/src/docs/api-reference.md index 63fde579bc..2b0fa6fa70 100644 --- a/src/docs/api-reference.md +++ b/src/docs/api-reference.md @@ -139,7 +139,7 @@ History point limits, timestamp cutoffs, incremental cost reads and ETag/304 beh | `GET` | `/api/config/agent/{name}` | Dashboard auth/session | Agent Config Get | `pkg/dashboard/api.go:207` | | `PUT` | `/api/config/agent/{name}/general` | Owner only | Agent Config General | `pkg/dashboard/api.go:208` | -| `PUT` | `/api/config/agent/{name}/cadences` | Owner only | Agent Config Cadences | `pkg/dashboard/api.go:209` | +| `PUT` | `/api/config/agent/{name}/cadences` | Owner only | Agent Config Cadences; each mode sent becomes operator-owned (`governor.cadence_owners`). Wrapped by the admin MCP `agent.cadences` operation | `pkg/dashboard/api.go:209` | | `PUT` | `/api/config/agent/{name}/models` | Owner only | Agent Config Models | `pkg/dashboard/api.go:210` | | `PUT` | `/api/config/agent/{name}/pipeline` | Owner only | Agent Config Pipeline | `pkg/dashboard/api.go:211` | | `PUT` | `/api/config/agent/{name}/hooks` | Owner only | Agent Config Hooks | `pkg/dashboard/api.go:212` | @@ -212,7 +212,7 @@ History point limits, timestamp cutoffs, incremental cost reads and ETag/304 beh | `PUT` | `/api/config/write-surface` | Owner only | Replace the lane write allowlist; `{"allowlist": {}}` clears it; unknown operation or bad lane name is a 400 with nothing changed | `pkg/dashboard/api.go:566` | | `GET` | `/api/config/review` | Dashboard auth/session | Review Config Get | `pkg/dashboard/api.go:253` | | `PUT` | `/api/config/review` | Owner only | Review Config Set | `pkg/dashboard/api.go:256` | -| `PUT` | `/api/config/governor/features` | Owner only | Governor Features | `pkg/dashboard/api.go:262` | +| `PUT` | `/api/config/governor/features` | Owner only | Governor Features; `writebackKinds` replaces the whole `writeback.kinds` map (a kind sent as `null` or `{}` is dropped). Wrapped by the admin MCP `governor.feature_settings` and `writeback.kind_policy` operations | `pkg/dashboard/api.go:262` | | `GET` | `/api/config/governor/general-advanced` | Owner only | Governor General Advanced Get | `pkg/dashboard/api.go:263` | | `PUT` | `/api/config/governor/general-advanced` | Owner only | Governor General Advanced Set | `pkg/dashboard/api.go:264` | | `GET` | `/api/config/auto-merge` | Owner only | Auto-Merge Config Get | `pkg/dashboard/api.go:268` | diff --git a/src/docs/api-reference/configuration.md b/src/docs/api-reference/configuration.md index 0f0ce7fbd8..b821927470 100644 --- a/src/docs/api-reference/configuration.md +++ b/src/docs/api-reference/configuration.md @@ -24,7 +24,7 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `GET` | `/api/config/agent/{name}` | Dashboard auth/session | Agent Config Get; `general` carries the API proxy's GitHub API hourly cap: `githubApiHourlyCap` (this agent's `agents..github_api_hourly_cap`, `null` = inherit), `githubApiHourlyCapEffective` (the cap the proxy applies now; 0 = no cap), `githubApiHourlyCapFleet` (the fleet default) and `githubApiHourlyCapBase` (the base agent of a replica or review head, else empty) | `pkg/dashboard/api.go:207` | | `PUT` | `/api/config/agent/{name}/general` | Owner only | Agent Config General; `githubApiHourlyCap` sets `agents..github_api_hourly_cap` (a whole number, 0 = no cap, `null` = inherit the fleet default), applies to the proxy without a restart and to the agent's replicas and review heads; refused (400) on a replica or review head. Audited as `config_agent_general` with the old and new cap | `pkg/dashboard/api.go:208` | -| `PUT` | `/api/config/agent/{name}/cadences` | Owner only | Agent Config Cadences | `pkg/dashboard/api.go:209` | +| `PUT` | `/api/config/agent/{name}/cadences` | Owner only | Agent Config Cadences; each mode sent becomes operator-owned (`governor.cadence_owners`). Wrapped by the admin MCP `agent.cadences` operation | `pkg/dashboard/api.go:209` | | `PUT` | `/api/config/agent/{name}/models` | Owner only | Agent Config Models | `pkg/dashboard/api.go:210` | | `PUT` | `/api/config/agent/{name}/pipeline` | Owner only | Agent Config Pipeline | `pkg/dashboard/api.go:211` | | `PUT` | `/api/config/agent/{name}/hooks` | Owner only | Agent Config Hooks | `pkg/dashboard/api.go:212` | @@ -98,7 +98,7 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `PUT` | `/api/config/write-surface` | Owner only | Replace the lane write allowlist; `{"allowlist": {}}` clears it; unknown operation or bad lane name is a 400 with nothing changed | `pkg/dashboard/api.go:566` | | `GET` | `/api/config/review` | Dashboard auth/session | Review Config Get | `pkg/dashboard/api.go:253` | | `PUT` | `/api/config/review` | Owner only | Review Config Set | `pkg/dashboard/api.go:256` | -| `PUT` | `/api/config/governor/features` | Owner only | Governor Features | `pkg/dashboard/api.go:262` | +| `PUT` | `/api/config/governor/features` | Owner only | Governor Features; `writebackKinds` replaces the whole `writeback.kinds` map (a kind sent as `null` or `{}` is dropped). Wrapped by the admin MCP `governor.feature_settings` and `writeback.kind_policy` operations | `pkg/dashboard/api.go:262` | | `GET` | `/api/config/governor/general-advanced` | Owner only | Governor General Advanced Get | `pkg/dashboard/api.go:263` | | `PUT` | `/api/config/governor/general-advanced` | Owner only | Governor General Advanced Set | `pkg/dashboard/api.go:264` | | `GET` | `/api/config/auto-merge` | Owner only | Auto-Merge Config Get | `pkg/dashboard/api.go:268` | diff --git a/src/docs/design/admin-mcp.md b/src/docs/design/admin-mcp.md index 0ace0f0865..efea02189a 100644 --- a/src/docs/design/admin-mcp.md +++ b/src/docs/design/admin-mcp.md @@ -635,6 +635,16 @@ Phase 5 registers the fleet-level write operations under that contract: (`ErrConfirmationStale`) instead of being overwritten. A change that admits more issues without triage, or that makes Sentinel flag fewer pull requests, is disclosed as widening, and the Sentinel disclosure names the pull requests that would no longer be held. +- `agent.cadences` and `writeback.kind_policy` wrap `PUT /api/config/agent/{name}/cadences` and + `PUT /api/config/governor/features` (its `writebackKinds` field) for two settings that had no + operation: one agent's per-mode cadences and the write-back gate's per-kind overrides. They use + the same `ConfirmGuard` stale-preview check. The cadence endpoint claims operator ownership of + every mode it is sent (`governor.cadence_owners`), so the op sends only the modes that change + and its preview says each becomes operator-owned, which keeps a later pack apply from resetting + it; a shorter cadence is disclosed as more spend. The Features endpoint replaces the whole + `writebackKinds` map, so the op reads the current overrides and sends them all with the change + merged in, and discloses a kind whose resolved policy (`writeback.Config.Policy`) would write at + a lower level, without the opt-in label, or on items the hive did not author. - `auto_merge.update` wraps `PATCH /api/config/auto-merge`, the endpoint behind the dashboard's merge settings. That endpoint replaces every list and map it is sent whole (`squash_only`, `require_current_base`, `human_merge_paths`, the native merge queue's repos and bases, the diff --git a/src/docs/operator-reference/sweeps-and-operations.md b/src/docs/operator-reference/sweeps-and-operations.md index aad55daa6d..6ca64339da 100644 --- a/src/docs/operator-reference/sweeps-and-operations.md +++ b/src/docs/operator-reference/sweeps-and-operations.md @@ -520,6 +520,10 @@ The gate is per write-back *kind*. Each kind has a minimum ACMM level and whether the review opt-in label (`review.require_labels`, default `hive-review`) is required on the PR; both are overridable per kind under `writeback.kinds..{min_level, require_label, unlabeled_min_level}`. +An owner changes these under Settings → Features, or with the admin MCP +operation `writeback.kind_policy`, which also sets `unlabeled_min_level` and +`own_only` and keeps the overrides of kinds it does not name +([admin-mcp.md](../admin-mcp.md#registered-operations)). The rationale for each default is the same question: does the hive have, at that level, the power the write-back exists to govern? diff --git a/src/pkg/adminmcp/tools_agent_ops.go b/src/pkg/adminmcp/tools_agent_ops.go index cf282741dc..23ab843e49 100644 --- a/src/pkg/adminmcp/tools_agent_ops.go +++ b/src/pkg/adminmcp/tools_agent_ops.go @@ -35,6 +35,7 @@ func DefaultWriteOps() []WriteOp { ops = append(ops, configSurfaceWriteOps()...) ops = append(ops, autoMergeWriteOps()...) ops = append(ops, decisionsWriteOps()...) + ops = append(ops, cadenceWritebackWriteOps()...) return append(ops, governorWriteOps()...) } diff --git a/src/pkg/adminmcp/tools_cadence_writeback_ops.go b/src/pkg/adminmcp/tools_cadence_writeback_ops.go new file mode 100644 index 0000000000..de89806b89 --- /dev/null +++ b/src/pkg/adminmcp/tools_cadence_writeback_ops.go @@ -0,0 +1,768 @@ +package adminmcp + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/url" + "sort" + "strings" + "time" + + "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/writeback" +) + +// Write operations for two settings an owner changes on the dashboard that +// had no admin MCP operation: one agent's per-mode cadences +// (governor.modes.., the agent's Cadences settings) and the +// write-back gate's per-kind overrides (writeback.kinds., Settings → +// Features). Each wraps exactly the endpoint the dashboard saves through, so +// the endpoint's owner-only check, validation and audit entry apply unchanged. +// +// Both previews read the current values first, show each change before and +// after, and record a fingerprint of what they read +// (WritePreview.StateFingerprint); ConfirmGuard reads again at write_confirm, +// which refuses with ErrConfirmationStale when it no longer matches. +// +// The Features endpoint replaces the whole writebackKinds map it is sent, so +// writeback.kind_policy sends the current overrides with the change merged in: +// kinds the caller does not name keep their override. +const ( + WriteOpAgentCadences = "agent.cadences" + WriteOpWritebackKindPolicy = "writeback.kind_policy" +) + +func cadenceWritebackWriteOps() []WriteOp { + return []WriteOp{agentCadencesOp{}, writebackKindPolicyOp{}} +} + +type agentCadencesOp struct{} +type writebackKindPolicyOp struct{} + +// ---- agent.cadences --------------------------------------------------------- + +// agentCadenceModes are the governor modes an agent cadence is set for, in +// ladder order. +var agentCadenceModes = []string{"surge", "busy", "quiet", "idle"} + +// agentCadenceRequest is one requested cadence: seconds between kicks, 0 for +// pause. +type agentCadenceRequest struct { + seconds int64 + label string +} + +// agentCadenceSecondsLabel spells seconds the way the cadence endpoint stores +// them (formatCadenceDuration in pkg/dashboard). +func agentCadenceSecondsLabel(seconds int64) string { + switch { + case seconds <= 0: + return "pause" + case seconds%3600 == 0: + return fmt.Sprintf("%dh", seconds/3600) + case seconds%60 == 0: + return fmt.Sprintf("%dm", seconds/60) + default: + return fmt.Sprintf("%ds", seconds) + } +} + +func parseAgentCadenceRequest(raw any, field string) (agentCadenceRequest, error) { + s, ok := raw.(string) + if !ok { + return agentCadenceRequest{}, fmt.Errorf("%s must be a duration such as 1h or 90m, or pause", field) + } + s = strings.ToLower(strings.TrimSpace(s)) + var req agentCadenceRequest + switch s { + case "pause", "paused", "off": + req = agentCadenceRequest{seconds: 0, label: "pause"} + default: + d, err := time.ParseDuration(s) + if err != nil || d <= 0 { + return agentCadenceRequest{}, fmt.Errorf("%s: %q is not a positive duration such as 1h or 90m, or pause", field, s) + } + if d%time.Second != 0 { + return agentCadenceRequest{}, fmt.Errorf("%s: %q must be whole seconds", field, s) + } + secs := int64(d / time.Second) + req = agentCadenceRequest{seconds: secs, label: agentCadenceSecondsLabel(secs)} + } + // The endpoint's own check (Cadence.Validate), run on the value it will + // store. + if err := config.Cadence(req.label).Validate(); err != nil { + return agentCadenceRequest{}, fmt.Errorf("%s: %v", field, err) + } + return req, nil +} + +// parseAgentCadencesArgs returns the agent and the requested cadence per mode. +func parseAgentCadencesArgs(args map[string]any) (string, map[string]agentCadenceRequest, error) { + const where = WriteOpAgentCadences + if err := rejectUnknownKeys(args, where, "agent", "modes"); err != nil { + return "", nil, err + } + agent, err := requiredString(args, "agent") + if err != nil { + return "", nil, err + } + modes, err := objectArg(args, "modes", where) + if err != nil { + return "", nil, err + } + if len(modes) == 0 { + return "", nil, fmt.Errorf("%s.modes names no mode: give one or more of %s", where, strings.Join(agentCadenceModes, ", ")) + } + if err := rejectUnknownKeys(modes, where+".modes", agentCadenceModes...); err != nil { + return "", nil, err + } + out := map[string]agentCadenceRequest{} + for _, mode := range agentCadenceModes { + raw, present := modes[mode] + if !present { + continue + } + req, err := parseAgentCadenceRequest(raw, where+".modes."+mode) + if err != nil { + return "", nil, err + } + out[mode] = req + } + return agent, out, nil +} + +// agentCadenceCell is one mode's cadence as the agent's settings report it. +type agentCadenceCell struct { + kind string // unset, interval, continuous, schedule + seconds int64 // interval only; 0 is paused + label string +} + +func readAgentCadenceCell(raw any, present bool) agentCadenceCell { + if !present { + return agentCadenceCell{kind: "unset", label: "not set"} + } + if n, ok := numberArg(raw); ok { + return agentCadenceCell{kind: "interval", seconds: int64(n), label: agentCadenceSecondsLabel(int64(n))} + } + if s, ok := raw.(string); ok { + if strings.EqualFold(strings.TrimSpace(s), config.CadenceModeContinuous) { + return agentCadenceCell{kind: "continuous", label: config.CadenceModeContinuous} + } + return agentCadenceCell{kind: "schedule", label: s} + } + data, _ := json.Marshal(raw) + return agentCadenceCell{kind: "schedule", label: "schedule " + string(data)} +} + +// agentCadenceState is what the preview read. The exported fields are what +// the confirm fingerprints. +type agentCadenceState struct { + Cadences map[string]any `json:"cadences"` + Modes []string `json:"modes"` +} + +// readAgentCadenceState reads the agent's settings (settings_read section +// agent, GET /api/config/agent/{name}): its cadence per mode, and the modes +// this hive configures. +func readAgentCadenceState(ctx context.Context, provider Provider, agent string) (agentCadenceState, error) { + if provider == nil { + return agentCadenceState{}, fmt.Errorf("%s reads agent %s's current cadences first, and this connection cannot read them; nothing was previewed", WriteOpAgentCadences, agent) + } + data, err := provider.Read(ctx, ToolSettingsRead, map[string]any{"section": "agent", "agent": agent}) + if err != nil { + return agentCadenceState{}, fmt.Errorf("%s could not read agent %s's settings (settings_read section agent): %w; nothing was previewed", WriteOpAgentCadences, agent, err) + } + m, _ := data.(map[string]any) + if m == nil { + return agentCadenceState{}, fmt.Errorf("%s could not read agent %s's settings: settings_read section agent returned no object; nothing was previewed", WriteOpAgentCadences, agent) + } + raw, present := m["cadences"] + if !present { + return agentCadenceState{}, missingSetting("agent "+agent+"'s cadences", "cadences") + } + st := agentCadenceState{Cadences: map[string]any{}} + if cad, ok := raw.(map[string]any); ok { + st.Cadences = cad + } else if raw != nil { + return agentCadenceState{}, missingSetting("agent "+agent+"'s cadences", "cadences") + } + // The endpoint skips a mode the hive does not configure, so a mode this + // hive lacks is refused here instead of being silently dropped. models + // carries one key per configured mode. + models, ok := m["models"].(map[string]any) + if !ok { + return agentCadenceState{}, missingSetting("the hive's governor modes", "models") + } + for mode := range models { + st.Modes = append(st.Modes, mode) + } + sort.Strings(st.Modes) + return st, nil +} + +func (agentCadencesOp) Name() string { return WriteOpAgentCadences } +func (agentCadencesOp) Description() string { + return "Set one agent's cadence in one or more governor modes (governor.modes..: surge, busy, quiet, idle) through PUT /api/config/agent/{name}/cadences, the endpoint the agent's Cadences settings save through. Each mode takes a duration such as 1h or 90m, or pause; modes you do not name keep their cadence. The preview reads the current cadences, shows each mode before → after, and says when the agent would run more often (more spend). Each mode set becomes operator-owned, as a dashboard edit does, so a later ACMM level change or pack apply no longer resets it. write_confirm is refused if the agent's cadences changed since the preview. Owner only: the endpoint refuses any other role. Time-of-day and cron schedules stay on the dashboard." +} +func (agentCadencesOp) InputSchema() map[string]any { + modes := map[string]any{} + for _, m := range agentCadenceModes { + modes[m] = map[string]any{"type": "string", "description": "Time between kicks in " + m + " mode: a duration such as 15m, 1h or 90m, or pause."} + } + return map[string]any{"type": "object", "properties": map[string]any{ + "agent": map[string]any{"type": "string", "minLength": 1}, + "modes": map[string]any{"type": "object", "properties": modes, "additionalProperties": false}, + }, "required": []string{"agent", "modes"}, "additionalProperties": false} +} + +func agentCadencesPath(agent string) string { + return "/api/config/agent/" + url.PathEscape(agent) + "/cadences" +} + +// Preview without a provider checks the arguments and names the endpoint; +// write_preview always goes through PreviewWithProvider, and write_confirm +// uses this only to check the method and path. +func (agentCadencesOp) Preview(_ context.Context, args map[string]any) (WritePreview, error) { + agent, _, err := parseAgentCadencesArgs(args) + if err != nil { + return WritePreview{}, err + } + return unreadSettingsPreview(WriteOpAgentCadences, agent, agentCadencesPath(agent), "cadences of agent "+agent), nil +} + +// ConfirmGuard reads the agent's cadences again at write_confirm and returns +// their fingerprint, which must still match the preview's. +func (op agentCadencesOp) ConfirmGuard(ctx context.Context, args map[string]any, provider Provider) (string, error) { + return confirmGuardFingerprint(op.PreviewWithProvider(ctx, args, provider)) +} + +// PreviewWithProvider reads the agent's cadences, compares each named mode +// and discloses every mode where the agent would run more often. +func (agentCadencesOp) PreviewWithProvider(ctx context.Context, args map[string]any, provider Provider) (WritePreview, error) { + agent, req, err := parseAgentCadencesArgs(args) + if err != nil { + return WritePreview{}, err + } + st, err := readAgentCadenceState(ctx, provider, agent) + if err != nil { + return WritePreview{}, err + } + configured := map[string]bool{} + for _, m := range st.Modes { + configured[m] = true + } + body := map[string]any{} + var changes []settingChange + var widen, narrow, owned []string + for _, mode := range agentCadenceModes { + want, ok := req[mode] + if !ok { + continue + } + if !configured[mode] { + return WritePreview{}, fmt.Errorf("%s: this hive configures no %s mode (configured: %s), so the endpoint would skip it; nothing was previewed", WriteOpAgentCadences, mode, listLabel(st.Modes)) + } + raw, present := st.Cadences[mode] + before := readAgentCadenceCell(raw, present) + if before.kind == "interval" && before.seconds == want.seconds { + continue + } + body[mode] = want.seconds + owned = append(owned, mode) + c := settingChange{Field: mode, Before: before.label, After: want.label} + switch { + case want.seconds == 0: + c.Note = "paused: the governor no longer kicks " + agent + " on a cadence in " + mode + narrow = append(narrow, agent+" stops running on a cadence in "+mode) + case before.kind == "interval" && before.seconds == 0: + widen = append(widen, agent+" runs more often in "+mode+": more spend (every "+want.label+", was paused)") + case before.kind == "interval" && before.seconds > want.seconds: + widen = append(widen, agent+" runs more often in "+mode+": more spend (every "+want.label+", was every "+before.label+")") + case before.kind == "interval": + narrow = append(narrow, agent+" runs less often in "+mode+" (every "+want.label+", was every "+before.label+")") + case before.kind == "continuous": + narrow = append(narrow, agent+" runs every "+want.label+" in "+mode+" instead of continuously") + case before.kind == "unset": + widen = append(widen, agent+" runs more often in "+mode+": more spend (it had no cadence of its own there and now runs every "+want.label+")") + default: + widen = append(widen, agent+" runs more often in "+mode+": more spend (every "+want.label+" replaces "+before.label+", which may have run less often)") + } + changes = append(changes, c) + } + if len(changes) == 0 { + return WritePreview{}, fmt.Errorf("%s changes nothing: agent %s's cadences already read that way", WriteOpAgentCadences, agent) + } + fingerprint, err := stateFingerprint(st) + if err != nil { + return WritePreview{}, err + } + fields := make([]string, 0, len(changes)) + effects := make([]string, 0, len(changes)+4) + for _, c := range changes { + fields = append(fields, c.Field) + effects = append(effects, c.effect()) + } + effects = append(effects, + "Hive saves it through agent "+agent+"'s Cadences settings (PUT "+agentCadencesPath(agent)+"), the same save the dashboard makes, and records a config_agent_cadences audit entry. Modes not named here keep their cadence.", + "Each mode set here becomes operator-owned for "+agent+" (governor.cadence_owners.."+agent+": operator), as a dashboard edit does: a later ACMM level change (fleet.autonomy_level) or pack apply no longer resets "+listLabel(owned)+" to the pack default. The hive does not report whether these cells were operator-owned already.", + "This write itself kicks, merges, approves and labels nothing.", + ) + narrowNote := "" + if len(narrow) > 0 { + narrowNote = " Narrowing: " + strings.Join(narrow, "; ") + "." + } + disclosure := "No widening: " + agent + " runs no more often in any mode." + narrowNote + if len(widen) > 0 { + disclosure = "Widening: " + strings.Join(widen, "; ") + "." + narrowNote + } + return WritePreview{ + Operation: WriteOpAgentCadences, + Summary: "Change agent " + agent + "'s cadence in " + strings.Join(fields, ", "), + Target: agent, + Request: WriteRequest{Method: http.MethodPut, Path: agentCadencesPath(agent), Body: body}, + Effects: effects, + WideningDisclosure: disclosure, + ConfirmationMessage: "Confirm changing agent " + agent + "'s cadence in " + strings.Join(fields, ", ") + ".", + Details: map[string]any{"agent": agent, "changes": changeDetails(changes), "operator_owned_after": owned}, + StateFingerprint: fingerprint, + }, nil +} + +// ---- writeback.kind_policy ------------------------------------------------- + +// writebackKindFields are the fields of writeback.kinds.. +var writebackKindFields = []string{"min_level", "require_label", "unlabeled_min_level", "own_only"} + +// writebackKindChange is one kind's requested change: remove the whole +// override, or set and unset single fields. +type writebackKindChange struct { + remove bool + set map[string]any // field → int or bool + unset []string +} + +func writebackKindNames() []string { + kinds := writeback.Kinds() + out := make([]string, len(kinds)) + for i, k := range kinds { + out[i] = string(k) + } + return out +} + +func parseWritebackKindPolicyArgs(args map[string]any) (map[string]writebackKindChange, error) { + const where = WriteOpWritebackKindPolicy + if err := rejectUnknownKeys(args, where, "kinds"); err != nil { + return nil, err + } + raw, present := args["kinds"] + kinds, ok := raw.(map[string]any) + if !present || !ok { + return nil, fmt.Errorf("%s.kinds must be an object of write-back kind → override (or null to remove the override)", where) + } + if len(kinds) == 0 { + return nil, fmt.Errorf("%s.kinds names no kind", where) + } + out := map[string]writebackKindChange{} + for name, rawChange := range kinds { + kind := strings.ToLower(strings.TrimSpace(name)) + if !writeback.IsKind(kind) { + return nil, fmt.Errorf("%s.kinds: %q is not a write-back kind (known: %s)", where, name, strings.Join(writebackKindNames(), ", ")) + } + if _, dup := out[kind]; dup { + return nil, fmt.Errorf("%s.kinds names %s twice", where, kind) + } + field := where + ".kinds." + kind + if rawChange == nil { + out[kind] = writebackKindChange{remove: true} + continue + } + m, ok := rawChange.(map[string]any) + if !ok { + return nil, fmt.Errorf("%s must be an object with %s, or null to remove the override", field, strings.Join(writebackKindFields, ", ")) + } + if err := rejectUnknownKeys(m, field, writebackKindFields...); err != nil { + return nil, err + } + if len(m) == 0 { + return nil, fmt.Errorf("%s names no field: give %s, or null to remove the override", field, strings.Join(writebackKindFields, ", ")) + } + c := writebackKindChange{set: map[string]any{}} + for _, f := range writebackKindFields { + v, present := m[f] + if !present { + continue + } + if v == nil { + c.unset = append(c.unset, f) + continue + } + switch f { + case "min_level", "unlabeled_min_level": + n, ok := numberArg(v) + if !ok || n > config.MaxACMMLevel { + return nil, fmt.Errorf("%s.%s must be a level from 0 to %d, or null to drop it", field, f, config.MaxACMMLevel) + } + c.set[f] = n + default: + b, ok := v.(bool) + if !ok { + return nil, fmt.Errorf("%s.%s must be true or false, or null to drop it", field, f) + } + c.set[f] = b + } + } + out[kind] = c + } + return out, nil +} + +// writebackKindState is the write-back settings the preview read. Kinds is +// what the confirm fingerprints. +type writebackKindState struct { + Kinds map[string]writeback.KindPolicyOverride `json:"writeback_kinds"` + requireLabels bool + optInLabels []string +} + +func readWritebackKindState(ctx context.Context, provider Provider) (writebackKindState, error) { + const what = "write-back kind overrides" + m, err := readGovernorSettings(ctx, provider, what) + if err != nil { + return writebackKindState{}, err + } + features, _ := m["features"].(map[string]any) + if features == nil { + return writebackKindState{}, missingSetting(what, "features") + } + raw, present := features["writebackKinds"] + if !present { + return writebackKindState{}, missingSetting(what, "features.writebackKinds") + } + st := writebackKindState{Kinds: map[string]writeback.KindPolicyOverride{}, requireLabels: true} + if raw != nil { + data, err := json.Marshal(raw) + if err != nil { + return writebackKindState{}, missingSetting(what, "features.writebackKinds") + } + var kinds map[string]writeback.KindPolicyOverride + if err := json.Unmarshal(data, &kinds); err != nil { + return writebackKindState{}, missingSetting(what, "features.writebackKinds") + } + for k, ov := range kinds { + st.Kinds[strings.ToLower(strings.TrimSpace(k))] = ov + } + } + if b, ok := boolField(features, "writebackRequireLabels"); ok { + st.requireLabels = b + } + st.optInLabels, _ = stringsField(features, "writebackOptInLabels") + return st, nil +} + +// writebackKindOverrideBody is one override as the endpoint takes it: only +// the fields that are set. +func writebackKindOverrideBody(ov writeback.KindPolicyOverride) map[string]any { + out := map[string]any{} + if ov.MinLevel != nil { + out["min_level"] = *ov.MinLevel + } + if ov.RequireLabel != nil { + out["require_label"] = *ov.RequireLabel + } + if ov.UnlabeledMinLevel != nil { + out["unlabeled_min_level"] = *ov.UnlabeledMinLevel + } + if ov.OwnOnly != nil { + out["own_only"] = *ov.OwnOnly + } + return out +} + +func writebackKindOverrideEmpty(ov writeback.KindPolicyOverride) bool { + return ov.MinLevel == nil && ov.RequireLabel == nil && ov.UnlabeledMinLevel == nil && ov.OwnOnly == nil +} + +func writebackKindOverrideLabel(ov writeback.KindPolicyOverride, present bool) string { + if !present || writebackKindOverrideEmpty(ov) { + return "no override" + } + var parts []string + for _, f := range writebackKindFields { + if v, ok := writebackKindOverrideBody(ov)[f]; ok { + parts = append(parts, fmt.Sprintf("%s: %v", f, v)) + } + } + return "{" + strings.Join(parts, ", ") + "}" +} + +// applyWritebackKindChange merges c onto the kind's current override. +// Removing an override or a field that is not set is refused, so a typo +// cannot pass for a removal. +func applyWritebackKindChange(kind string, cur writeback.KindPolicyOverride, present bool, c writebackKindChange) (writeback.KindPolicyOverride, error) { + if c.remove { + if !present { + return cur, fmt.Errorf("%s: cannot remove the override for %s, it has none", WriteOpWritebackKindPolicy, kind) + } + return writeback.KindPolicyOverride{}, nil + } + next := cur + set := writebackKindOverrideBody(cur) + for _, f := range c.unset { + if _, ok := set[f]; !ok { + return cur, fmt.Errorf("%s: cannot drop %s.%s, the override does not set it (%s)", WriteOpWritebackKindPolicy, kind, f, writebackKindOverrideLabel(cur, present)) + } + switch f { + case "min_level": + next.MinLevel = nil + case "require_label": + next.RequireLabel = nil + case "unlabeled_min_level": + next.UnlabeledMinLevel = nil + case "own_only": + next.OwnOnly = nil + } + } + for f, v := range c.set { + switch f { + case "min_level": + n := v.(int) + next.MinLevel = &n + case "require_label": + b := v.(bool) + next.RequireLabel = &b + case "unlabeled_min_level": + n := v.(int) + next.UnlabeledMinLevel = &n + case "own_only": + b := v.(bool) + next.OwnOnly = &b + } + } + return next, nil +} + +// writebackKindNever is the level a kind never reaches. +const writebackKindNever = 99 + +// writebackKindReach is the lowest level at which kind writes on an item the +// hive did not author, with and without the opt-in label (Gate.Allowed). +func writebackKindReach(p writeback.KindPolicy) (withLabel, withoutLabel int) { + if p.OwnOnly { + return writebackKindNever, writebackKindNever + } + switch { + case !p.RequireLabel: + return p.MinLevel, p.MinLevel + case p.UnlabeledMinLevel > 0: + return p.MinLevel, p.UnlabeledMinLevel + default: + return p.MinLevel, writebackKindNever + } +} + +func writebackKindPolicyLabel(p writeback.KindPolicy) string { + with, without := writebackKindReach(p) + switch { + case with == writebackKindNever: + return "hive-authored items only" + case without == with: + return fmt.Sprintf("L%d, any item", with) + case without == writebackKindNever: + return fmt.Sprintf("L%d with the opt-in label", with) + default: + return fmt.Sprintf("L%d with the opt-in label, L%d without", with, without) + } +} + +func writebackKindLevelLabel(level int) string { + if level == writebackKindNever { + return "never" + } + return fmt.Sprintf("L%d", level) +} + +func (writebackKindPolicyOp) Name() string { return WriteOpWritebackKindPolicy } +func (writebackKindPolicyOp) Description() string { + return "Change the write-back gate's per-kind overrides (writeback.kinds.: min_level, require_label, unlabeled_min_level, own_only) through PUT /api/config/governor/features, the endpoint Settings → Features saves through. kinds maps a write-back kind to the fields to set (null drops one field), or to null to remove that kind's override. That endpoint replaces the whole override map, so the preview reads the current overrides and sends them all with the change merged in: kinds you do not name keep their override. The preview shows each kind's override and effective policy before → after and says when a kind would write at a lower level or without the opt-in label. write_confirm is refused if the overrides changed since the preview. Owner only: the endpoint refuses any other role. It posts, labels and merges nothing itself." +} +func (writebackKindPolicyOp) InputSchema() map[string]any { + level := map[string]any{"anyOf": []any{map[string]any{"type": "integer", "minimum": 0, "maximum": config.MaxACMMLevel}, map[string]any{"type": "null"}}} + flag := map[string]any{"anyOf": []any{map[string]any{"type": "boolean"}, map[string]any{"type": "null"}}} + override := map[string]any{"type": "object", "properties": map[string]any{ + "min_level": level, + "require_label": flag, + "unlabeled_min_level": level, + "own_only": flag, + }, "additionalProperties": false} + kinds := map[string]any{} + for _, k := range writebackKindNames() { + kinds[k] = map[string]any{"anyOf": []any{override, map[string]any{"type": "null"}}} + } + return map[string]any{"type": "object", "properties": map[string]any{ + "kinds": map[string]any{"type": "object", "description": "Write-back kind → the override fields to change (null drops a field), or null to remove the kind's override. Kinds you do not name keep their override.", "properties": kinds, "additionalProperties": false}, + }, "required": []string{"kinds"}, "additionalProperties": false} +} + +// Preview without a provider checks the arguments and names the endpoint; +// see agentCadencesOp.Preview. +func (writebackKindPolicyOp) Preview(_ context.Context, args map[string]any) (WritePreview, error) { + if _, err := parseWritebackKindPolicyArgs(args); err != nil { + return WritePreview{}, err + } + return unreadSettingsPreview(WriteOpWritebackKindPolicy, "writeback.kinds", "/api/config/governor/features", "write-back kind overrides"), nil +} + +// ConfirmGuard reads the overrides again at write_confirm and returns their +// fingerprint, which must still match the preview's. +func (op writebackKindPolicyOp) ConfirmGuard(ctx context.Context, args map[string]any, provider Provider) (string, error) { + return confirmGuardFingerprint(op.PreviewWithProvider(ctx, args, provider)) +} + +// PreviewWithProvider reads the current overrides, merges the change onto +// them and discloses every kind that would write on more items. +func (writebackKindPolicyOp) PreviewWithProvider(ctx context.Context, args map[string]any, provider Provider) (WritePreview, error) { + req, err := parseWritebackKindPolicyArgs(args) + if err != nil { + return WritePreview{}, err + } + st, err := readWritebackKindState(ctx, provider) + if err != nil { + return WritePreview{}, err + } + after := map[string]writeback.KindPolicyOverride{} + for k, ov := range st.Kinds { + after[k] = ov + } + named := make([]string, 0, len(req)) + for k := range req { + named = append(named, k) + } + sort.Strings(named) + + requireLabels := st.requireLabels + policyOf := func(kinds map[string]writeback.KindPolicyOverride, kind string) writeback.KindPolicy { + return writeback.Config{Kinds: kinds, Unsolicited: writeback.UnsolicitedConfig{RequireLabels: &requireLabels}}.Policy(writeback.Kind(kind)) + } + optIn := listLabel(st.optInLabels) + if len(st.optInLabels) == 0 { + optIn = "the review opt-in label" + } + + var changes []settingChange + var widen, narrow, changed, dashboardLossy []string + for _, kind := range named { + cur, present := st.Kinds[kind] + next, err := applyWritebackKindChange(kind, cur, present, req[kind]) + if err != nil { + return WritePreview{}, err + } + if writebackKindOverrideEmpty(next) { + delete(after, kind) + } else { + after[kind] = next + } + _, nextPresent := after[kind] + beforeLabel := writebackKindOverrideLabel(cur, present) + afterLabel := writebackKindOverrideLabel(next, nextPresent) + if beforeLabel == afterLabel { + continue + } + changed = append(changed, kind) + pb, pa := policyOf(st.Kinds, kind), policyOf(after, kind) + changes = append(changes, settingChange{ + Field: "writeback.kinds." + kind, + Before: beforeLabel, + After: afterLabel, + Note: "effective: " + writebackKindPolicyLabel(pb) + " → " + writebackKindPolicyLabel(pa), + }) + bw, bwo := writebackKindReach(pb) + aw, awo := writebackKindReach(pa) + switch { + case bw == writebackKindNever && aw != writebackKindNever: + widen = append(widen, kind+" now writes on items the hive did not author ("+writebackKindPolicyLabel(pa)+"); before, only on its own") + case aw == writebackKindNever && bw != writebackKindNever: + narrow = append(narrow, kind+" now writes only on items the hive authored (was "+writebackKindPolicyLabel(pb)+")") + default: + switch { + case aw < bw: + widen = append(widen, kind+" now writes on opted-in items from "+writebackKindLevelLabel(aw)+" (was "+writebackKindLevelLabel(bw)+")") + case aw > bw: + narrow = append(narrow, kind+" writes on opted-in items from "+writebackKindLevelLabel(aw)+" only (was "+writebackKindLevelLabel(bw)+")") + } + switch { + case awo < bwo && bwo == writebackKindNever: + widen = append(widen, kind+" now writes on items without the opt-in label ("+optIn+") from "+writebackKindLevelLabel(awo)+"; before, it needed the label") + case awo < bwo: + widen = append(widen, kind+" now writes on items without the opt-in label from "+writebackKindLevelLabel(awo)+" (was "+writebackKindLevelLabel(bwo)+")") + case awo > bwo && awo == writebackKindNever: + narrow = append(narrow, kind+" no longer writes on items without the opt-in label (was from "+writebackKindLevelLabel(bwo)+")") + case awo > bwo: + narrow = append(narrow, kind+" writes on items without the opt-in label from "+writebackKindLevelLabel(awo)+" only (was "+writebackKindLevelLabel(bwo)+")") + } + } + } + if len(changes) == 0 { + return WritePreview{}, fmt.Errorf("%s changes nothing: the overrides already read that way", WriteOpWritebackKindPolicy) + } + fingerprint, err := stateFingerprint(st) + if err != nil { + return WritePreview{}, err + } + + // The endpoint replaces the whole map: send every override, changed or + // not. An empty map clears them all. + kindsBody := map[string]any{} + var kept []string + for k, ov := range after { + kindsBody[k] = writebackKindOverrideBody(ov) + if ov.UnlabeledMinLevel != nil || ov.OwnOnly != nil { + dashboardLossy = append(dashboardLossy, k) + } + if _, isNamed := req[k]; !isNamed { + kept = append(kept, k) + } + } + sort.Strings(kept) + sort.Strings(dashboardLossy) + + effects := make([]string, 0, len(changes)+5) + for _, c := range changes { + effects = append(effects, c.effect()) + } + keptNote := "No other kind has an override." + if len(kept) > 0 { + keptNote = "The overrides of kinds not named here (" + strings.Join(kept, ", ") + ") are sent unchanged and kept." + } + effects = append(effects, + "Hive saves it through Settings → Features (PUT /api/config/governor/features, writebackKinds), records a config_governor_features audit entry, and the write-back gate applies it from its next decision, with no restart. That endpoint replaces the whole override map, so this write sends every override with the change merged in. "+keptNote, + "The effective policy shown ignores writeback.unsolicited.min_level, which when set still raises every kind's level, and writeback.per_repo, which still sets each repository's mode.", + ) + if len(dashboardLossy) > 0 { + effects = append(effects, "Settings → Features' write-back kind table edits only min_level and require_label, and saving an edit there rewrites every kind's override from that table: it would drop unlabeled_min_level and own_only from "+strings.Join(dashboardLossy, ", ")+". Change those through this operation or hive.yaml.") + } + effects = append(effects, "This write itself posts, labels, closes and merges nothing.") + + narrowNote := "" + if len(narrow) > 0 { + narrowNote = " Narrowing: " + strings.Join(narrow, "; ") + "." + } + disclosure := "No widening: no kind writes at a lower level or without the opt-in label." + narrowNote + if len(widen) > 0 { + disclosure = "Widening: hive writes on more items it did not open. " + strings.Join(widen, "; ") + "." + narrowNote + } + return WritePreview{ + Operation: WriteOpWritebackKindPolicy, + Summary: "Change the write-back kind overrides: " + strings.Join(changed, ", "), + Target: "writeback.kinds", + Request: WriteRequest{Method: http.MethodPut, Path: "/api/config/governor/features", Body: map[string]any{"writebackKinds": kindsBody}}, + Effects: effects, + WideningDisclosure: disclosure, + ConfirmationMessage: "Confirm changing the write-back kind overrides: " + strings.Join(changed, ", ") + ".", + Details: map[string]any{"changes": changeDetails(changes), "kept": kept}, + StateFingerprint: fingerprint, + }, nil +} diff --git a/src/pkg/adminmcp/tools_cadence_writeback_ops_test.go b/src/pkg/adminmcp/tools_cadence_writeback_ops_test.go new file mode 100644 index 0000000000..1949e6278f --- /dev/null +++ b/src/pkg/adminmcp/tools_cadence_writeback_ops_test.go @@ -0,0 +1,428 @@ +package adminmcp + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "strings" + "testing" +) + +// cadenceWBProvider answers settings_read section agent (per agent) and +// section governor with a JSON round trip, as from the hive, and records +// writes. readErr and writeErr stand in for the endpoint's refusals. +type cadenceWBProvider struct { + agents map[string]map[string]any + governor map[string]any + readErr error + writeErr error + requests []WriteRequest +} + +func (p *cadenceWBProvider) Read(_ context.Context, tool string, args map[string]any) (any, error) { + if p.readErr != nil { + return nil, p.readErr + } + if tool != ToolSettingsRead { + return map[string]any{}, nil + } + var v any + switch args["section"] { + case "agent": + a, ok := p.agents[fmt.Sprint(args["agent"])] + if !ok { + return nil, &HiveRefusalError{StatusCode: http.StatusNotFound, Message: "agent not found"} + } + v = a + case SettingsSectionDefault: + v = p.governor + default: + return map[string]any{}, nil + } + data, err := json.Marshal(v) + if err != nil { + return nil, err + } + var out map[string]any + err = json.Unmarshal(data, &out) + return out, err +} + +func (p *cadenceWBProvider) ExecuteWrite(_ context.Context, req WriteRequest) (any, error) { + if p.writeErr != nil { + return nil, p.writeErr + } + p.requests = append(p.requests, req) + return map[string]any{"status": "updated"}, nil +} + +// knuckleScanner is the knuckle hive's scanner on 2026-11-10: 4h in every +// mode. +func knuckleScanner() map[string]any { + return map[string]any{ + "general": map[string]any{"enabled": true}, + "cadences": map[string]any{"surge": 14400, "busy": 14400, "quiet": 14400, "idle": 14400}, + "models": map[string]any{"surge": "", "busy": "", "quiet": "", "idle": ""}, + } +} + +// knuckleWriteback is the knuckle hive's write-back settings on 2026-11-10: +// one override, stage_label without the opt-in label. +func knuckleWriteback() map[string]any { + return map[string]any{"features": map[string]any{ + "writebackKinds": map[string]any{"stage_label": map[string]any{"require_label": false}}, + "writebackRequireLabels": true, + "writebackOptInLabels": []string{"hive-review"}, + }} +} + +func cadenceWBHandler(p *cadenceWBProvider) *Handler { + return NewHandler(p, WithWritesEnabled(true), WithPendingStore(NewMemoryPendingStore()), WithHiveID("hive-a")) +} + +func newCadenceWBProvider() *cadenceWBProvider { + return &cadenceWBProvider{agents: map[string]map[string]any{"scanner": knuckleScanner()}, governor: knuckleWriteback()} +} + +func TestCadenceWritebackOpsRegisteredOnTheirEndpoints(t *testing.T) { + for name, path := range map[string]string{ + WriteOpAgentCadences: "PUT /api/config/agent/{name}/cadences", + WriteOpWritebackKindPolicy: "PUT /api/config/governor/features", + } { + op := mustOp(t, name) + if !strings.Contains(op.Description(), path) || !strings.Contains(op.Description(), "Owner only") { + t.Errorf("%s description does not name %s and the owner-only rule", name, path) + } + if _, ok := op.(confirmGuardOp); !ok { + t.Errorf("%s has no ConfirmGuard, so a stale preview could be confirmed", name) + } + } +} + +// ---- agent.cadences ---- + +func TestAgentCadencesOpRejectsUnknownFields(t *testing.T) { + p := newCadenceWBProvider() + // A hive that configures no surge mode: the endpoint would skip it. + p.agents["lean"] = map[string]any{"cadences": map[string]any{"idle": 3600}, "models": map[string]any{"idle": "", "quiet": ""}} + h := cadenceWBHandler(p) + for name, args := range map[string]map[string]any{ + "top-level typo": {"agent": "scanner", "mode": map[string]any{"surge": "1h"}}, + "unknown mode": {"agent": "scanner", "modes": map[string]any{"weekend": "1h"}}, + "not a duration": {"agent": "scanner", "modes": map[string]any{"surge": "soon"}}, + "negative duration": {"agent": "scanner", "modes": map[string]any{"surge": "-1h"}}, + "sub-second duration": {"agent": "scanner", "modes": map[string]any{"surge": "1500ms"}}, + "number not string": {"agent": "scanner", "modes": map[string]any{"surge": 3600}}, + "no mode": {"agent": "scanner", "modes": map[string]any{}}, + "no agent": {"modes": map[string]any{"surge": "1h"}}, + "unknown agent": {"agent": "nobody", "modes": map[string]any{"surge": "1h"}}, + "mode not on the hive": {"agent": "lean", "modes": map[string]any{"surge": "1h"}}, + "already that cadence": {"agent": "scanner", "modes": map[string]any{"surge": "4h"}}, + } { + t.Run(name, func(t *testing.T) { + if _, err := h.PreviewWrite(context.Background(), map[string]any{"operation": WriteOpAgentCadences, "args": args}); err == nil { + t.Fatalf("args %v accepted", args) + } + }) + } + if pending, _ := h.PendingStore.List(context.Background()); len(pending) != 0 { + t.Fatalf("a refused preview minted a confirmation: %+v", pending) + } +} + +// Only the named modes are sent; a named mode already at that cadence is +// left out too, so the endpoint does not claim ownership of it. +func TestAgentCadencesOpKeepsUntouchedModes(t *testing.T) { + p := newCadenceWBProvider() + h := cadenceWBHandler(p) + preview, id := capPreview(t, h, WriteOpAgentCadences, map[string]any{"agent": "scanner", "modes": map[string]any{"surge": "1h", "busy": "60m", "quiet": "4h"}}) + if preview.Request.Method != http.MethodPut || preview.Request.Path != "/api/config/agent/scanner/cadences" { + t.Fatalf("request = %s %s", preview.Request.Method, preview.Request.Path) + } + if got := bodyJSON(t, preview.Request.Body); got != `{"busy":3600,"surge":3600}` { + t.Fatalf("body = %s, want only surge and busy", got) + } + effects := strings.Join(preview.Effects, "\n") + for _, want := range []string{"surge: 4h → 1h", "busy: 4h → 1h", "operator-owned", "fleet.autonomy_level"} { + if !strings.Contains(effects, want) { + t.Errorf("effects lack %q:\n%s", want, effects) + } + } + if strings.Contains(effects, "quiet:") { + t.Errorf("effects list the unchanged quiet mode:\n%s", effects) + } + if _, err := h.ConfirmWrite(context.Background(), map[string]any{"confirmation_id": id}); err != nil { + t.Fatalf("confirm: %v", err) + } + if len(p.requests) != 1 || bodyJSON(t, p.requests[0].Body) != `{"busy":3600,"surge":3600}` { + t.Fatalf("executed %+v", p.requests) + } +} + +func TestAgentCadencesOpFlagsWidening(t *testing.T) { + p := newCadenceWBProvider() + p.agents["paused"] = map[string]any{"cadences": map[string]any{"surge": 0, "busy": 7200}, "models": map[string]any{"surge": "", "busy": "", "quiet": "", "idle": ""}} + h := cadenceWBHandler(p) + for name, tc := range map[string]struct { + agent, mode, value string + widening bool + want string + }{ + "shorter": {"scanner", "surge", "1h", true, "scanner runs more often in surge: more spend"}, + "longer": {"scanner", "idle", "8h", false, "runs less often in idle"}, + "pause": {"scanner", "quiet", "pause", false, "stops running on a cadence in quiet"}, + "from paused": {"paused", "surge", "6h", true, "paused runs more often in surge: more spend (every 6h, was paused)"}, + "from unset": {"paused", "idle", "12h", true, "paused runs more often in idle: more spend"}, + "longer from 2h": {"paused", "busy", "3h", false, "runs less often in busy"}, + "shorter from 2h": {"paused", "busy", "30m", true, "paused runs more often in busy"}, + "seconds are exact": {"scanner", "busy", "90m", true, "every 90m, was every 4h"}, + } { + t.Run(name, func(t *testing.T) { + preview, _ := capPreview(t, h, WriteOpAgentCadences, map[string]any{"agent": tc.agent, "modes": map[string]any{tc.mode: tc.value}}) + if isWidening(preview) != tc.widening { + t.Fatalf("widening = %v, want %v: %s", isWidening(preview), tc.widening, preview.WideningDisclosure) + } + if !strings.Contains(preview.WideningDisclosure, tc.want) { + t.Fatalf("disclosure %q lacks %q", preview.WideningDisclosure, tc.want) + } + }) + } +} + +func TestAgentCadencesOpRefusesStalePreview(t *testing.T) { + p := newCadenceWBProvider() + h := cadenceWBHandler(p) + args := map[string]any{"agent": "scanner", "modes": map[string]any{"surge": "1h"}} + _, id := capPreview(t, h, WriteOpAgentCadences, args) + + // Somebody edits another mode on the dashboard in between. + p.agents["scanner"]["cadences"].(map[string]any)["quiet"] = 7200 + if _, err := h.ConfirmWrite(context.Background(), map[string]any{"confirmation_id": id}); !errors.Is(err, ErrConfirmationStale) { + t.Fatalf("stale confirm err = %v, want ErrConfirmationStale", err) + } + if len(p.requests) != 0 { + t.Fatalf("a stale confirm wrote %+v", p.requests) + } + + _, id = capPreview(t, h, WriteOpAgentCadences, args) + if _, err := h.ConfirmWrite(context.Background(), map[string]any{"confirmation_id": id}); err != nil { + t.Fatalf("fresh confirm: %v", err) + } + if len(p.requests) != 1 || bodyJSON(t, p.requests[0].Body) != `{"surge":3600}` { + t.Fatalf("executed %+v", p.requests) + } +} + +// The cadence endpoint is owner only. A caller the hive refuses gets no +// confirmation, and a confirm the endpoint refuses writes nothing. +func TestAgentCadencesOpRefusesNonOwner(t *testing.T) { + cadenceWBRefusesNonOwner(t, WriteOpAgentCadences, map[string]any{"agent": "scanner", "modes": map[string]any{"surge": "1h"}}) +} + +func cadenceWBRefusesNonOwner(t *testing.T, op string, args map[string]any) { + t.Helper() + p := newCadenceWBProvider() + p.readErr = fmt.Errorf("%w: Hive API returned HTTP 403: owner access required", ErrForbidden) + h := cadenceWBHandler(p) + if _, err := h.PreviewWrite(context.Background(), map[string]any{"operation": op, "args": args}); err == nil || !strings.Contains(err.Error(), "owner access required") { + t.Fatalf("refused read: preview err = %v, want the owner refusal", err) + } + if pending, _ := h.PendingStore.List(context.Background()); len(pending) != 0 { + t.Fatalf("a refused read minted a confirmation: %+v", pending) + } + + p.readErr = nil + p.writeErr = &HiveRefusalError{StatusCode: http.StatusForbidden, Message: "owner access required"} + _, id := capPreview(t, h, op, args) + _, err := h.ConfirmWrite(context.Background(), map[string]any{"confirmation_id": id}) + if refusal, ok := HiveRefusalFromError(err); !ok || refusal.StatusCode != http.StatusForbidden { + t.Fatalf("confirm err = %v, want the endpoint's 403", err) + } + if len(p.requests) != 0 { + t.Fatalf("wrote without owner access: %+v", p.requests) + } +} + +// ---- writeback.kind_policy ---- + +func TestWritebackKindPolicyOpRejectsUnknownFields(t *testing.T) { + h := cadenceWBHandler(newCadenceWBProvider()) + for name, args := range map[string]map[string]any{ + "top-level typo": {"kind": map[string]any{"base_refresh": map[string]any{"min_level": 6}}}, + "no kinds": {}, + "empty kinds": {"kinds": map[string]any{}}, + "kinds not an object": {"kinds": []any{"base_refresh"}}, + "unknown kind": {"kinds": map[string]any{"base_refesh": map[string]any{"min_level": 6}}}, + "unknown field": {"kinds": map[string]any{"base_refresh": map[string]any{"max_level": 6}}}, + "no field": {"kinds": map[string]any{"base_refresh": map[string]any{}}}, + "level above 6": {"kinds": map[string]any{"base_refresh": map[string]any{"min_level": 7}}}, + "negative level": {"kinds": map[string]any{"base_refresh": map[string]any{"unlabeled_min_level": -1}}}, + "fractional level": {"kinds": map[string]any{"base_refresh": map[string]any{"min_level": 5.5}}}, + "level as string": {"kinds": map[string]any{"base_refresh": map[string]any{"min_level": "6"}}}, + "flag as string": {"kinds": map[string]any{"base_refresh": map[string]any{"require_label": "no"}}}, + "override not an object": {"kinds": map[string]any{"base_refresh": 6}}, + "remove absent override": {"kinds": map[string]any{"base_refresh": nil}}, + "drop field not set": {"kinds": map[string]any{"stage_label": map[string]any{"min_level": nil}}}, + "same as the current": {"kinds": map[string]any{"stage_label": map[string]any{"require_label": false}}}, + "same kind twice by case": {"kinds": map[string]any{"stage_label": nil, "Stage_Label": nil}}, + } { + t.Run(name, func(t *testing.T) { + if _, err := h.PreviewWrite(context.Background(), map[string]any{"operation": WriteOpWritebackKindPolicy, "args": args}); err == nil { + t.Fatalf("args %v accepted", args) + } + }) + } +} + +// The Features endpoint replaces the whole writebackKinds map, so a change +// to one kind must send every other override unchanged. On knuckle that is +// stage_label's require_label: false, which must survive the base_refresh +// change. +func TestWritebackKindPolicyOpKeepsUntouchedKinds(t *testing.T) { + p := newCadenceWBProvider() + h := cadenceWBHandler(p) + preview, id := capPreview(t, h, WriteOpWritebackKindPolicy, map[string]any{"kinds": map[string]any{"base_refresh": map[string]any{"unlabeled_min_level": 6}}}) + want := `{"writebackKinds":{"base_refresh":{"unlabeled_min_level":6},"stage_label":{"require_label":false}}}` + if preview.Request.Method != http.MethodPut || preview.Request.Path != "/api/config/governor/features" || bodyJSON(t, preview.Request.Body) != want { + t.Fatalf("request = %s %s %s, want PUT /api/config/governor/features %s", preview.Request.Method, preview.Request.Path, bodyJSON(t, preview.Request.Body), want) + } + effects := strings.Join(preview.Effects, "\n") + for _, s := range []string{"writeback.kinds.base_refresh: no override → {unlabeled_min_level: 6}", "L6 with the opt-in label → L6, any item", "(stage_label) are sent unchanged", "would drop unlabeled_min_level and own_only from base_refresh"} { + if !strings.Contains(effects, s) { + t.Errorf("effects lack %q:\n%s", s, effects) + } + } + if _, err := h.ConfirmWrite(context.Background(), map[string]any{"confirmation_id": id}); err != nil { + t.Fatalf("confirm: %v", err) + } + if len(p.requests) != 1 || bodyJSON(t, p.requests[0].Body) != want { + t.Fatalf("executed %+v", p.requests) + } + + for name, tc := range map[string]struct { + replace bool // replace knuckle's overrides with kinds + kinds map[string]any + args map[string]any + want string + }{ + "a field merges into the override": { + args: map[string]any{"stage_label": map[string]any{"min_level": 6}}, + want: `{"writebackKinds":{"stage_label":{"min_level":6,"require_label":false}}}`, + }, + "null drops one field": { + replace: true, + kinds: map[string]any{"stage_label": map[string]any{"require_label": false, "min_level": 6}}, + args: map[string]any{"stage_label": map[string]any{"min_level": nil}}, + want: `{"writebackKinds":{"stage_label":{"require_label":false}}}`, + }, + "null removes only that kind": { + replace: true, + kinds: map[string]any{"stage_label": map[string]any{"require_label": false}, "sentinel": map[string]any{"min_level": 6}}, + args: map[string]any{"sentinel": nil}, + want: `{"writebackKinds":{"stage_label":{"require_label":false}}}`, + }, + "removing the last override sends an empty map": { + args: map[string]any{"stage_label": nil}, + want: `{"writebackKinds":{}}`, + }, + "no overrides yet": { + replace: true, + kinds: nil, + args: map[string]any{"base_refresh": map[string]any{"unlabeled_min_level": 6}}, + want: `{"writebackKinds":{"base_refresh":{"unlabeled_min_level":6}}}`, + }, + } { + t.Run(name, func(t *testing.T) { + p := newCadenceWBProvider() + if tc.replace { + p.governor["features"].(map[string]any)["writebackKinds"] = tc.kinds + } + preview, _ := capPreview(t, cadenceWBHandler(p), WriteOpWritebackKindPolicy, map[string]any{"kinds": tc.args}) + if got := bodyJSON(t, preview.Request.Body); got != tc.want { + t.Fatalf("body = %s, want %s", got, tc.want) + } + }) + } +} + +func TestWritebackKindPolicyOpFlagsWidening(t *testing.T) { + for name, tc := range map[string]struct { + kinds map[string]any + requireLabels bool + widening bool + want string + }{ + "unlabeled level added": { + kinds: map[string]any{"base_refresh": map[string]any{"unlabeled_min_level": 6}}, requireLabels: true, widening: true, + want: "base_refresh now writes on items without the opt-in label (hive-review) from L6; before, it needed the label", + }, + "min level lowered": { + kinds: map[string]any{"ci_rerun": map[string]any{"min_level": 5}}, requireLabels: true, widening: true, + want: "ci_rerun now writes on opted-in items from L5 (was L6)", + }, + "label no longer required": { + kinds: map[string]any{"issue_close": map[string]any{"require_label": false}}, requireLabels: true, widening: true, + want: "issue_close now writes on items without the opt-in label (hive-review) from L5", + }, + "own_only lifted": { + kinds: map[string]any{"hold_gate_notice": map[string]any{"own_only": false}}, requireLabels: true, widening: true, + want: "hold_gate_notice now writes on items the hive did not author", + }, + "label required again": { + kinds: map[string]any{"stage_label": nil}, requireLabels: true, widening: false, + want: "Narrowing: stage_label no longer writes on items without the opt-in label (was from L5)", + }, + "min level raised": { + kinds: map[string]any{"verdict_label": map[string]any{"min_level": 5}}, requireLabels: true, widening: false, + want: "verdict_label writes on opted-in items from L5 only (was L3)", + }, + "labels off hive-wide": { + kinds: map[string]any{"base_refresh": map[string]any{"unlabeled_min_level": 6}}, requireLabels: false, widening: false, + want: "No widening", + }, + } { + t.Run(name, func(t *testing.T) { + p := newCadenceWBProvider() + p.governor["features"].(map[string]any)["writebackRequireLabels"] = tc.requireLabels + preview, _ := capPreview(t, cadenceWBHandler(p), WriteOpWritebackKindPolicy, map[string]any{"kinds": tc.kinds}) + if isWidening(preview) != tc.widening { + t.Fatalf("widening = %v, want %v: %s", isWidening(preview), tc.widening, preview.WideningDisclosure) + } + if !strings.Contains(preview.WideningDisclosure, tc.want) { + t.Fatalf("disclosure %q lacks %q", preview.WideningDisclosure, tc.want) + } + }) + } +} + +func TestWritebackKindPolicyOpRefusesStalePreview(t *testing.T) { + p := newCadenceWBProvider() + h := cadenceWBHandler(p) + args := map[string]any{"kinds": map[string]any{"base_refresh": map[string]any{"unlabeled_min_level": 6}}} + _, id := capPreview(t, h, WriteOpWritebackKindPolicy, args) + + // Somebody saves another kind's override on Settings → Features in + // between; confirming the old preview would wipe it. + p.governor["features"].(map[string]any)["writebackKinds"] = map[string]any{"stage_label": map[string]any{"require_label": false}, "ci_rerun": map[string]any{"min_level": 5}} + if _, err := h.ConfirmWrite(context.Background(), map[string]any{"confirmation_id": id}); !errors.Is(err, ErrConfirmationStale) { + t.Fatalf("stale confirm err = %v, want ErrConfirmationStale", err) + } + if len(p.requests) != 0 { + t.Fatalf("a stale confirm wrote %+v", p.requests) + } + + _, id = capPreview(t, h, WriteOpWritebackKindPolicy, args) + if _, err := h.ConfirmWrite(context.Background(), map[string]any{"confirmation_id": id}); err != nil { + t.Fatalf("fresh confirm: %v", err) + } + want := `{"writebackKinds":{"base_refresh":{"unlabeled_min_level":6},"ci_rerun":{"min_level":5},"stage_label":{"require_label":false}}}` + if len(p.requests) != 1 || bodyJSON(t, p.requests[0].Body) != want { + t.Fatalf("executed %+v, want body %s", p.requests, want) + } +} + +func TestWritebackKindPolicyOpRefusesNonOwner(t *testing.T) { + cadenceWBRefusesNonOwner(t, WriteOpWritebackKindPolicy, map[string]any{"kinds": map[string]any{"base_refresh": map[string]any{"unlabeled_min_level": 6}}}) +} diff --git a/src/pkg/dashboard/admin_mcp_cadence_writeback_test.go b/src/pkg/dashboard/admin_mcp_cadence_writeback_test.go new file mode 100644 index 0000000000..d7932da146 --- /dev/null +++ b/src/pkg/dashboard/admin_mcp_cadence_writeback_test.go @@ -0,0 +1,85 @@ +package dashboard + +import ( + "strings" + "testing" + + "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/writeback" +) + +// agent.cadences and writeback.kind_policy go through the endpoints the +// dashboard saves with, which are owner only: a read-write member's confirm +// is refused and changes nothing. The owner's confirm changes exactly the +// named mode and kind: the other modes keep their cadence and ownership, and +// the other kind's override survives, although the Features endpoint +// replaces the whole writebackKinds map it is sent. +func TestAdminMCPCadenceAndWritebackKindOpsAreOwnerOnlyAndMerge(t *testing.T) { + t.Setenv("HIVE_ADMIN_MCP_ENABLE_WRITES", "1") + t.Setenv("HIVE_ADMIN_MCP_PENDING_FILE", t.TempDir()+"/pending.json") + srv := newFullServer(t) + cfg := srv.deps.Config + cfg.Governor.Modes = map[string]config.ModeConfig{ + "idle": {Cadences: map[string]config.Cadence{"scanner": "4h"}}, + "quiet": {Threshold: 2, Cadences: map[string]config.Cadence{"scanner": "4h"}}, + "busy": {Threshold: 10, Cadences: map[string]config.Cadence{"scanner": "4h"}}, + "surge": {Threshold: 20, Cadences: map[string]config.Cadence{"scanner": "4h"}}, + } + off := false + cfg.Writeback.Kinds = map[string]writeback.KindPolicyOverride{"stage_label": {RequireLabel: &off}} + + srv.authToken = "secret" + h := srv.authenticate(srv.roleEnforcement(srv.securityHeaders(srv.mux))) + member := adminMCPAs(t, h, map[string]string{"X-Hive-User": "alice", "X-Hive-Role": config.RoleReadWrite, proxyAuthHeader: "secret"}) + owner := adminMCPAs(t, h, map[string]string{"Authorization": "Bearer secret"}) + preview := func(op, args string) string { + return `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"write_preview","arguments":{"operation":"` + op + `","args":` + args + `}}}` + } + confirm := func(id string) string { + return `{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"write_confirm","arguments":{"confirmation_id":"` + id + `"}}}` + } + cases := []struct{ op, args string }{ + {"agent.cadences", `{"agent":"scanner","modes":{"surge":"1h"}}`}, + {"writeback.kind_policy", `{"kinds":{"base_refresh":{"unlabeled_min_level":6}}}`}, + } + + for _, tc := range cases { + if got := member(confirm(confirmationID(t, member(preview(tc.op, tc.args))))); !strings.Contains(got, "owner access required") { + t.Fatalf("a read-write member's %s confirm = %s, want the endpoint's owner refusal", tc.op, got) + } + } + if got := cfg.Governor.Modes["surge"].Cadences["scanner"]; got != "4h" || cfg.Governor.CadenceIsOperatorOwned("surge", "scanner") { + t.Fatalf("a refused write changed the surge cadence to %q (operator-owned %v)", got, cfg.Governor.CadenceIsOperatorOwned("surge", "scanner")) + } + if _, ok := cfg.Writeback.Kinds["base_refresh"]; ok || len(cfg.Writeback.Kinds) != 1 { + t.Fatalf("a refused write changed writeback.kinds to %+v", cfg.Writeback.Kinds) + } + + for _, tc := range cases { + if got := owner(confirm(confirmationID(t, owner(preview(tc.op, tc.args))))); !strings.Contains(got, `"write_result"`) { + t.Fatalf("the owner's %s confirm = %s", tc.op, got) + } + } + if got := cfg.Governor.Modes["surge"].Cadences["scanner"]; got != "1h" { + t.Fatalf("surge cadence = %q, want 1h", got) + } + if !cfg.Governor.CadenceIsOperatorOwned("surge", "scanner") { + t.Fatal("the surge cadence the owner set is not operator-owned, so a level change would reset it") + } + for _, mode := range []string{"busy", "quiet", "idle"} { + if got := cfg.Governor.Modes[mode].Cadences["scanner"]; got != "4h" || cfg.Governor.CadenceIsOperatorOwned(mode, "scanner") { + t.Fatalf("%s cadence = %q (operator-owned %v), want the untouched 4h", mode, got, cfg.Governor.CadenceIsOperatorOwned(mode, "scanner")) + } + } + stage, ok := cfg.Writeback.Kinds["stage_label"] + if !ok || stage.RequireLabel == nil || *stage.RequireLabel { + t.Fatalf("stage_label's require_label: false override did not survive the base_refresh change: %+v", cfg.Writeback.Kinds) + } + refresh, ok := cfg.Writeback.Kinds["base_refresh"] + if !ok || refresh.UnlabeledMinLevel == nil || *refresh.UnlabeledMinLevel != 6 || refresh.MinLevel != nil || refresh.RequireLabel != nil { + t.Fatalf("base_refresh override = %+v, want only unlabeled_min_level: 6", refresh) + } + if got := cfg.Writeback.Policy(writeback.KindBaseRefresh); got.UnlabeledMinLevel != 6 { + t.Fatalf("effective base_refresh policy = %+v", got) + } +}