From 763c22c2df5fbefb87124ddf82d578df93650a5b Mon Sep 17 00:00:00 2001 From: Danathar Date: Mon, 9 Nov 2026 19:36:59 -0500 Subject: [PATCH 1/4] =?UTF-8?q?=E2=9C=A8=20feat(adminmcp):=20change=20merg?= =?UTF-8?q?e=20settings=20through=20preview=20and=20confirm?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add auto_merge.update, an admin MCP write operation that wraps PATCH /api/config/auto-merge, so an owner can change merge settings without the dashboard. The endpoint replaces every list and map it is sent whole, so the op takes changes (add/remove per list, one repository's human-merge paths set or unset), reads the current settings at preview time and sends the merged whole value. The preview shows each change before and after and discloses changes that let the hive merge more on its own. A new confirmGuardOp hook lets write_confirm re-read that state: the op fingerprints the before-value of every field it sends, and a changed setting refuses the confirm with ErrConfirmationStale instead of being overwritten. The op never merges anything; the endpoint's owner check and validation still apply to both the read and the write. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BQYnPGFJx81c8JXR3o1sg1 Signed-off-by: Danathar --- .../added-adminmcp-auto-merge-update.md | 1 + src/docs/admin-mcp.md | 27 +- src/docs/design/admin-mcp.md | 17 +- src/pkg/adminmcp/adminmcp.go | 20 +- src/pkg/adminmcp/tools_agent_ops.go | 1 + src/pkg/adminmcp/tools_automerge_ops.go | 874 ++++++++++++++++++ src/pkg/adminmcp/tools_automerge_ops_test.go | 264 ++++++ src/pkg/adminmcp/write_contract.go | 5 + 8 files changed, 1206 insertions(+), 3 deletions(-) create mode 100644 changelog.d/added-adminmcp-auto-merge-update.md create mode 100644 src/pkg/adminmcp/tools_automerge_ops.go create mode 100644 src/pkg/adminmcp/tools_automerge_ops_test.go diff --git a/changelog.d/added-adminmcp-auto-merge-update.md b/changelog.d/added-adminmcp-auto-merge-update.md new file mode 100644 index 0000000000..366167c909 --- /dev/null +++ b/changelog.d/added-adminmcp-auto-merge-update.md @@ -0,0 +1 @@ +- **Admin MCP: change merge settings through preview and confirm.** The new `auto_merge.update` write operation wraps `PATCH /api/config/auto-merge`, so an owner can change `squash_only`, `require_current_base`, `human_merge_paths`, the native merge queue, trusted authors, the contributor lane and the other merge settings without opening the dashboard. Lists take `add`/`remove` and `human_merge_paths` takes one repository at a time; the preview reads the current settings and sends each changed list or map whole, so entries you did not name are kept, shows every change before and after, and says when a change lets the hive merge more on its own. `write_confirm` refuses if any of those settings changed after the preview. The operation never merges a pull request, and `human_merge_pin_only` (not on the endpoint) is still set in the configuration file. diff --git a/src/docs/admin-mcp.md b/src/docs/admin-mcp.md index 60486b506a..430350fa25 100644 --- a/src/docs/admin-mcp.md +++ b/src/docs/admin-mcp.md @@ -680,7 +680,8 @@ Every write takes two steps: single-use and expires after 10 minutes. Only the caller who previewed a write can confirm it. The HTTP endpoint checks the writes switch again at this step, so a confirmation previewed before the owner turned writes off is - refused. + refused. An operation built from the current settings (`auto_merge.update`) + reads them again here and is refused if they changed after the preview. ### Who a write runs as @@ -710,6 +711,7 @@ The audit log cannot tell an assistant-mediated write from a dashboard action. | Fleet | `fleet.autonomy_level` | | Plans | `plan.propose`, `plan.approve`, `plan.reject` | | Governor | `governor.feature_settings`, `governor.thresholds`, `governor.threshold_scaling` | +| Merge settings | `auto_merge.update` | | Repositories | `repository.pause`, `repository.resume`, `repository.item_hold` | | Activity monitor row actions | see below | | Budget | `budget.update`, `budget.reset`, `budget.ignore` | @@ -736,6 +738,29 @@ installation's shared hourly bucket and the agent reserve floor be read, the preview says the change may be widening. See [Changing the agent caps](operator-reference/runtime-and-quota.md#changing-the-agent-caps). +`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. + +- **Pass only what changes,** shaped like the endpoint's body, for example + `{"squash_only": {"add": ["org/c"]}}` or + `{"contributor_lane": {"repos": {"remove": ["org/a"]}}}`. A list takes `add` + and `remove`. `human_merge_paths` takes `owner/repo` and every pattern that + repository should hold; `null` or `[]` removes the repository. An unknown + field is refused. +- **Entries you do not name are kept.** The endpoint replaces each list and + map it is sent, so the preview reads the current settings and sends the + merged whole value. It shows every change before and after. +- **A stale preview is refused.** `write_confirm` reads the settings again and + refuses if any setting the change sends was changed after the preview. + Preview again to build on the new value. +- **Widening is disclosed.** The preview says when a change lets the hive + merge more on its own: turning on the trusted-author lane, removing a + human-merge path, adding a repository to the native merge queue, emptying a + repository allow-list (empty means every repository), and the like. +- It never merges a pull request. `human_merge_pin_only` is not on this + endpoint, so it is still set in the hive configuration file. + The Activity monitor's row actions: | Operation | Button | diff --git a/src/docs/design/admin-mcp.md b/src/docs/design/admin-mcp.md index 24ccd31b3d..65ba29cdb2 100644 --- a/src/docs/design/admin-mcp.md +++ b/src/docs/design/admin-mcp.md @@ -121,7 +121,7 @@ type WriteOp interface { } ``` -A write op may also implement `PreviewWithProvider(ctx, args, provider)` to read live hive state for its preview; `PreviewWrite` prefers it over `Preview`, which remains the provider-less fallback. +A write op may also implement `PreviewWithProvider(ctx, args, provider)` to read live hive state for its preview; `PreviewWrite` prefers it over `Preview`, which remains the provider-less fallback. An op whose request is built from that state also implements `ConfirmGuard(ctx, args, provider)` and sets `StateFingerprint` on its preview, which is stored with the confirmation: `write_confirm` reads the state again and refuses with `ErrConfirmationStale`, writing nothing, when the fingerprint no longer matches. The preview returns a `WritePreview` containing the operator-facing summary, widening disclosure, and the REST `WriteRequest` to execute on confirmation. Keep new operations in their own files (for example `tools_agent_ops.go`, `tools_fleet_ops.go`, `tools_repo_ops.go`) so later phases can add operations without editing unrelated operation groups. Phase 3 registered `agent.pause` and `agent.resume`. Phase 4 extends the same `tools_agent_ops.go` group with `agent.nudge`, `agent.restart`, `agent.add`, `agent.remove`, `agent.model`, `agent.backend`, `agent.effort`, and `agent.interaction_tier`; it also adds the read-only `agent_nudge_status` lookup for `GET /api/kick/{agent}/status`. Nudge previews include the prompt verbatim in the confirmation message, because that text is typed into an agent CLI session. Interaction-tier previews carry explicit widening disclosure because `ISSUES_ONLY`, `ISSUES_AND_PRS`, and `ISSUES_PRS_MERGE` grant progressively broader GitHub authority. @@ -534,6 +534,7 @@ start-up script, its process launch, PIDs, signal handling and exit codes are un | plan propose | `POST /api/plan/from-issue` | **deliberately not owner** — ioscan + ACMM L5 floor | | plan approve / reject | `POST /api/plan/{epicID}/approve`, `.../reject` | `requireOwnerRole` | | feature settings | `PUT /api/config/governor/features` | `requireOwnerRole`; pointer fields, nil means unchanged | +| merge settings | `PATCH /api/config/auto-merge` | `requireOwnerRole` on the read and the write; every list and map is a full replace | | 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 | @@ -621,6 +622,20 @@ Phase 5 registers the fleet-level write operations under that contract: of the change in operator terms — a lower effective threshold engages a busier mode at a shallower queue, which raises agent cadence and spend — because the number alone does not tell an owner what it buys. +- `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 + trusted-author and contributor-lane repos and labels), so a one-repository change sent as is + would wipe the others. The op takes changes instead (`add`/`remove` per list, one repository's + human-merge paths set or unset), reads the current settings through `settings_read` section + `auto_merge` while previewing, and sends the merged whole value; the preview shows each change + before and after. Its `ConfirmGuard` fingerprints the before-value of every field it sends, so + a setting changed between preview and confirm refuses the confirm instead of being overwritten. + The preview names each change that lets the hive merge more on its own (a lane turned on, a + human-merge path removed, a repository added to an allow-list or an allow-list emptied, which + means every repository). Both the read and the write are owner only at the endpoint, and the + op merges nothing itself. `human_merge_pin_only` has no field on the endpoint, so the op + cannot reach it. 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 diff --git a/src/pkg/adminmcp/adminmcp.go b/src/pkg/adminmcp/adminmcp.go index 4351b0f28f..366e7a9543 100644 --- a/src/pkg/adminmcp/adminmcp.go +++ b/src/pkg/adminmcp/adminmcp.go @@ -496,6 +496,15 @@ type providerPreviewOp interface { PreviewWithProvider(ctx context.Context, args map[string]any, provider Provider) (WritePreview, error) } +// confirmGuardOp is implemented by write ops whose request was built from +// live hive state read at preview time (auto_merge.update sends whole lists +// merged into the current settings). ConfirmWrite asks it for that state's +// fingerprint again and refuses when it no longer matches the preview's +// StateFingerprint, so a request built from stale state is never sent. +type confirmGuardOp interface { + ConfirmGuard(ctx context.Context, args map[string]any, provider Provider) (string, error) +} + func (h *Handler) PreviewWrite(ctx context.Context, args map[string]any) (any, error) { if !h.writesUsable() { return nil, h.writesDisabledErr() @@ -590,6 +599,15 @@ func (h *Handler) ConfirmWrite(ctx context.Context, args map[string]any) (any, e if err := CheckRequestPath(pending.Preview.Request.Path); err != nil { return nil, err } + if guarded, ok := op.(confirmGuardOp); ok { + current, err := guarded.ConfirmGuard(ctx, pending.Args, h.Provider) + if err != nil { + return nil, err + } + if pending.Preview.StateFingerprint == "" || current != pending.Preview.StateFingerprint { + return nil, ErrConfirmationStale + } + } result, err := h.WriteClient.ExecuteWrite(ctx, pending.Preview.Request) if err != nil { return nil, err @@ -623,7 +641,7 @@ func pendingValueNeedsFreshConfirm(v any) bool { // caller of write_preview and would otherwise duplicate the args (up to a // 10 000-char nudge prompt) in every stored entry (#9162). func persistedPendingPreview(preview WritePreview) WritePreview { - return WritePreview{Operation: preview.Operation, Target: scrubOutboundString(preview.Target), Request: scrubPendingPreview(preview).Request} + return WritePreview{Operation: preview.Operation, Target: scrubOutboundString(preview.Target), Request: scrubPendingPreview(preview).Request, StateFingerprint: preview.StateFingerprint} } func scrubPendingPreview(preview WritePreview) WritePreview { diff --git a/src/pkg/adminmcp/tools_agent_ops.go b/src/pkg/adminmcp/tools_agent_ops.go index 41139cae71..f81f62a0ed 100644 --- a/src/pkg/adminmcp/tools_agent_ops.go +++ b/src/pkg/adminmcp/tools_agent_ops.go @@ -32,6 +32,7 @@ func DefaultWriteOps() []WriteOp { ops = append(ops, fleetWriteOps()...) ops = append(ops, stageTrackerWriteOps()...) ops = append(ops, githubCapWriteOps()...) + ops = append(ops, autoMergeWriteOps()...) return append(ops, governorWriteOps()...) } diff --git a/src/pkg/adminmcp/tools_automerge_ops.go b/src/pkg/adminmcp/tools_automerge_ops.go new file mode 100644 index 0000000000..f23287ffca --- /dev/null +++ b/src/pkg/adminmcp/tools_automerge_ops.go @@ -0,0 +1,874 @@ +package adminmcp + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "net/http" + "path/filepath" + "strings" + "time" + + "github.com/hivecommons/hive/pkg/config" +) + +// auto_merge.update changes the hive's merge settings through the endpoint the +// dashboard's merge controls use, PATCH /api/config/auto-merge +// (handleAutoMergePut). That endpoint replaces every list and map it is sent +// whole: squash_only ["a/b"] drops every other repository. So this op takes +// changes instead (entries to add and remove, one repository's human-merge +// paths to set or unset), reads the current settings while previewing, and +// sends each changed list or map as its whole merged value. The preview shows +// every changed setting before and after. ConfirmGuard reads the settings +// again at write_confirm and refuses when any of those before-values moved, so +// a merge built from a stale read never overwrites someone else's change. +// +// The op never merges a pull request. It changes which pull requests the merge +// sweeps may merge later, and the endpoint validates, saves and audits the +// change exactly as it does for the dashboard, for the owner only. +const ( + WriteOpAutoMergeUpdate = "auto_merge.update" + + autoMergeSettingsPath = "/api/config/auto-merge" + + // defaultAutoMergeMaxMerges mirrors automerge.DefaultAutoMergeSweepMaxMerges, + // what max_merges 0 means. It only words the widening check. + defaultAutoMergeMaxMerges = 3 +) + +func autoMergeWriteOps() []WriteOp { return []WriteOp{autoMergeUpdateOp{}} } + +type autoMergeUpdateOp struct{} + +type amKind int + +const ( + amBool amKind = iota + amInt + amDuration + amEnum + amList + amRepoPaths +) + +// amEntry is how a list's entries are compared. +type amEntry int + +const ( + amEntryExact amEntry = iota + amEntryFold + amEntryRepo // owner/repo or a bare project repo name, case-insensitive + amEntryBase // owner/repo#base, the repository part case-insensitive +) + +// amWiden is the rule that decides whether a change lets the hive merge more +// on its own. +type amWiden int + +const ( + amWidenNever amWiden = iota + amWidenOn // a boolean turned on + amWidenOff // a boolean turned off + amWidenRaise // a number raised (0 means def) + amWidenLower // a number or duration lowered (0 means def) + amWidenAdd // a list gains an entry + amWidenRemove // a list loses an entry + amWidenAllowList // a repository allow-list where empty means every repository + amWidenChecks // required_checks + amWidenTiers // contributor_lane.require_tiers, where empty means the default tiers + amWidenRole // trusted_authors.require_role from owner to merger + amWidenScope // contributor_lane.auto_promotion_scope from repo to hive + amWidenPaths // human_merge_paths loses a pattern +) + +type amField struct { + key string // body path, dotted for a nested object + kind amKind + entry amEntry + enum []string + def int // what 0 means, for amWidenRaise and amWidenLower on a number + positive bool // a duration must be above zero + widen amWiden + why string // what the widening lets the hive do +} + +// autoMergeFields is every body field handleAutoMergePut reads. A preview +// lists the changes in the order of the argument names. +var autoMergeFields = []amField{ + {key: "self_authored", kind: amBool, widen: amWidenOn, why: "the App merges its own CI-green pull requests with no human queue approval"}, + {key: "max_merges", kind: amInt, def: defaultAutoMergeMaxMerges, widen: amWidenRaise, why: "more merges per sweep pass"}, + {key: "min_head_age", kind: amDuration, positive: true, widen: amWidenLower, why: "a new head may merge sooner after a push, before slow checks have registered"}, + {key: "required_checks", kind: amList, widen: amWidenChecks, why: "the self-merge sweep gates on fewer named checks"}, + {key: "allow_unprotected_base", kind: amList, entry: amEntryRepo}, + {key: "no_ci_ok", kind: amList, entry: amEntryRepo, widen: amWidenAdd, why: "a repository with no CI at all counts as green to the merge-request relay"}, + {key: "trusted_bot_authors", kind: amList, entry: amEntryFold, widen: amWidenAdd, why: "these bots' green pull requests merge like the App's own"}, + {key: "squash_only", kind: amList, entry: amEntryRepo, widen: amWidenRemove, why: "a mixed-author pull request there merges with a merge commit instead of going back to a person"}, + {key: "require_current_base", kind: amList, entry: amEntryRepo, widen: amWidenRemove, why: "pull requests there may merge without the current base tip"}, + {key: "human_merge_paths", kind: amRepoPaths, widen: amWidenPaths, why: "pull requests touching these paths no longer wait for a person to merge them"}, + {key: "bot_takeover_enabled", kind: amBool, widen: amWidenOn, why: "the App re-authors trusted github-actions[bot] pull requests and merges its copy"}, + {key: "require_current_base_default", kind: amBool, widen: amWidenOff, why: "repositories without an override may merge without the current base tip"}, + {key: "merge_train.enabled", kind: amBool}, + {key: "merge_train.max_rebase_attempts", kind: amInt}, + {key: "native_merge_queue.enabled", kind: amBool, widen: amWidenOn, why: "eligible pull requests are handed to GitHub's merge queue"}, + {key: "native_merge_queue.repos", kind: amList, entry: amEntryRepo, widen: amWidenAllowList, why: "more repositories hand pull requests to GitHub's merge queue"}, + {key: "native_merge_queue.bases", kind: amList, entry: amEntryBase, widen: amWidenAdd, why: "more base branches hand pull requests to GitHub's merge queue"}, + {key: "native_merge_queue.skip_current_base_gate", kind: amBool, widen: amWidenOn, why: "queue-enabled bases skip the current-base gate"}, + {key: "native_merge_queue.probe_ttl", kind: amDuration}, + {key: "trusted_authors.enabled", kind: amBool, widen: amWidenOn, why: "pull requests by authors who hold merge authority merge with no review"}, + {key: "trusted_authors.repos", kind: amList, entry: amEntryRepo, widen: amWidenAllowList, why: "the trusted-author lane merges in more repositories"}, + {key: "trusted_authors.require_role", kind: amEnum, enum: []string{config.RoleMerger, config.RoleOwner}, widen: amWidenRole, why: "authors at the merger role qualify, not only owners"}, + {key: "trusted_authors.require_github_permission", kind: amBool, widen: amWidenOff, why: "authors qualify without GitHub write permission on the repository"}, + {key: "trusted_authors.exclude_labels", kind: amList, entry: amEntryFold, widen: amWidenRemove, why: "pull requests with these labels are no longer kept out of the trusted-author lane"}, + {key: "contributor_lane.enabled", kind: amBool, widen: amWidenOn, why: "contributor pull requests the hive dispatched merge once green, reviewed and soaked"}, + {key: "contributor_lane.soak_minutes", kind: amInt, def: config.DefaultContributorLaneSoakMinutes, widen: amWidenLower, why: "contributor pull requests merge after a shorter soak"}, + {key: "contributor_lane.require_reviewer_verdict", kind: amBool, widen: amWidenOff, why: "contributor pull requests merge without an approving reviewer verdict"}, + {key: "contributor_lane.repos", kind: amList, entry: amEntryRepo, widen: amWidenAllowList, why: "the contributor lane merges in more repositories"}, + {key: "contributor_lane.exclude_labels", kind: amList, entry: amEntryFold, widen: amWidenRemove, why: "pull requests with these labels are no longer kept out of the contributor lane"}, + {key: "contributor_lane.require_tiers", kind: amList, entry: amEntryFold, widen: amWidenTiers, why: "contributors at more trust tiers qualify for unattended merge"}, + {key: "contributor_lane.registry_tiers_sufficient", kind: amBool, widen: amWidenOn, why: "a registry tier alone admits a pull request, with no claim marker"}, + {key: "contributor_lane.auto_promotion_scope", kind: amEnum, enum: config.ContributorLaneAutoPromotionScopes, widen: amWidenScope, why: "merges in every repository count toward automatic promotion"}, + {key: "contributor_lane.approve_held_runs_for_registry_trusted", kind: amBool, widen: amWidenOn, why: "the hive approves held workflow runs for registry-trusted authors"}, + {key: "contributor_lane.owner_approval_releases_workflow_fence", kind: amBool, widen: amWidenOn, why: "an owner's approval lets the lane merge workflow-file changes"}, +} + +func (autoMergeUpdateOp) Name() string { return WriteOpAutoMergeUpdate } +func (autoMergeUpdateOp) Description() string { + return "Change merge settings (auto_merge) through PATCH /api/config/auto-merge, the endpoint the dashboard's merge controls use. Owner only. Pass only what changes, shaped like the endpoint's body. A list takes {\"add\": [...], \"remove\": [...]}; human_merge_paths takes {\"owner/repo\": [every pattern for that repository]}, with null or [] removing that repository. The preview reads the current settings and sends each changed list or map whole, keeping every entry you did not name, shows each change before and after, and says which changes let the hive merge more on its own. write_confirm refuses if any of those settings changed after the preview. This operation never merges a pull request. human_merge_pin_only is not on this endpoint." +} + +func (autoMergeUpdateOp) InputSchema() map[string]any { + props := map[string]any{} + groups := map[string]map[string]any{} + for i := range autoMergeFields { + f := &autoMergeFields[i] + group, name, nested := strings.Cut(f.key, ".") + if !nested { + props[f.key] = f.schema() + continue + } + if groups[group] == nil { + groups[group] = map[string]any{} + } + groups[group][name] = f.schema() + } + for group, sub := range groups { + props[group] = map[string]any{"type": "object", "properties": sub, "additionalProperties": false} + } + return map[string]any{"type": "object", "properties": props, "required": []string{}, "additionalProperties": false} +} + +func (f *amField) schema() map[string]any { + list := map[string]any{"type": "array", "items": stringSchema()} + switch f.kind { + case amBool: + return map[string]any{"type": "boolean"} + case amInt: + return map[string]any{"type": "integer", "minimum": 0} + case amDuration: + return map[string]any{"type": "string", "description": "A duration such as 3m or 1h30m."} + case amEnum: + return map[string]any{"type": "string", "enum": f.enum} + case amRepoPaths: + return map[string]any{"type": "object", "description": "owner/repo to every glob pattern that repository should hold; null or [] removes the repository. Repositories you do not name are kept.", "additionalProperties": map[string]any{"anyOf": []any{list, map[string]any{"type": "null"}}}} + default: + return map[string]any{"type": "object", "description": "Entries to add and to remove. Entries you do not name are kept.", "properties": map[string]any{"add": list, "remove": list}, "additionalProperties": false} + } +} + +// Preview cannot read the current settings, so it only checks that every +// argument names a field this op knows. write_preview uses +// PreviewWithProvider; write_confirm calls Preview to check the request still +// names this endpoint, and then ConfirmGuard reads the settings again. +func (autoMergeUpdateOp) Preview(_ context.Context, args map[string]any) (WritePreview, error) { + if _, err := parseAutoMergeArgs(args); err != nil { + return WritePreview{}, err + } + return WritePreview{ + Operation: WriteOpAutoMergeUpdate, + Summary: "Change merge settings (current settings not read)", + Target: "merge settings (auto_merge)", + Request: WriteRequest{Method: http.MethodPatch, Path: autoMergeSettingsPath}, + WideningDisclosure: "Potential widening: the current merge settings were not read, so this preview cannot say what would change.", + ConfirmationMessage: "Preview this change through write_preview to see what it would do.", + }, nil +} + +// PreviewWithProvider reads the current merge settings, merges the requested +// changes into them and previews the request that sends the result. +func (autoMergeUpdateOp) PreviewWithProvider(ctx context.Context, args map[string]any, provider Provider) (WritePreview, error) { + plan, err := planAutoMergeUpdate(ctx, args, provider) + if err != nil { + return WritePreview{}, err + } + fields := make([]string, 0, len(plan.changes)) + changes := make([]map[string]any, 0, len(plan.changes)) + lines := make([]string, 0, len(plan.changes)) + var notes []string + for _, c := range plan.changes { + fields = append(fields, c.field.key) + for _, row := range c.rows() { + changes = append(changes, map[string]any{"field": row.field, "before": row.before, "after": row.after}) + lines = append(lines, row.field+": "+compactJSON(row.before)+" → "+compactJSON(row.after)) + } + notes = append(notes, c.notes...) + } + disclosure := "No widening: none of these changes lets the hive merge more on its own. This operation merges nothing." + if len(notes) > 0 { + disclosure = "Widening: " + strings.Join(notes, "; ") + ". The merge sweeps may then merge these pull requests with no person involved. This operation itself merges nothing." + } + effects := []string{ + "Hive sends PATCH " + autoMergeSettingsPath + " with only the settings listed here. Each list or map goes as its whole new value, built from the current setting read for this preview, so entries you did not name are kept.", + "The endpoint validates the change with the same rules as the dashboard's merge settings, saves it, applies it without a restart and records a config_auto_merge audit entry. It is owner only.", + "This changes which pull requests the merge sweeps may merge from now on. It merges nothing itself.", + "write_confirm reads these settings again and refuses if any of them changed after this preview.", + } + if len(plan.unchanged) > 0 { + effects = append(effects, "Already as requested, so not sent: "+strings.Join(plan.unchanged, ", ")+".") + } + details := map[string]any{"fields": fields, "changes": changes} + if len(plan.unchanged) > 0 { + details["unchanged"] = plan.unchanged + } + return WritePreview{ + Operation: WriteOpAutoMergeUpdate, + Summary: "Change merge settings: " + strings.Join(fields, ", "), + Target: "merge settings (auto_merge)", + Request: WriteRequest{Method: http.MethodPatch, Path: autoMergeSettingsPath, Body: plan.body}, + Effects: effects, + WideningDisclosure: disclosure, + ConfirmationMessage: "Confirm changing merge settings: " + strings.Join(lines, "; ") + ".", + Details: details, + StateFingerprint: plan.fingerprint, + }, nil +} + +// ConfirmGuard reads the merge settings again and returns the fingerprint of +// the before-values the confirmation would overwrite. +func (autoMergeUpdateOp) ConfirmGuard(ctx context.Context, args map[string]any, provider Provider) (string, error) { + plan, err := planAutoMergeUpdate(ctx, args, provider) + if err != nil { + return "", fmt.Errorf("write_confirm checks the merge settings again before writing, and that check refused this change; preview it again: %w", err) + } + return plan.fingerprint, nil +} + +type amArg struct { + field *amField + raw any +} + +type amPlanned struct { + field *amField + before any + after any + notes []string +} + +type amPlan struct { + changes []amPlanned + unchanged []string + body map[string]any + fingerprint string +} + +type amRow struct { + field string + before, after any +} + +// rows splits a human_merge_paths change into one row per repository that +// changes, so a preview names repositories as values rather than as keys. +func (c amPlanned) rows() []amRow { + if c.field.kind != amRepoPaths { + return []amRow{{field: c.field.key, before: c.before, after: c.after}} + } + before := repoPathsValue(c.before) + after, _ := c.after.(map[string][]string) + var rows []amRow + for _, repo := range unionRepoKeys(before, after) { + b, a := before[repo], after[repo] + if compactJSON(b) == compactJSON(a) { + continue + } + rows = append(rows, amRow{field: c.field.key + "[" + repo + "]", before: nilAsEmpty(b), after: nilAsEmpty(a)}) + } + return rows +} + +func parseAutoMergeArgs(args map[string]any) ([]amArg, error) { + top := map[string]*amField{} + nested := map[string]map[string]*amField{} + for i := range autoMergeFields { + f := &autoMergeFields[i] + group, name, ok := strings.Cut(f.key, ".") + if !ok { + top[f.key] = f + continue + } + if nested[group] == nil { + nested[group] = map[string]*amField{} + } + nested[group][name] = f + } + var out []amArg + for _, key := range SortKeys(args) { + if sub, ok := nested[key]; ok { + obj, isObj := args[key].(map[string]any) + if !isObj { + return nil, fmt.Errorf("%s must be an object", key) + } + for _, name := range SortKeys(obj) { + f := sub[name] + if f == nil { + return nil, unknownAutoMergeField(key + "." + name) + } + out = append(out, amArg{field: f, raw: obj[name]}) + } + continue + } + f := top[key] + if f == nil { + return nil, unknownAutoMergeField(key) + } + out = append(out, amArg{field: f, raw: args[key]}) + } + if len(out) == 0 { + return nil, fmt.Errorf("at least one merge setting is required") + } + return out, nil +} + +func unknownAutoMergeField(key string) error { + if key == "human_merge_pin_only" { + return fmt.Errorf("human_merge_pin_only is not on PATCH %s, so this operation cannot change it; it is set in the hive configuration file", autoMergeSettingsPath) + } + return fmt.Errorf("unsupported merge setting %q", key) +} + +func planAutoMergeUpdate(ctx context.Context, args map[string]any, provider Provider) (amPlan, error) { + parsed, err := parseAutoMergeArgs(args) + if err != nil { + return amPlan{}, err + } + current, err := readAutoMergeSettings(ctx, provider) + if err != nil { + return amPlan{}, err + } + projectRepos := stringListValueLoose(current["project_repos"]) + plan := amPlan{body: map[string]any{}} + beforeValues := map[string]any{} + for _, a := range parsed { + f := a.field + before, ok := lookupSetting(current, f.key) + if !ok { + return amPlan{}, fmt.Errorf("this hive's merge settings do not report %s, so the change cannot be previewed against its current value; the hive may run an older build", f.key) + } + after, err := f.apply(before, a.raw, projectRepos) + if err != nil { + return amPlan{}, err + } + if compactJSON(before) == compactJSON(after) { + plan.unchanged = append(plan.unchanged, f.key) + continue + } + setSetting(plan.body, f.key, after) + beforeValues[f.key] = before + plan.changes = append(plan.changes, amPlanned{field: f, before: before, after: after, notes: f.widening(before, after, projectRepos)}) + } + if len(plan.changes) == 0 { + return amPlan{}, fmt.Errorf("nothing would change: %s already as requested", strings.Join(plan.unchanged, ", ")) + } + plan.fingerprint = settingsFingerprint(beforeValues) + return plan, nil +} + +// readAutoMergeSettings reads what the dashboard's merge settings show +// (settings_read section auto_merge, GET /api/config/auto-merge), which only a +// verified owner may read. Without it there is nothing to merge a change into, +// so the preview is refused rather than guessed. +func readAutoMergeSettings(ctx context.Context, provider Provider) (map[string]any, error) { + if provider == nil { + return nil, fmt.Errorf("%s reads the current merge settings first, and this connection cannot read them", WriteOpAutoMergeUpdate) + } + data, err := provider.Read(ctx, ToolSettingsRead, map[string]any{"section": "auto_merge"}) + if err != nil { + return nil, fmt.Errorf("%s needs the current merge settings, which only the hive's verified owner can read: %w", WriteOpAutoMergeUpdate, err) + } + m, ok := data.(map[string]any) + if !ok || len(m) == 0 { + return nil, fmt.Errorf("%s could not read the current merge settings", WriteOpAutoMergeUpdate) + } + return m, nil +} + +func lookupSetting(m map[string]any, key string) (any, bool) { + group, name, nested := strings.Cut(key, ".") + if !nested { + v, ok := m[key] + return v, ok + } + sub, _ := m[group].(map[string]any) + if sub == nil { + return nil, false + } + v, ok := sub[name] + return v, ok +} + +func setSetting(body map[string]any, key string, value any) { + group, name, nested := strings.Cut(key, ".") + if !nested { + body[key] = value + return + } + sub, _ := body[group].(map[string]any) + if sub == nil { + sub = map[string]any{} + body[group] = sub + } + sub[name] = value +} + +// settingsFingerprint hashes the before-value of every field a change sends. +// encoding/json sorts map keys, so equal settings hash equally. +func settingsFingerprint(before map[string]any) string { + b, _ := json.Marshal(before) + sum := sha256.Sum256(b) + return hex.EncodeToString(sum[:]) +} + +// apply returns the value to send for f: the argument itself for a scalar, +// the merged whole value for a list or map. +func (f *amField) apply(before, raw any, projectRepos []string) (any, error) { + switch f.kind { + case amBool: + v, ok := raw.(bool) + if !ok { + return nil, fmt.Errorf("%s must be true or false", f.key) + } + return v, nil + case amInt: + n, ok := wholeNumber(raw) + if !ok || n < 0 { + return nil, fmt.Errorf("%s must be a whole number of at least 0", f.key) + } + return n, nil + case amDuration: + s, _ := raw.(string) + d, err := time.ParseDuration(strings.TrimSpace(s)) + if err != nil || d < 0 || (f.positive && d == 0) { + bound := "0 or more" + if f.positive { + bound = "above zero" + } + return nil, fmt.Errorf("%s must be a duration such as 3m, %s", f.key, bound) + } + return d.String(), nil + case amEnum: + s, _ := raw.(string) + s = strings.ToLower(strings.TrimSpace(s)) + for _, allowed := range f.enum { + if s == allowed { + return s, nil + } + } + return nil, fmt.Errorf("%s must be one of %s", f.key, strings.Join(f.enum, ", ")) + case amRepoPaths: + return applyRepoPaths(before, raw, projectRepos) + default: + return f.applyList(before, raw, projectRepos) + } +} + +func (f *amField) applyList(before, raw any, projectRepos []string) ([]string, error) { + change, ok := raw.(map[string]any) + if !ok { + return nil, fmt.Errorf("%s takes {\"add\": [...], \"remove\": [...]}", f.key) + } + for k := range change { + if k != "add" && k != "remove" { + return nil, fmt.Errorf("%s takes only add and remove, not %q", f.key, k) + } + } + add, err := f.entries(change["add"], "add", projectRepos) + if err != nil { + return nil, err + } + remove, err := f.entries(change["remove"], "remove", projectRepos) + if err != nil { + return nil, err + } + if len(add)+len(remove) == 0 { + return nil, fmt.Errorf("%s needs entries to add or remove", f.key) + } + cur := stringListValueLoose(before) + have := map[string]bool{} + for _, c := range cur { + have[f.norm(c, projectRepos)] = true + } + drop := map[string]bool{} + for _, r := range remove { + k := f.norm(r, projectRepos) + if !have[k] { + return nil, fmt.Errorf("%s does not hold %q (now: %s)", f.key, r, listOrNone(cur)) + } + drop[k] = true + } + out := make([]string, 0, len(cur)+len(add)) + for _, c := range cur { + if !drop[f.norm(c, projectRepos)] { + out = append(out, c) + } + } + for _, a := range add { + k := f.norm(a, projectRepos) + if drop[k] { + return nil, fmt.Errorf("%s: %q is both added and removed", f.key, a) + } + if have[k] { + continue + } + have[k] = true + out = append(out, a) + } + return out, nil +} + +// entries checks one add or remove list and returns its entries in the form +// the endpoint stores. +func (f *amField) entries(raw any, which string, projectRepos []string) ([]string, error) { + list, err := stringListValue(raw) + if err != nil { + return nil, fmt.Errorf("%s.%s must be a list of strings", f.key, which) + } + out := make([]string, 0, len(list)) + for _, e := range list { + e = strings.TrimSpace(e) + if e == "" { + return nil, fmt.Errorf("%s.%s entries must be non-empty", f.key, which) + } + switch f.entry { + case amEntryRepo: + if strings.ContainsAny(e, " \t#") { + return nil, fmt.Errorf("%s: %q is not a repository name", f.key, e) + } + e = qualifyProjectRepo(e, projectRepos) + case amEntryBase: + repo, base, ok := strings.Cut(e, "#") + if !ok || repo == "" || base == "" || strings.ContainsAny(e, " \t") { + return nil, fmt.Errorf("%s: %q is not an owner/repo#base pair", f.key, e) + } + e = strings.ToLower(repo) + "#" + base + } + out = append(out, e) + } + return out, nil +} + +func (f *amField) norm(e string, projectRepos []string) string { + e = strings.TrimSpace(e) + switch f.entry { + case amEntryFold: + return strings.ToLower(e) + case amEntryRepo: + return strings.ToLower(qualifyProjectRepo(e, projectRepos)) + case amEntryBase: + repo, base, _ := strings.Cut(e, "#") + return strings.ToLower(repo) + "#" + base + } + return e +} + +// applyRepoPaths sets or unsets the named repositories' human-merge paths and +// keeps every other repository's entry. +func applyRepoPaths(before, raw any, projectRepos []string) (map[string][]string, error) { + change, ok := raw.(map[string]any) + if !ok || len(change) == 0 { + return nil, fmt.Errorf("human_merge_paths takes {\"owner/repo\": [every pattern for it]}; null or [] removes that repository") + } + out := map[string][]string{} + for repo, patterns := range repoPathsValue(before) { + out[repo] = patterns + } + touched := map[string]bool{} + for _, key := range SortKeys(change) { + repo := qualifyProjectRepo(strings.TrimSpace(key), projectRepos) + owner, name, ok := strings.Cut(repo, "/") + if !ok || owner == "" || name == "" || strings.Contains(name, "/") || strings.ContainsAny(repo, " \t") { + return nil, fmt.Errorf("human_merge_paths: %q is not an owner/repo name", key) + } + if touched[strings.ToLower(repo)] { + return nil, fmt.Errorf("human_merge_paths names %s twice", repo) + } + touched[strings.ToLower(repo)] = true + list, err := stringListValue(change[key]) + if err != nil { + return nil, fmt.Errorf("human_merge_paths[%s] must be a list of glob patterns or null", repo) + } + patterns := make([]string, 0, len(list)) + seen := map[string]bool{} + for _, p := range list { + p = strings.TrimSpace(p) + if p == "" { + return nil, fmt.Errorf("human_merge_paths[%s] patterns must be non-empty", repo) + } + if _, err := filepath.Match(p, ""); err != nil { + return nil, fmt.Errorf("human_merge_paths[%s]: %s is not a valid glob", repo, p) + } + if !seen[p] { + seen[p] = true + patterns = append(patterns, p) + } + } + existing := "" + for k := range out { + if strings.EqualFold(k, repo) { + existing = k + } + } + if len(patterns) == 0 { + if existing == "" { + return nil, fmt.Errorf("human_merge_paths has no entry for %s to remove", repo) + } + delete(out, existing) + continue + } + if existing != "" { + repo = existing + } + out[repo] = patterns + } + return out, nil +} + +// widening names what a change lets the hive merge on its own, if anything. +func (f *amField) widening(before, after any, projectRepos []string) []string { + note := func(what string) []string { return []string{f.key + " " + what + ": " + f.why} } + switch f.widen { + case amWidenOn: + if b, _ := before.(bool); !b && after == true { + return note("turned on") + } + case amWidenOff: + if b, _ := before.(bool); b && after == false { + return note("turned off") + } + case amWidenRaise, amWidenLower: + from, to, ok := f.compare(before, after) + if ok && ((f.widen == amWidenRaise && to > from) || (f.widen == amWidenLower && to < from)) { + return note(compactJSON(before) + " → " + compactJSON(after)) + } + case amWidenAdd: + if added := f.diff(after, before, projectRepos); len(added) > 0 { + return note("adds " + strings.Join(added, ", ")) + } + case amWidenRemove, amWidenChecks: + removed := f.diff(before, after, projectRepos) + if len(removed) > 0 { + return note("removes " + strings.Join(removed, ", ")) + } + if f.widen == amWidenChecks && len(stringListValueLoose(before)) == 0 { + return []string{f.key + " is declared for the first time: the self-merge sweep then gates on this list instead of the branch's own required checks, which may hold fewer"} + } + case amWidenAllowList: + was, now := stringListValueLoose(before), stringListValueLoose(after) + if len(was) > 0 && len(now) == 0 { + return []string{f.key + " becomes empty, which means every repository: " + f.why} + } + if added := f.diff(after, before, projectRepos); len(was) > 0 && len(added) > 0 { + return note("adds " + strings.Join(added, ", ")) + } + case amWidenTiers: + now := after + if len(stringListValueLoose(after)) == 0 { + now = config.DefaultContributorLaneRequireTiers + } + if added := f.diff(now, before, projectRepos); len(added) > 0 { + return note("adds " + strings.Join(added, ", ")) + } + case amWidenRole: + if before == config.RoleOwner && after == config.RoleMerger { + return note("owner → merger") + } + case amWidenScope: + if before == config.ContributorLaneAutoPromotionScopeRepo && after == config.ContributorLaneAutoPromotionScopeHive { + return note("repo → hive") + } + case amWidenPaths: + was := repoPathsValue(before) + now, _ := after.(map[string][]string) + var notes []string + for _, repo := range unionRepoKeys(was, now) { + kept := map[string]bool{} + for _, p := range now[repo] { + kept[p] = true + } + var removed []string + for _, p := range was[repo] { + if !kept[p] { + removed = append(removed, p) + } + } + if len(removed) > 0 { + notes = append(notes, f.key+"["+repo+"] removes "+strings.Join(removed, ", ")+": "+f.why) + } + } + return notes + } + return nil +} + +// compare returns a number or duration setting's before and after as +// comparable values, with 0 standing for the default where it does. +func (f *amField) compare(before, after any) (int64, int64, bool) { + if f.kind == amDuration { + b, err1 := time.ParseDuration(fmt.Sprint(before)) + a, err2 := time.ParseDuration(fmt.Sprint(after)) + return int64(b), int64(a), err1 == nil && err2 == nil + } + b, ok1 := wholeNumber(before) + a, ok2 := wholeNumber(after) + if f.def > 0 { + if b == 0 { + b = f.def + } + if a == 0 { + a = f.def + } + } + return int64(b), int64(a), ok1 && ok2 +} + +// diff returns the entries of a that b does not hold. +func (f *amField) diff(a, b any, projectRepos []string) []string { + have := map[string]bool{} + for _, e := range stringListValueLoose(b) { + have[f.norm(e, projectRepos)] = true + } + var out []string + for _, e := range stringListValueLoose(a) { + if !have[f.norm(e, projectRepos)] { + out = append(out, e) + } + } + return out +} + +// qualifyProjectRepo turns a bare repository name into the project +// repository's owner/repo, as the endpoint does for project.repos. +func qualifyProjectRepo(repo string, projectRepos []string) string { + if strings.Contains(repo, "/") { + return repo + } + for _, full := range projectRepos { + if _, name, ok := strings.Cut(full, "/"); ok && strings.EqualFold(name, repo) { + return full + } + } + return repo +} + +func repoPathsValue(v any) map[string][]string { + out := map[string][]string{} + switch m := v.(type) { + case map[string]any: + for repo, patterns := range m { + out[repo] = stringListValueLoose(patterns) + } + case map[string][]string: + for repo, patterns := range m { + out[repo] = patterns + } + } + return out +} + +func unionRepoKeys(a, b map[string][]string) []string { + keys := map[string]any{} + for k := range a { + keys[k] = nil + } + for k := range b { + keys[k] = nil + } + return SortKeys(keys) +} + +// stringListValue reads a JSON list of strings; nil is an empty list. +func stringListValue(v any) ([]string, error) { + switch list := v.(type) { + case nil: + return nil, nil + case []string: + return append([]string(nil), list...), nil + case []any: + out := make([]string, 0, len(list)) + for _, item := range list { + s, ok := item.(string) + if !ok { + return nil, fmt.Errorf("not a string") + } + out = append(out, s) + } + return out, nil + } + return nil, fmt.Errorf("not a list") +} + +// stringListValueLoose reads a list the hive returned, skipping anything that +// is not a string. +func stringListValueLoose(v any) []string { + switch list := v.(type) { + case []string: + return list + case []any: + out := make([]string, 0, len(list)) + for _, item := range list { + if s, ok := item.(string); ok { + out = append(out, s) + } + } + return out + } + return nil +} + +func wholeNumber(v any) (int, bool) { + switch n := v.(type) { + case int: + return n, true + case float64: + if n != float64(int(n)) { + return 0, false + } + return int(n), true + case json.Number: + i, err := n.Int64() + return int(i), err == nil + } + return 0, false +} + +func nilAsEmpty(list []string) []string { + if list == nil { + return []string{} + } + return list +} + +func listOrNone(list []string) string { + if len(list) == 0 { + return "empty" + } + return strings.Join(list, ", ") +} + +func compactJSON(v any) string { + b, err := json.Marshal(v) + if err != nil { + return fmt.Sprint(v) + } + return string(b) +} diff --git a/src/pkg/adminmcp/tools_automerge_ops_test.go b/src/pkg/adminmcp/tools_automerge_ops_test.go new file mode 100644 index 0000000000..953f851157 --- /dev/null +++ b/src/pkg/adminmcp/tools_automerge_ops_test.go @@ -0,0 +1,264 @@ +package adminmcp + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "strings" + "testing" +) + +// autoMergeProvider answers settings_read section auto_merge with a copy of +// settings, decoded from JSON as the endpoint's answer is, and records writes. +type autoMergeProvider struct { + settings map[string]any + readErr error + reads int + requests []WriteRequest +} + +func (p *autoMergeProvider) Read(_ context.Context, tool string, args map[string]any) (any, error) { + if tool != ToolSettingsRead || args["section"] != "auto_merge" { + return map[string]any{}, nil + } + p.reads++ + if p.readErr != nil { + return nil, p.readErr + } + b, err := json.Marshal(p.settings) + if err != nil { + return nil, err + } + var out map[string]any + if err := json.Unmarshal(b, &out); err != nil { + return nil, err + } + return out, nil +} + +func (p *autoMergeProvider) ExecuteWrite(_ context.Context, req WriteRequest) (any, error) { + p.requests = append(p.requests, req) + return map[string]any{"ok": true}, nil +} + +// autoMergeFixture is GET /api/config/auto-merge for a hive with three +// project repositories, two of them squash-only and with human-merge paths. +func autoMergeFixture() map[string]any { + return map[string]any{ + "self_authored": true, + "max_merges": 0, + "min_head_age": "3m0s", + "required_checks": []string{"build"}, + "allow_unprotected_base": []string{}, + "no_ci_ok": []string{}, + "squash_only": []string{"org/a", "org/b"}, + "require_current_base": []string{}, + "human_merge_paths": map[string][]string{"org/a": {".github/workflows/**", ".claude/hooks/**"}, "org/b": {"CODEOWNERS"}}, + "project_repos": []string{"org/a", "org/b", "org/c"}, + "trusted_bot_authors": []string{"dependabot[bot]"}, + "bot_takeover_enabled": false, + "require_current_base_default": false, + "merge_train": map[string]any{"enabled": true, "max_rebase_attempts": 2}, + "native_merge_queue": map[string]any{"enabled": true, "repos": []string{"org/a"}, "bases": []string{"org/a#main"}, "skip_current_base_gate": false, "probe_ttl": "30m0s"}, + "trusted_authors": map[string]any{"enabled": false, "repos": []string{}, "require_role": "owner", "require_github_permission": true, "exclude_labels": []string{"hold"}}, + "contributor_lane": map[string]any{ + "enabled": true, "soak_minutes": 30, "require_reviewer_verdict": true, "repos": []string{"org/a"}, + "exclude_labels": []string{"hold"}, "require_tiers": []string{"merger", "trusted"}, "registry_tiers_sufficient": true, + "auto_promotion_scope": "hive", "approve_held_runs_for_registry_trusted": true, "owner_approval_releases_workflow_fence": true, + }, + } +} + +func autoMergeHandler(p *autoMergeProvider) *Handler { + return NewHandler(p, WithWritesEnabled(true), WithPendingStore(NewMemoryPendingStore()), WithHiveID("hive-a")) +} + +func autoMergePreview(t *testing.T, h *Handler, args map[string]any) (WritePreview, string) { + t.Helper() + out, err := h.PreviewWrite(context.Background(), map[string]any{"operation": WriteOpAutoMergeUpdate, "args": args}) + if err != nil { + t.Fatalf("preview %v: %v", args, err) + } + m := out.(map[string]any) + return m["preview"].(WritePreview), m["confirmation_id"].(string) +} + +func TestAutoMergeUpdateRegistered(t *testing.T) { + if _, ok := DefaultWriteRegistry().Get(WriteOpAutoMergeUpdate); !ok { + t.Fatalf("%s is not registered", WriteOpAutoMergeUpdate) + } +} + +// An argument the endpoint does not take is refused before anything is read, +// at the top level and inside a nested object; human_merge_pin_only, which +// the endpoint has no field for, says so. +func TestAutoMergeUpdateRejectsUnknownFields(t *testing.T) { + for name, tc := range map[string]struct { + args map[string]any + want string + }{ + "top-level typo": {map[string]any{"squash_onyl": map[string]any{"add": []any{"org/c"}}}, `unsupported merge setting "squash_onyl"`}, + "nested unknown": {map[string]any{"contributor_lane": map[string]any{"enabled": true, "workflow_fence_scope": "all"}}, `unsupported merge setting "contributor_lane.workflow_fence_scope"`}, + "dotted top-level": {map[string]any{"merge_train.enabled": false}, `unsupported merge setting "merge_train.enabled"`}, + "pin-only": {map[string]any{"human_merge_pin_only": map[string]any{"org/a": map[string]any{"enabled": true}}}, "human_merge_pin_only is not on PATCH /api/config/auto-merge"}, + "list without add": {map[string]any{"squash_only": map[string]any{"set": []any{"org/c"}}}, "takes only add and remove"}, + "list given as array": {map[string]any{"squash_only": []any{"org/c"}}, `takes {"add"`}, + } { + t.Run(name, func(t *testing.T) { + p := &autoMergeProvider{settings: autoMergeFixture()} + h := autoMergeHandler(p) + _, err := h.PreviewWrite(context.Background(), map[string]any{"operation": WriteOpAutoMergeUpdate, "args": tc.args}) + if err == nil || !strings.Contains(err.Error(), tc.want) { + t.Fatalf("err = %v, want it to contain %q", err, tc.want) + } + if pending, _ := h.PendingStore.List(context.Background()); len(pending) != 0 { + t.Fatalf("a refused preview minted a confirmation: %+v", pending) + } + if len(p.requests) != 0 { + t.Fatalf("a refused preview wrote: %+v", p.requests) + } + }) + } +} + +// The endpoint replaces a list or map whole, so a change to one repository +// must send every other repository's entry back unchanged. +func TestAutoMergeUpdateOneRepoChangeKeepsTheOthers(t *testing.T) { + p := &autoMergeProvider{settings: autoMergeFixture()} + h := autoMergeHandler(p) + preview, id := autoMergePreview(t, h, map[string]any{ + "human_merge_paths": map[string]any{"org/c": []any{"infra/**"}}, + "squash_only": map[string]any{"add": []any{"c"}}, + }) + if preview.Request.Method != http.MethodPatch || preview.Request.Path != "/api/config/auto-merge" { + t.Fatalf("request = %s %s", preview.Request.Method, preview.Request.Path) + } + want := `{"human_merge_paths":{"org/a":[".github/workflows/**",".claude/hooks/**"],"org/b":["CODEOWNERS"],"org/c":["infra/**"]},"squash_only":["org/a","org/b","org/c"]}` + if got := compactJSON(preview.Request.Body); got != want { + t.Fatalf("body = %s\nwant %s", got, want) + } + if !strings.HasPrefix(preview.WideningDisclosure, "No widening:") { + t.Fatalf("adding a guarded path and a squash-only repository is not widening: %s", preview.WideningDisclosure) + } + changes, _ := preview.Details["changes"].([]map[string]any) + if len(changes) != 2 || changes[0]["field"] != "human_merge_paths[org/c]" || changes[1]["field"] != "squash_only" { + t.Fatalf("changes = %+v, want human_merge_paths[org/c] and squash_only before and after", changes) + } + if _, err := h.ConfirmWrite(context.Background(), map[string]any{"confirmation_id": id}); err != nil { + t.Fatalf("confirm: %v", err) + } + if len(p.requests) != 1 || compactJSON(p.requests[0].Body) != want { + t.Fatalf("executed %+v, want body %s", p.requests, want) + } +} + +// Taking a pattern away from human_merge_paths lets the hive merge pull +// requests that touch it, so the preview must say so; adding one must not. +func TestAutoMergeUpdateFlagsHumanMergePathRemovalAsWidening(t *testing.T) { + for name, tc := range map[string]struct { + args map[string]any + widen bool + names string + }{ + "drop one pattern": {map[string]any{"human_merge_paths": map[string]any{"org/a": []any{".github/workflows/**"}}}, true, ".claude/hooks/**"}, + "unset a repository": {map[string]any{"human_merge_paths": map[string]any{"org/b": nil}}, true, "CODEOWNERS"}, + "add a pattern": {map[string]any{"human_merge_paths": map[string]any{"org/b": []any{"CODEOWNERS", "SECURITY.md"}}}, false, ""}, + } { + t.Run(name, func(t *testing.T) { + preview, _ := autoMergePreview(t, autoMergeHandler(&autoMergeProvider{settings: autoMergeFixture()}), tc.args) + if got := strings.HasPrefix(preview.WideningDisclosure, "Widening:"); got != tc.widen { + t.Fatalf("widening = %v, want %v: %s", got, tc.widen, preview.WideningDisclosure) + } + if tc.widen && !strings.Contains(preview.WideningDisclosure, tc.names) { + t.Fatalf("disclosure does not name %s: %s", tc.names, preview.WideningDisclosure) + } + }) + } +} + +// Other changes that let the hive merge more on its own, and two that look +// similar but do not. +func TestAutoMergeUpdateWideningRules(t *testing.T) { + for name, tc := range map[string]struct { + args map[string]any + widen bool + }{ + "trusted authors on": {map[string]any{"trusted_authors": map[string]any{"enabled": true}}, true}, + "trusted role to merger": {map[string]any{"trusted_authors": map[string]any{"require_role": "merger"}}, true}, + "merge queue gains a repo": {map[string]any{"native_merge_queue": map[string]any{"repos": map[string]any{"add": []any{"org/b"}}}}, true}, + "lane allow-list emptied": {map[string]any{"contributor_lane": map[string]any{"repos": map[string]any{"remove": []any{"org/a"}}}}, true}, + "lane allow-list grows": {map[string]any{"contributor_lane": map[string]any{"repos": map[string]any{"add": []any{"org/b"}}}}, true}, + "required check removed": {map[string]any{"required_checks": map[string]any{"remove": []any{"build"}}}, true}, + "squash-only repo removed": {map[string]any{"squash_only": map[string]any{"remove": []any{"org/b"}}}, true}, + "soak shortened": {map[string]any{"contributor_lane": map[string]any{"soak_minutes": float64(10)}}, true}, + "soak 0 is the default 30": {map[string]any{"contributor_lane": map[string]any{"soak_minutes": float64(0)}}, false}, + "exclude label added": {map[string]any{"trusted_authors": map[string]any{"exclude_labels": map[string]any{"add": []any{"wip"}}}}, false}, + "self-authored switched off": {map[string]any{"self_authored": false}, false}, + } { + t.Run(name, func(t *testing.T) { + preview, _ := autoMergePreview(t, autoMergeHandler(&autoMergeProvider{settings: autoMergeFixture()}), tc.args) + if got := strings.HasPrefix(preview.WideningDisclosure, "Widening:"); got != tc.widen { + t.Fatalf("widening = %v, want %v: %s", got, tc.widen, preview.WideningDisclosure) + } + }) + } +} + +// A preview is built from the settings it read. If a setting it would send +// changes before write_confirm, sending the preview's merged value would undo +// that change, so the confirm is refused and nothing is written. A change to +// a setting the preview does not send does not block it. +func TestAutoMergeUpdateRefusesStalePreview(t *testing.T) { + p := &autoMergeProvider{settings: autoMergeFixture()} + h := autoMergeHandler(p) + args := map[string]any{"squash_only": map[string]any{"add": []any{"org/c"}}} + + _, id := autoMergePreview(t, h, args) + p.settings["squash_only"] = []string{"org/a"} // someone removed org/b meanwhile + if _, err := h.ConfirmWrite(context.Background(), map[string]any{"confirmation_id": id}); !errors.Is(err, ErrConfirmationStale) { + t.Fatalf("confirm err = %v, want ErrConfirmationStale", err) + } + if len(p.requests) != 0 { + t.Fatalf("a stale confirmation wrote: %+v", p.requests) + } + + preview, id := autoMergePreview(t, h, args) + if got := compactJSON(preview.Request.Body); got != `{"squash_only":["org/a","org/c"]}` { + t.Fatalf("fresh preview body = %s", got) + } + p.settings["max_merges"] = 5 // not sent, so not stale + if _, err := h.ConfirmWrite(context.Background(), map[string]any{"confirmation_id": id}); err != nil { + t.Fatalf("confirm after an unrelated change: %v", err) + } + if len(p.requests) != 1 || compactJSON(p.requests[0].Body) != `{"squash_only":["org/a","org/c"]}` { + t.Fatalf("executed %+v", p.requests) + } +} + +// Merge settings are owner only. A caller the hive does not verify as owner +// cannot read them, so the preview is refused with no confirmation minted; +// and a confirmation whose re-read is refused writes nothing. +func TestAutoMergeUpdateRefusesNonOwner(t *testing.T) { + ownerOnly := fmt.Errorf("%w: Hive API returned HTTP 403: owner access required", ErrForbidden) + p := &autoMergeProvider{settings: autoMergeFixture(), readErr: ownerOnly} + h := autoMergeHandler(p) + _, err := h.PreviewWrite(context.Background(), map[string]any{"operation": WriteOpAutoMergeUpdate, "args": map[string]any{"self_authored": false}}) + if err == nil || !errors.Is(err, ErrForbidden) || !strings.Contains(err.Error(), "verified owner") { + t.Fatalf("non-owner preview err = %v", err) + } + if pending, _ := h.PendingStore.List(context.Background()); len(pending) != 0 { + t.Fatalf("a non-owner preview minted a confirmation: %+v", pending) + } + + p.readErr = nil + _, id := autoMergePreview(t, h, map[string]any{"self_authored": false}) + p.readErr = ownerOnly + if _, err := h.ConfirmWrite(context.Background(), map[string]any{"confirmation_id": id}); err == nil { + t.Fatal("a confirm whose re-read was refused went through") + } + if len(p.requests) != 0 { + t.Fatalf("wrote without owner access: %+v", p.requests) + } +} diff --git a/src/pkg/adminmcp/write_contract.go b/src/pkg/adminmcp/write_contract.go index 2f9e34a270..267feca12a 100644 --- a/src/pkg/adminmcp/write_contract.go +++ b/src/pkg/adminmcp/write_contract.go @@ -34,6 +34,7 @@ var ( 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") + ErrConfirmationStale = errors.New("admin MCP confirmation is stale: the settings it was previewed against changed after the preview; preview it again") ) type WriteClient interface { @@ -55,6 +56,10 @@ type WritePreview struct { WideningDisclosure string `json:"widening_disclosure"` ConfirmationMessage string `json:"confirmation_message"` Details map[string]any `json:"details,omitempty"` + // StateFingerprint is set by an op whose request was built from live + // hive state (confirmGuardOp). It is stored with the confirmation, and + // write_confirm refuses when the state no longer matches it. + StateFingerprint string `json:"state_fingerprint,omitempty"` } type WriteOp interface { From 087166c51a9dc307be65574d02e534467863f190 Mon Sep 17 00:00:00 2001 From: Danathar Date: Mon, 9 Nov 2026 19:44:27 -0500 Subject: [PATCH 2/4] =?UTF-8?q?=F0=9F=90=9B=20fix(adminmcp):=20use=20a=20n?= =?UTF-8?q?on-misspelled=20unknown=20key=20in=20the=20auto=5Fmerge.update?= =?UTF-8?q?=20test?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit golangci-lint's misspell check flagged the deliberate typo "squash_onyl". The test only needs a key the op does not accept; "squash_repos" is one. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BQYnPGFJx81c8JXR3o1sg1 Signed-off-by: Danathar --- src/pkg/adminmcp/tools_automerge_ops_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pkg/adminmcp/tools_automerge_ops_test.go b/src/pkg/adminmcp/tools_automerge_ops_test.go index 953f851157..a2e03c056d 100644 --- a/src/pkg/adminmcp/tools_automerge_ops_test.go +++ b/src/pkg/adminmcp/tools_automerge_ops_test.go @@ -99,7 +99,7 @@ func TestAutoMergeUpdateRejectsUnknownFields(t *testing.T) { args map[string]any want string }{ - "top-level typo": {map[string]any{"squash_onyl": map[string]any{"add": []any{"org/c"}}}, `unsupported merge setting "squash_onyl"`}, + "top-level typo": {map[string]any{"squash_repos": map[string]any{"add": []any{"org/c"}}}, `unsupported merge setting "squash_repos"`}, "nested unknown": {map[string]any{"contributor_lane": map[string]any{"enabled": true, "workflow_fence_scope": "all"}}, `unsupported merge setting "contributor_lane.workflow_fence_scope"`}, "dotted top-level": {map[string]any{"merge_train.enabled": false}, `unsupported merge setting "merge_train.enabled"`}, "pin-only": {map[string]any{"human_merge_pin_only": map[string]any{"org/a": map[string]any{"enabled": true}}}, "human_merge_pin_only is not on PATCH /api/config/auto-merge"}, From d7702d3f59a6ac25c41a828826aaef75744591c6 Mon Sep 17 00:00:00 2001 From: Danathar Date: Mon, 9 Nov 2026 20:05:44 -0500 Subject: [PATCH 3/4] =?UTF-8?q?=E2=9C=A8=20feat(automerge):=20the=20pin-on?= =?UTF-8?q?ly=20exception=20can=20be=20set=20from=20the=20dashboard=20and?= =?UTF-8?q?=20admin=20MCP?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit auto_merge.human_merge_pin_only (#16377) could only be set in hive.yaml, so a hosted hive needed a seed edit. PUT/PATCH /api/config/auto-merge now takes it as a whole map, like human_merge_paths: keys are checked against project.repos and stored as owner/repo, lists are trimmed and de-duplicated, the map must pass ValidateHumanMergePinOnly, and an enabled entry the write adds or changes is refused for a repository with no human_merge_paths, where it would never apply. GET returns it with pin_only_kinds. A write reaches the running hive at once: the sweep lanes and /approve read the shared config, and the dashboard's GitHub-client sync now refreshes the merge-request relay's copy too. A write that cannot be saved is rolled back. Settings -> Features -> Auto-merge gets a per-repository editor next to the human-merge paths. The admin MCP op auto_merge.update sets or unsets one repository's exception and keeps the others, shows it before and after, fingerprints it for the stale-preview check, and names turning one on or adding paths, kinds or trusted authors as widening. What counts as a pin bump, and every other merge gate, is unchanged. Refs #16377 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BQYnPGFJx81c8JXR3o1sg1 Signed-off-by: Danathar --- .../added-adminmcp-auto-merge-update.md | 2 +- .../added-automerge-pin-only-setting.md | 1 + src/docs/admin-mcp.md | 17 +- src/docs/api-reference.md | 2 +- src/docs/api-reference/configuration.md | 2 +- src/docs/design/admin-mcp.md | 5 +- src/docs/hive-merge.md | 9 +- src/docs/operator-reference/README.md | 39 ++- src/docs/settings.md | 2 +- src/pkg/adminmcp/tools_automerge_ops.go | 277 +++++++++++++++++- src/pkg/adminmcp/tools_automerge_ops_test.go | 4 +- .../adminmcp/tools_automerge_pin_only_test.go | 156 ++++++++++ src/pkg/adminmcp/tools_settings.go | 2 +- src/pkg/config/automerge_pin_only.go | 9 +- src/pkg/dashboard/api_config_automerge.go | 131 ++++++++- .../api_config_automerge_pin_only_test.go | 269 +++++++++++++++++ .../dashboard/settings_parity_allowlist.txt | 4 - .../static-src/css/config-dialog.css | 2 + .../static-src/js/config-features.js | 25 +- .../dashboard/static-src/js/config-helpers.js | 20 ++ src/pkg/dashboard/static/index.html | 47 ++- src/pkg/github/human_merge_paths.go | 7 + 22 files changed, 982 insertions(+), 50 deletions(-) create mode 100644 changelog.d/added-automerge-pin-only-setting.md create mode 100644 src/pkg/adminmcp/tools_automerge_pin_only_test.go create mode 100644 src/pkg/dashboard/api_config_automerge_pin_only_test.go diff --git a/changelog.d/added-adminmcp-auto-merge-update.md b/changelog.d/added-adminmcp-auto-merge-update.md index 366167c909..cdd398a81f 100644 --- a/changelog.d/added-adminmcp-auto-merge-update.md +++ b/changelog.d/added-adminmcp-auto-merge-update.md @@ -1 +1 @@ -- **Admin MCP: change merge settings through preview and confirm.** The new `auto_merge.update` write operation wraps `PATCH /api/config/auto-merge`, so an owner can change `squash_only`, `require_current_base`, `human_merge_paths`, the native merge queue, trusted authors, the contributor lane and the other merge settings without opening the dashboard. Lists take `add`/`remove` and `human_merge_paths` takes one repository at a time; the preview reads the current settings and sends each changed list or map whole, so entries you did not name are kept, shows every change before and after, and says when a change lets the hive merge more on its own. `write_confirm` refuses if any of those settings changed after the preview. The operation never merges a pull request, and `human_merge_pin_only` (not on the endpoint) is still set in the configuration file. +- **Admin MCP: change merge settings through preview and confirm.** The new `auto_merge.update` write operation wraps `PATCH /api/config/auto-merge`, so an owner can change `squash_only`, `require_current_base`, `human_merge_paths`, the native merge queue, trusted authors, the contributor lane and the other merge settings without opening the dashboard. Lists take `add`/`remove` and `human_merge_paths` takes one repository at a time; the preview reads the current settings and sends each changed list or map whole, so entries you did not name are kept, shows every change before and after, and says when a change lets the hive merge more on its own. `write_confirm` refuses if any of those settings changed after the preview. The operation never merges a pull request. diff --git a/changelog.d/added-automerge-pin-only-setting.md b/changelog.d/added-automerge-pin-only-setting.md new file mode 100644 index 0000000000..da1fecdf30 --- /dev/null +++ b/changelog.d/added-automerge-pin-only-setting.md @@ -0,0 +1 @@ +- **The pin-only exception can be set from the dashboard and admin MCP.** `auto_merge.human_merge_pin_only`, which lets a pull request whose only change is a version or digest pin bump on a human-merge path merge without a hand merge, is now on `PUT`/`PATCH /api/config/auto-merge` (whole map, owner only), in **Settings → Features → Auto-merge** next to the human-merge paths, and in the admin MCP `auto_merge.update` operation one repository at a time. It is validated with the same rules `hive.yaml` loads under, refused for a repository with no `human_merge_paths`, saved like the other merge settings and applied without a restart, including to the merge-request relay. The MCP preview names what turning one on or widening it lets merge. What counts as a pin bump, and every other merge gate, is unchanged. diff --git a/src/docs/admin-mcp.md b/src/docs/admin-mcp.md index 430350fa25..33f91bb0e5 100644 --- a/src/docs/admin-mcp.md +++ b/src/docs/admin-mcp.md @@ -746,8 +746,12 @@ only. `{"squash_only": {"add": ["org/c"]}}` or `{"contributor_lane": {"repos": {"remove": ["org/a"]}}}`. A list takes `add` and `remove`. `human_merge_paths` takes `owner/repo` and every pattern that - repository should hold; `null` or `[]` removes the repository. An unknown - field is refused. + repository should hold; `null` or `[]` removes the repository. + `human_merge_pin_only` takes `owner/repo` and that repository's whole + pin-only exception, `{"enabled": true, "paths": [...], "kinds": [...], + "trusted_authors": [...]}`; `null` removes it. An enabled exception needs + `human_merge_paths` for the repository, set already or in the same change. + An unknown field is refused. - **Entries you do not name are kept.** The endpoint replaces each list and map it is sent, so the preview reads the current settings and sends the merged whole value. It shows every change before and after. @@ -757,9 +761,12 @@ only. - **Widening is disclosed.** The preview says when a change lets the hive merge more on its own: turning on the trusted-author lane, removing a human-merge path, adding a repository to the native merge queue, emptying a - repository allow-list (empty means every repository), and the like. -- It never merges a pull request. `human_merge_pin_only` is not on this - endpoint, so it is still set in the hive configuration file. + repository allow-list (empty means every repository), and the like. Turning + a pin-only exception on, or giving it more paths, kinds or trusted authors, + is widening too, and the preview names what merges as a result, for example + "pin bumps (action-sha) to .github/workflows/*.yml in org/a by renovate[bot] + will merge without a hand merge". Removing any of those is not. +- It never merges a pull request. The Activity monitor's row actions: diff --git a/src/docs/api-reference.md b/src/docs/api-reference.md index 143d53fc02..f0fd25dd47 100644 --- a/src/docs/api-reference.md +++ b/src/docs/api-reference.md @@ -216,7 +216,7 @@ History point limits, timestamp cutoffs, incremental cost reads and ETag/304 beh | `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` | -| `PUT` | `/api/config/auto-merge` | Owner only | Auto-Merge Config Set | `pkg/dashboard/api.go:269` | +| `PUT` | `/api/config/auto-merge` | Owner only | Auto-Merge Config Set; `human_merge_pin_only` replaces the whole pin-only map (`{}` clears it), and an invalid entry is a 400 with nothing changed | `pkg/dashboard/api.go:269` | | `GET` | `/api/config/convergence` | Owner only | Convergence Config Get | `pkg/dashboard/api.go:275` | | `PUT` | `/api/config/convergence` | Owner only | Convergence Config Set | `pkg/dashboard/api.go:277` | | `GET` | `/api/config/governor/advisory` | Owner only | Governor Advisory Get | `pkg/dashboard/api.go:281` | diff --git a/src/docs/api-reference/configuration.md b/src/docs/api-reference/configuration.md index 81c9ce8b64..8779ebda02 100644 --- a/src/docs/api-reference/configuration.md +++ b/src/docs/api-reference/configuration.md @@ -102,7 +102,7 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `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` | -| `PUT` | `/api/config/auto-merge` | Owner only | Auto-Merge Config Set | `pkg/dashboard/api.go:269` | +| `PUT` | `/api/config/auto-merge` | Owner only | Auto-Merge Config Set; `human_merge_pin_only` replaces the whole pin-only map (`{}` clears it), and an invalid entry is a 400 with nothing changed | `pkg/dashboard/api.go:269` | | `PATCH` | `/api/config/auto-merge` | Owner only | Partially update auto-merge settings, including nested `merge_train`; omitted fields stay unchanged; returns effective settings and bot-author metadata | `pkg/dashboard/api_config_automerge.go` | | `GET` | `/api/config/convergence` | Owner only | Convergence Config Get | `pkg/dashboard/api.go:275` | | `PUT` | `/api/config/convergence` | Owner only | Convergence Config Set | `pkg/dashboard/api.go:277` | diff --git a/src/docs/design/admin-mcp.md b/src/docs/design/admin-mcp.md index 65ba29cdb2..ff092da1fe 100644 --- a/src/docs/design/admin-mcp.md +++ b/src/docs/design/admin-mcp.md @@ -634,8 +634,9 @@ Phase 5 registers the fleet-level write operations under that contract: The preview names each change that lets the hive merge more on its own (a lane turned on, a human-merge path removed, a repository added to an allow-list or an allow-list emptied, which means every repository). Both the read and the write are owner only at the endpoint, and the - op merges nothing itself. `human_merge_pin_only` has no field on the endpoint, so the op - cannot reach it. + op merges nothing itself. `human_merge_pin_only` is set one repository at a time the same way + (the whole exception for that repository, or `null` to remove it); turning one on or giving + it more paths, kinds or trusted authors is named as widening. 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 diff --git a/src/docs/hive-merge.md b/src/docs/hive-merge.md index 3461fc4222..a893e9a4fd 100644 --- a/src/docs/hive-merge.md +++ b/src/docs/hive-merge.md @@ -246,9 +246,12 @@ schema or classifier APIs grants permission to merge or clears a hold. Native required checks and producer bindings, freshness, current reviews, substantive objections, unrelated holds and configured soak must remain independent gates. -Operators stage the key in the controller's configured `hive.yaml` seed, not in -the image repository (reload behaviour is documented in the operator reference -linked above). On an image that contains #16266 and #16265, reloading the seed +Owners set the key from **Settings → Features → Auto-merge → Pin bumps that +skip the hand merge**, through `human_merge_pin_only` on `PUT`/`PATCH +/api/config/auto-merge`, or with the admin MCP operation `auto_merge.update`; +it applies without a restart. It can also be staged in the controller's +configured `hive.yaml` seed, not in the image repository (reload behaviour is +documented in the operator reference linked above). On an image that contains #16266 and #16265, reloading the seed enables the sweep, `/approve`, and `hive-merge` relay exception at once. Non-GitHub forge relays retain the existing fail-closed human-merge-path policy. diff --git a/src/docs/operator-reference/README.md b/src/docs/operator-reference/README.md index fcd00228c0..b5b5247415 100644 --- a/src/docs/operator-reference/README.md +++ b/src/docs/operator-reference/README.md @@ -280,7 +280,7 @@ Go callers keep reading `cfg.Agents`, `cfg.Governor.Gateways` and so on through | `config.refuse_gate_regression` | `false` | Safety-gate regression guard ([#16438](https://github.com/hivecommons/hive/issues/16438)). At boot the hive compares the effective config against any previous runtime overlay still on the PVC (`/data/hive.yaml.runtime`, an operator's `hive.yaml.runtime.bak`, `/data/hive.yaml.dashboard`) for `review.require_labels`, `project.issue_filter.require_labels`, `project.paused_repos` and `writeback.per_repo` modes. A gate the overlay carried that the effective config lacks or loosens — typically a boot from the ConfigMap seed after the overlay was moved aside — is logged once per gate as `WARN safety gate dropped: (was ) — effective config has `, listed in `/api/status` under `config.gate_regressions`, and shown as a banner at the top of Settings. `true` makes it fatal: the hive exits (code 21) with the gates named instead of running with weaker gates. Set it in the overlay itself; the ConfigMap seed is the file the regression usually comes from. Legacy `/data/hive.yaml.bak` is not consulted — it is frozen at the rename and would warn forever about gates removed on purpose. | | `auto_merge.allow_unprotected_base` | Deprecated no-op. | Accepted so older configs keep loading. `hive-merge` now merges into any protected or unprotected branch the App can write, subject to the CI-evidence gate and GitHub's own merge rules. | | `auto_merge.no_ci_ok` | Empty by default. | Explicit repo list whose zero-CI merge-request verdict may pass; failing or pending CI evidence is still enforced. | -| `auto_merge.human_merge_pin_only` | Unset (off); enforced by the automerge sweep lanes and `/approve` (#16266), and by the `hive-merge` relay (#16265), which additionally requires the requested head SHA to match the PR head before and after fetching files. | Per-repo schema for `enabled`, `paths`, `kinds` (`action-sha`, `image-digest`, `version-pin`) and `trusted_authors`. Enabled entries require all three lists. The sweep does not place a human-merge-path hold on a PR whose author is in `trusted_authors`, whose complete diff (every changed file, guarded or not) is pin replacements, whose every commit is authored by a `trusted_authors` login with a GitHub-verified signature, and whose every new action SHA resolves in its upstream action repository (the `# vN` tag points at it, or it is on the default branch; #16399); it never clears an existing hold. See [hive-merge.md](../hive-merge.md) for grammar, restrictions and outstanding integration/deployment requirements (#16242). | +| `auto_merge.human_merge_pin_only` | Unset (off); enforced by the automerge sweep lanes and `/approve` (#16266), and by the `hive-merge` relay (#16265), which additionally requires the requested head SHA to match the PR head before and after fetching files. | Per-repo schema for `enabled`, `paths`, `kinds` (`action-sha`, `image-digest`, `version-pin`) and `trusted_authors`. Enabled entries require all three lists. The sweep does not place a human-merge-path hold on a PR whose author is in `trusted_authors`, whose complete diff (every changed file, guarded or not) is pin replacements, whose every commit is authored by a `trusted_authors` login with a GitHub-verified signature, and whose every new action SHA resolves in its upstream action repository (the `# vN` tag points at it, or it is on the default branch; #16399); it never clears an existing hold. Owners set it per repository from **Settings → Features → Auto-merge** or with the admin MCP operation `auto_merge.update`; an enabled entry is refused for a repository with no `human_merge_paths`. See [hive-merge.md](../hive-merge.md) for grammar, restrictions and outstanding integration/deployment requirements (#16242). | | `auto_merge.human_merge_paths` | Unset (off). | Per-repo map of `owner/repo` to glob patterns (same syntax as `intent.guardrail_path_patterns`) for paths a person must merge. Applies to every merge lane (App self-merge, trusted-author, label-queued, merge-request relay) whatever the intent tier; a matching PR is held with one comment, and an incomplete changed-file list fails closed. Details in the sweep key table below. | | `auto_merge.human_merge_title_prefixes` | `["⚠️", "⚠"]` | Title prefixes (after trimming) that mark a PR as a breaking change a person must merge. Every auto-merge lane and the merge train skip the PR; the tracker parks it at 090 *Ready for human merge · human merge*. Set to `[]` to disable. | | `auto_merge.human_merge_labels` | `["needs-owner-merge"]` | Labels (case-insensitive) that mark a PR a person must merge; same effect as the title prefixes. Set to `[]` to disable. | @@ -561,11 +561,11 @@ advanced into the merge path. | `auto_merge.contributor_lane.exclude_labels` | `hold`, `do-not-merge`, `needs-human`, `blocked`, `needs-rebase` | Labels that keep a PR out of contributor-lane auto-merge (`do-not-merge/*` always excluded). | Owners can edit `auto_merge.trusted_authors.*`, `auto_merge.contributor_lane.*`, -`auto_merge.require_current_base`, `auto_merge.squash_only` and -`auto_merge.human_merge_paths` from **Settings → Features → Auto-merge** (the -last three under **Per-repository merge policy**, picking from `project.repos` -and saving each value as `owner/repo`; a repo outside `project.repos` is -refused). The dashboard writes the same +`auto_merge.require_current_base`, `auto_merge.squash_only`, +`auto_merge.human_merge_paths` and `auto_merge.human_merge_pin_only` from +**Settings → Features → Auto-merge** (the last four under **Per-repository +merge policy**, picking from `project.repos` and saving each value as +`owner/repo`; a repo outside `project.repos` is refused). The dashboard writes the same owner-only `/api/config/auto-merge` overlay as the other auto-merge controls, so hosted spoke changes survive restarts without editing `hive.yaml`. @@ -603,14 +603,25 @@ auto_merge: | `kinds` | Explicit subset of `action-sha`, `image-digest`, `version-pin`; unknown kinds rejected. Required when enabled. An `action-sha` pin is admitted only when the upstream repo's `tags/` (annotated tags dereferenced) points at the new SHA, or, without a comment, the SHA is an ancestor of the upstream default branch; any lookup failure holds. | | `trusted_authors` | Explicit author allowlist; required when enabled. Matched against the PR author login and against the author login of every commit behind the head; each commit must also be committed by GitHub (`web-flow`) or by a trusted login and carry a GitHub-verified signature, since GitHub verifies the committer, not the author (web-flow-committed bot commits qualify; human authors must commit and sign as themselves). Not permission to trust arbitrary bot-looking logins. | -Edit the controller's active `hive.yaml` seed, not the consumer image repo. -The config file watcher loads the seed plus dashboard overlay after a debounced -file change and logs `config reloaded from file`; a rejected reload logs -`config reload failed` and does not install the change. See -[config layering](../config-layering.md) for seed/overlay precedence. Do not -assume the dashboard auto-merge editor exposes this new map. Verify both relay -and sweep lookups use the reloaded configuration before relying on it; use a -controller restart on the verified image if the running version lacks live wiring. +**Setting it.** On a build that has the editor, owners set the exception from +**Settings → Features → Auto-merge → Pin bumps that skip the hand merge**, one +row per repository that has paths a person must merge: on/off, the paths, the +kinds and the trusted authors. The same value goes through `PUT`/`PATCH +/api/config/auto-merge` as `human_merge_pin_only` (the whole map, like +`human_merge_paths`; `{}` clears it) or through the admin MCP operation +`auto_merge.update`, which changes one repository and keeps the others. The +endpoint checks it with the same rules `hive.yaml` loads under and refuses an +enabled entry it adds or changes for a repository with no `human_merge_paths`, +where the exception would never apply. It saves to the dashboard overlay and +applies at once, with no restart: the sweep lanes and `/approve` read it on +every evaluation, and the write refreshes the merge-request relay's copy. A +change that cannot be saved is rolled back. + +On an older build, edit the controller's active `hive.yaml` seed, not the +consumer image repo. The config file watcher loads the seed plus dashboard +overlay after a debounced file change and logs `config reloaded from file`; a +rejected reload logs `config reload failed` and does not install the change. +See [config layering](../config-layering.md) for seed/overlay precedence. Qualification requires a complete exact-head diff and trusted author, not just SHA-shaped text. The exception never bypasses native required checks or producer diff --git a/src/docs/settings.md b/src/docs/settings.md index b34ccdf291..359d2a79db 100644 --- a/src/docs/settings.md +++ b/src/docs/settings.md @@ -88,7 +88,7 @@ Optional capabilities, each off or inert until you turn it on. Where a feature h - Audit publication: [Audit campaign](audit-campaign.md#publication). - Token mint: [Token mint](token-mint.md). - Spek stage runner: [Spektacular](spektacular.md). -- Auto-merge: [App self-merge sweep](operator-reference.md#app-self-merge-sweep-auto_merge), [Trusted bot authors](hive-merge.md#trusted-bot-authors), [Trusted-author auto-merge](hive-merge.md#trusted-author-auto-merge), and the per-repository merge policy (`auto_merge.require_current_base`, `auto_merge.squash_only`, `auto_merge.human_merge_paths`). +- Auto-merge: [App self-merge sweep](operator-reference.md#app-self-merge-sweep-auto_merge), [Trusted bot authors](hive-merge.md#trusted-bot-authors), [Trusted-author auto-merge](hive-merge.md#trusted-author-auto-merge), and the per-repository merge policy (`auto_merge.require_current_base`, `auto_merge.squash_only`, `auto_merge.human_merge_paths`, `auto_merge.human_merge_pin_only`). - Review gate: [Review swarm](review-swarm.md#configuration), [Blocking line and backlog](review-swarm.md#blocking-line-reviewseverity-reviewbacklog), and [external review bot threads](review-bot-threads.md). - Trajectory review: [Trajectory-Review Lane](trajectory-review.md#configuration). - Linear agent: [Linear agent integration](linear-agent.md). diff --git a/src/pkg/adminmcp/tools_automerge_ops.go b/src/pkg/adminmcp/tools_automerge_ops.go index f23287ffca..1756d72bb9 100644 --- a/src/pkg/adminmcp/tools_automerge_ops.go +++ b/src/pkg/adminmcp/tools_automerge_ops.go @@ -8,6 +8,7 @@ import ( "fmt" "net/http" "path/filepath" + "slices" "strings" "time" @@ -19,8 +20,9 @@ import ( // (handleAutoMergePut). That endpoint replaces every list and map it is sent // whole: squash_only ["a/b"] drops every other repository. So this op takes // changes instead (entries to add and remove, one repository's human-merge -// paths to set or unset), reads the current settings while previewing, and -// sends each changed list or map as its whole merged value. The preview shows +// paths or pin-only exception to set or unset), reads the current settings +// while previewing, and sends each changed list or map as its whole merged +// value. The preview shows // every changed setting before and after. ConfirmGuard reads the settings // again at write_confirm and refuses when any of those before-values moved, so // a merge built from a stale read never overwrites someone else's change. @@ -51,6 +53,7 @@ const ( amEnum amList amRepoPaths + amPinOnly ) // amEntry is how a list's entries are compared. @@ -81,6 +84,7 @@ const ( amWidenRole // trusted_authors.require_role from owner to merger amWidenScope // contributor_lane.auto_promotion_scope from repo to hive amWidenPaths // human_merge_paths loses a pattern + amWidenPinOnly // human_merge_pin_only admits more repositories, paths, kinds or authors ) type amField struct { @@ -107,6 +111,7 @@ var autoMergeFields = []amField{ {key: "squash_only", kind: amList, entry: amEntryRepo, widen: amWidenRemove, why: "a mixed-author pull request there merges with a merge commit instead of going back to a person"}, {key: "require_current_base", kind: amList, entry: amEntryRepo, widen: amWidenRemove, why: "pull requests there may merge without the current base tip"}, {key: "human_merge_paths", kind: amRepoPaths, widen: amWidenPaths, why: "pull requests touching these paths no longer wait for a person to merge them"}, + {key: "human_merge_pin_only", kind: amPinOnly, widen: amWidenPinOnly}, {key: "bot_takeover_enabled", kind: amBool, widen: amWidenOn, why: "the App re-authors trusted github-actions[bot] pull requests and merges its copy"}, {key: "require_current_base_default", kind: amBool, widen: amWidenOff, why: "repositories without an override may merge without the current base tip"}, {key: "merge_train.enabled", kind: amBool}, @@ -135,7 +140,7 @@ var autoMergeFields = []amField{ func (autoMergeUpdateOp) Name() string { return WriteOpAutoMergeUpdate } func (autoMergeUpdateOp) Description() string { - return "Change merge settings (auto_merge) through PATCH /api/config/auto-merge, the endpoint the dashboard's merge controls use. Owner only. Pass only what changes, shaped like the endpoint's body. A list takes {\"add\": [...], \"remove\": [...]}; human_merge_paths takes {\"owner/repo\": [every pattern for that repository]}, with null or [] removing that repository. The preview reads the current settings and sends each changed list or map whole, keeping every entry you did not name, shows each change before and after, and says which changes let the hive merge more on its own. write_confirm refuses if any of those settings changed after the preview. This operation never merges a pull request. human_merge_pin_only is not on this endpoint." + return "Change merge settings (auto_merge) through PATCH /api/config/auto-merge, the endpoint the dashboard's merge controls use. Owner only. Pass only what changes, shaped like the endpoint's body. A list takes {\"add\": [...], \"remove\": [...]}; human_merge_paths takes {\"owner/repo\": [every pattern for that repository]}, with null or [] removing that repository. human_merge_pin_only takes {\"owner/repo\": {\"enabled\": true, \"paths\": [...], \"kinds\": [...], \"trusted_authors\": [...]}}, the whole exception for that repository, with null removing it; the repository needs human_merge_paths. The preview reads the current settings and sends each changed list or map whole, keeping every entry you did not name, shows each change before and after, and says which changes let the hive merge more on its own. write_confirm refuses if any of those settings changed after the preview. This operation never merges a pull request." } func (autoMergeUpdateOp) InputSchema() map[string]any { @@ -172,6 +177,19 @@ func (f *amField) schema() map[string]any { return map[string]any{"type": "string", "enum": f.enum} case amRepoPaths: return map[string]any{"type": "object", "description": "owner/repo to every glob pattern that repository should hold; null or [] removes the repository. Repositories you do not name are kept.", "additionalProperties": map[string]any{"anyOf": []any{list, map[string]any{"type": "null"}}}} + case amPinOnly: + entry := map[string]any{ + "type": "object", + "properties": map[string]any{ + "enabled": map[string]any{"type": "boolean"}, + "paths": map[string]any{"type": "array", "items": stringSchema(), "description": "Glob patterns, within the repository's human_merge_paths, a pin bump may touch."}, + "kinds": map[string]any{"type": "array", "items": map[string]any{"type": "string", "enum": config.PinOnlyKinds}}, + "trusted_authors": map[string]any{"type": "array", "items": stringSchema(), "description": "Logins that must author the pull request and every commit behind its head."}, + }, + "required": []string{"enabled"}, + "additionalProperties": false, + } + return map[string]any{"type": "object", "description": "owner/repo to that repository's whole pin-only exception; null removes it. Repositories you do not name are kept. An enabled exception lets a pull request whose only change is a pin bump on a human-merge path merge without a hand merge.", "additionalProperties": map[string]any{"anyOf": []any{entry, map[string]any{"type": "null"}}}} default: return map[string]any{"type": "object", "description": "Entries to add and to remove. Entries you do not name are kept.", "properties": map[string]any{"add": list, "remove": list}, "additionalProperties": false} } @@ -278,9 +296,31 @@ type amRow struct { before, after any } -// rows splits a human_merge_paths change into one row per repository that -// changes, so a preview names repositories as values rather than as keys. +// rows splits a human_merge_paths or human_merge_pin_only change into one row +// per repository that changes, so a preview names repositories as values +// rather than as keys. func (c amPlanned) rows() []amRow { + if c.field.kind == amPinOnly { + before := pinOnlyValue(c.before) + after, _ := c.after.(map[string]amPin) + var rows []amRow + for _, repo := range unionPinOnlyKeys(before, after) { + b, hadB := before[repo] + a, hasA := after[repo] + if hadB == hasA && compactJSON(b) == compactJSON(a) { + continue + } + row := amRow{field: c.field.key + "[" + repo + "]"} + if hadB { + row.before = b + } + if hasA { + row.after = a + } + rows = append(rows, row) + } + return rows + } if c.field.kind != amRepoPaths { return []amRow{{field: c.field.key, before: c.before, after: c.after}} } @@ -341,9 +381,6 @@ func parseAutoMergeArgs(args map[string]any) ([]amArg, error) { } func unknownAutoMergeField(key string) error { - if key == "human_merge_pin_only" { - return fmt.Errorf("human_merge_pin_only is not on PATCH %s, so this operation cannot change it; it is set in the hive configuration file", autoMergeSettingsPath) - } return fmt.Errorf("unsupported merge setting %q", key) } @@ -380,6 +417,9 @@ func planAutoMergeUpdate(ctx context.Context, args map[string]any, provider Prov if len(plan.changes) == 0 { return amPlan{}, fmt.Errorf("nothing would change: %s already as requested", strings.Join(plan.unchanged, ", ")) } + if err := checkPinOnlyGuarded(plan, current); err != nil { + return amPlan{}, err + } plan.fingerprint = settingsFingerprint(beforeValues) return plan, nil } @@ -477,6 +517,8 @@ func (f *amField) apply(before, raw any, projectRepos []string) (any, error) { return nil, fmt.Errorf("%s must be one of %s", f.key, strings.Join(f.enum, ", ")) case amRepoPaths: return applyRepoPaths(before, raw, projectRepos) + case amPinOnly: + return applyPinOnly(before, raw, projectRepos) default: return f.applyList(before, raw, projectRepos) } @@ -643,6 +685,223 @@ func applyRepoPaths(before, raw any, projectRepos []string) (map[string][]string return out, nil } +// amPin is one repository's auto_merge.human_merge_pin_only entry as the +// endpoint reports and takes it. The fields are in the order encoding/json +// sorts map keys, so a value read back from the hive and one built here +// encode the same. +type amPin struct { + Enabled bool `json:"enabled"` + Kinds []string `json:"kinds"` + Paths []string `json:"paths"` + TrustedAuthors []string `json:"trusted_authors"` +} + +// pinOnlyValue reads human_merge_pin_only as the hive reported it. +func pinOnlyValue(v any) map[string]amPin { + out := map[string]amPin{} + switch m := v.(type) { + case map[string]any: + for repo, raw := range m { + e, _ := raw.(map[string]any) + enabled, _ := e["enabled"].(bool) + out[repo] = amPin{ + Enabled: enabled, + Kinds: nilAsEmpty(stringListValueLoose(e["kinds"])), + Paths: nilAsEmpty(stringListValueLoose(e["paths"])), + TrustedAuthors: nilAsEmpty(stringListValueLoose(e["trusted_authors"])), + } + } + case map[string]amPin: + for repo, e := range m { + out[repo] = e + } + } + return out +} + +func unionPinOnlyKeys(a, b map[string]amPin) []string { + keys := map[string]any{} + for k := range a { + keys[k] = nil + } + for k := range b { + keys[k] = nil + } + return SortKeys(keys) +} + +// applyPinOnly sets or unsets the named repositories' whole pin-only +// exception and keeps every other repository's entry. The merged map must +// pass the same validation hive.yaml loads under. +func applyPinOnly(before, raw any, projectRepos []string) (map[string]amPin, error) { + const shape = `human_merge_pin_only takes {"owner/repo": {"enabled": true, "paths": [...], "kinds": [...], "trusted_authors": [...]}}; null removes that repository` + change, ok := raw.(map[string]any) + if !ok || len(change) == 0 { + return nil, fmt.Errorf("%s", shape) + } + out := pinOnlyValue(before) + touched := map[string]bool{} + for _, key := range SortKeys(change) { + repo := qualifyProjectRepo(strings.TrimSpace(key), projectRepos) + owner, name, ok := strings.Cut(repo, "/") + if !ok || owner == "" || name == "" || strings.Contains(name, "/") || strings.ContainsAny(repo, " \t") { + return nil, fmt.Errorf("human_merge_pin_only: %q is not an owner/repo name", key) + } + if touched[strings.ToLower(repo)] { + return nil, fmt.Errorf("human_merge_pin_only names %s twice", repo) + } + touched[strings.ToLower(repo)] = true + existing := "" + for k := range out { + if strings.EqualFold(k, repo) { + existing = k + } + } + if change[key] == nil { + if existing == "" { + return nil, fmt.Errorf("human_merge_pin_only has no entry for %s to remove", repo) + } + delete(out, existing) + continue + } + entry, err := pinOnlyEntryArg(repo, change[key]) + if err != nil { + return nil, err + } + if existing != "" { + repo = existing + } + out[repo] = entry + } + check := config.AutoMergeConfig{HumanMergePinOnly: map[string]config.PinOnlyException{}} + for repo, e := range out { + check.HumanMergePinOnly[repo] = config.PinOnlyException{Enabled: e.Enabled, Paths: e.Paths, Kinds: e.Kinds, TrustedAuthors: e.TrustedAuthors} + } + if err := check.ValidateHumanMergePinOnly(); err != nil { + return nil, err + } + return out, nil +} + +// pinOnlyEntryArg reads one repository's exception from the arguments. +func pinOnlyEntryArg(repo string, raw any) (amPin, error) { + obj, ok := raw.(map[string]any) + if !ok { + return amPin{}, fmt.Errorf("human_merge_pin_only[%s] must be an object with enabled, paths, kinds and trusted_authors, or null", repo) + } + for k := range obj { + switch k { + case "enabled", "paths", "kinds", "trusted_authors": + default: + return amPin{}, fmt.Errorf("human_merge_pin_only[%s] takes enabled, paths, kinds and trusted_authors, not %q", repo, k) + } + } + enabled, ok := obj["enabled"].(bool) + if !ok { + return amPin{}, fmt.Errorf("human_merge_pin_only[%s].enabled must be true or false", repo) + } + entry := amPin{Enabled: enabled} + for _, f := range []struct { + name string + dst *[]string + }{{"kinds", &entry.Kinds}, {"paths", &entry.Paths}, {"trusted_authors", &entry.TrustedAuthors}} { + list, err := stringListValue(obj[f.name]) + if err != nil { + return amPin{}, fmt.Errorf("human_merge_pin_only[%s].%s must be a list of strings", repo, f.name) + } + vals := []string{} + for _, v := range list { + v = strings.TrimSpace(v) + if v == "" { + return amPin{}, fmt.Errorf("human_merge_pin_only[%s].%s entries must be non-empty", repo, f.name) + } + if !slices.Contains(vals, v) { + vals = append(vals, v) + } + } + *f.dst = vals + } + return entry, nil +} + +// checkPinOnlyGuarded refuses an enabled pin-only exception the change adds +// or alters for a repository that has no human_merge_paths after the change, +// as the endpoint does: the exception only lifts a human-merge-path hold, so +// there it would never apply. +func checkPinOnlyGuarded(plan amPlan, current map[string]any) error { + var pin *amPlanned + for i := range plan.changes { + if plan.changes[i].field.kind == amPinOnly { + pin = &plan.changes[i] + } + } + if pin == nil { + return nil + } + paths := repoPathsValue(current["human_merge_paths"]) + if sent, ok := plan.body["human_merge_paths"]; ok { + paths = repoPathsValue(sent) + } + before := pinOnlyValue(pin.before) + after, _ := pin.after.(map[string]amPin) + for _, repo := range unionPinOnlyKeys(after, nil) { + e := after[repo] + if b, had := before[repo]; !e.Enabled || (had && compactJSON(b) == compactJSON(e)) { + continue + } + guarded := false + for k, patterns := range paths { + if strings.EqualFold(k, repo) && len(patterns) > 0 { + guarded = true + } + } + if !guarded { + return fmt.Errorf("human_merge_pin_only[%s]: %s has no human_merge_paths, so a pin-only exception there would never apply; set its human-merge paths first (or in the same change)", repo, repo) + } + } + return nil +} + +// pinOnlyWidening names what a human_merge_pin_only change lets merge without +// a hand merge: a repository whose exception turns on, or an enabled one that +// gains paths, kinds or trusted authors. Removing any of those narrows it. +func pinOnlyWidening(before, after any) []string { + was := pinOnlyValue(before) + now := pinOnlyValue(after) + var notes []string + for _, repo := range unionPinOnlyKeys(now, nil) { + e := now[repo] + if !e.Enabled { + continue + } + b, had := was[repo] + bump := "pin bumps (" + strings.Join(e.Kinds, ", ") + ") to " + strings.Join(e.Paths, ", ") + " in " + repo + " by " + strings.Join(e.TrustedAuthors, ", ") + if !had || !b.Enabled { + notes = append(notes, "human_merge_pin_only["+repo+"] turned on: "+bump+" will merge without a hand merge") + continue + } + var gained []string + for _, f := range []struct { + name string + was, now []string + }{{"paths", b.Paths, e.Paths}, {"kinds", b.Kinds, e.Kinds}, {"trusted_authors", b.TrustedAuthors, e.TrustedAuthors}} { + var added []string + for _, v := range f.now { + if !slices.Contains(f.was, v) { + added = append(added, v) + } + } + if len(added) > 0 { + gained = append(gained, f.name+" "+strings.Join(added, ", ")) + } + } + if len(gained) > 0 { + notes = append(notes, "human_merge_pin_only["+repo+"] adds "+strings.Join(gained, "; ")+": "+bump+" will merge without a hand merge") + } + } + return notes +} + // widening names what a change lets the hive merge on its own, if anything. func (f *amField) widening(before, after any, projectRepos []string) []string { note := func(what string) []string { return []string{f.key + " " + what + ": " + f.why} } @@ -696,6 +955,8 @@ func (f *amField) widening(before, after any, projectRepos []string) []string { if before == config.ContributorLaneAutoPromotionScopeRepo && after == config.ContributorLaneAutoPromotionScopeHive { return note("repo → hive") } + case amWidenPinOnly: + return pinOnlyWidening(before, after) case amWidenPaths: was := repoPathsValue(before) now, _ := after.(map[string][]string) diff --git a/src/pkg/adminmcp/tools_automerge_ops_test.go b/src/pkg/adminmcp/tools_automerge_ops_test.go index a2e03c056d..1383a5d182 100644 --- a/src/pkg/adminmcp/tools_automerge_ops_test.go +++ b/src/pkg/adminmcp/tools_automerge_ops_test.go @@ -92,8 +92,7 @@ func TestAutoMergeUpdateRegistered(t *testing.T) { } // An argument the endpoint does not take is refused before anything is read, -// at the top level and inside a nested object; human_merge_pin_only, which -// the endpoint has no field for, says so. +// at the top level and inside a nested object. func TestAutoMergeUpdateRejectsUnknownFields(t *testing.T) { for name, tc := range map[string]struct { args map[string]any @@ -102,7 +101,6 @@ func TestAutoMergeUpdateRejectsUnknownFields(t *testing.T) { "top-level typo": {map[string]any{"squash_repos": map[string]any{"add": []any{"org/c"}}}, `unsupported merge setting "squash_repos"`}, "nested unknown": {map[string]any{"contributor_lane": map[string]any{"enabled": true, "workflow_fence_scope": "all"}}, `unsupported merge setting "contributor_lane.workflow_fence_scope"`}, "dotted top-level": {map[string]any{"merge_train.enabled": false}, `unsupported merge setting "merge_train.enabled"`}, - "pin-only": {map[string]any{"human_merge_pin_only": map[string]any{"org/a": map[string]any{"enabled": true}}}, "human_merge_pin_only is not on PATCH /api/config/auto-merge"}, "list without add": {map[string]any{"squash_only": map[string]any{"set": []any{"org/c"}}}, "takes only add and remove"}, "list given as array": {map[string]any{"squash_only": []any{"org/c"}}, `takes {"add"`}, } { diff --git a/src/pkg/adminmcp/tools_automerge_pin_only_test.go b/src/pkg/adminmcp/tools_automerge_pin_only_test.go new file mode 100644 index 0000000000..80fe4dd8eb --- /dev/null +++ b/src/pkg/adminmcp/tools_automerge_pin_only_test.go @@ -0,0 +1,156 @@ +package adminmcp + +import ( + "context" + "errors" + "strings" + "testing" +) + +// auto_merge.update and auto_merge.human_merge_pin_only: the pin-only +// exception to human_merge_paths (#16377), set one repository at a time. + +// pinOnlyFixture is autoMergeFixture on a hive that reports +// human_merge_pin_only, with an exception already set for org/a. +func pinOnlyFixture() map[string]any { + f := autoMergeFixture() + f["human_merge_pin_only"] = map[string]any{ + "org/a": map[string]any{"enabled": true, "paths": []string{".github/workflows/*.yml", "Containerfile"}, "kinds": []string{"action-sha", "image-digest"}, "trusted_authors": []string{"renovate[bot]"}}, + } + return f +} + +func pinOnlyArg(paths, kinds, authors []any) map[string]any { + return map[string]any{"enabled": true, "paths": paths, "kinds": kinds, "trusted_authors": authors} +} + +// Setting one repository's exception sends the whole map back with every +// other repository's entry unchanged, and says what will now merge on its own. +func TestAutoMergeUpdatePinOnlySetKeepsOtherRepos(t *testing.T) { + p := &autoMergeProvider{settings: pinOnlyFixture()} + h := autoMergeHandler(p) + preview, id := autoMergePreview(t, h, map[string]any{ + "human_merge_pin_only": map[string]any{"b": pinOnlyArg([]any{"CODEOWNERS", " CODEOWNERS "}, []any{"version-pin"}, []any{"dependabot[bot]"})}, + }) + want := `{"human_merge_pin_only":{` + + `"org/a":{"enabled":true,"kinds":["action-sha","image-digest"],"paths":[".github/workflows/*.yml","Containerfile"],"trusted_authors":["renovate[bot]"]},` + + `"org/b":{"enabled":true,"kinds":["version-pin"],"paths":["CODEOWNERS"],"trusted_authors":["dependabot[bot]"]}}}` + if got := compactJSON(preview.Request.Body); got != want { + t.Fatalf("body = %s\nwant %s", got, want) + } + changes, _ := preview.Details["changes"].([]map[string]any) + if len(changes) != 1 || changes[0]["field"] != "human_merge_pin_only[org/b]" || changes[0]["before"] != nil { + t.Fatalf("changes = %+v, want one row for org/b from nothing", changes) + } + for _, s := range []string{"Widening:", "pin bumps", "CODEOWNERS", "in org/b", "dependabot[bot]", "will merge without a hand merge"} { + if !strings.Contains(preview.WideningDisclosure, s) { + t.Fatalf("disclosure missing %q: %s", s, preview.WideningDisclosure) + } + } + if strings.Contains(preview.WideningDisclosure, "org/a") { + t.Fatalf("the untouched org/a entry is disclosed as a change: %s", preview.WideningDisclosure) + } + if _, err := h.ConfirmWrite(context.Background(), map[string]any{"confirmation_id": id}); err != nil { + t.Fatalf("confirm: %v", err) + } + if len(p.requests) != 1 || compactJSON(p.requests[0].Body) != want { + t.Fatalf("executed %+v, want body %s", p.requests, want) + } +} + +// Turning an exception on or giving it more paths, kinds or authors lets more +// pull requests past a human-merge hold. Taking any of those away does not. +func TestAutoMergeUpdatePinOnlyWidening(t *testing.T) { + a := func(paths, kinds, authors []any) map[string]any { + return map[string]any{"human_merge_pin_only": map[string]any{"org/a": pinOnlyArg(paths, kinds, authors)}} + } + paths, kinds, ra := []any{".github/workflows/*.yml", "Containerfile"}, []any{"action-sha", "image-digest"}, []any{"renovate[bot]"} + for name, tc := range map[string]struct { + args map[string]any + widen bool + names string + }{ + "new repository": {map[string]any{"human_merge_pin_only": map[string]any{"org/b": pinOnlyArg([]any{"CODEOWNERS"}, []any{"action-sha"}, ra)}}, true, "human_merge_pin_only[org/b] turned on"}, + "adds a path": {a(append([]any{".claude/hooks/*.sh"}, paths...), kinds, ra), true, "paths .claude/hooks/*.sh"}, + "adds a kind": {a(paths, []any{"action-sha", "image-digest", "version-pin"}, ra), true, "kinds version-pin"}, + "adds an author": {a(paths, kinds, []any{"renovate[bot]", "someone"}), true, "trusted_authors someone"}, + "swaps a path": {a([]any{"Dockerfile", "Containerfile"}, kinds, ra), true, "paths Dockerfile"}, + "removes a path": {a([]any{"Containerfile"}, kinds, ra), false, ""}, + "removes a kind": {a(paths, []any{"image-digest"}, ra), false, ""}, + "disabled": {map[string]any{"human_merge_pin_only": map[string]any{"org/a": map[string]any{"enabled": false, "paths": paths, "kinds": kinds, "trusted_authors": ra}}}, false, ""}, + "unset with null": {map[string]any{"human_merge_pin_only": map[string]any{"org/a": nil}}, false, ""}, + } { + t.Run(name, func(t *testing.T) { + preview, _ := autoMergePreview(t, autoMergeHandler(&autoMergeProvider{settings: pinOnlyFixture()}), tc.args) + if got := strings.HasPrefix(preview.WideningDisclosure, "Widening:"); got != tc.widen { + t.Fatalf("widening = %v, want %v: %s", got, tc.widen, preview.WideningDisclosure) + } + if tc.widen && !strings.Contains(preview.WideningDisclosure, tc.names) { + t.Fatalf("disclosure does not name %q: %s", tc.names, preview.WideningDisclosure) + } + if tc.widen && !strings.Contains(preview.WideningDisclosure, "will merge without a hand merge") { + t.Fatalf("disclosure does not say what now merges on its own: %s", preview.WideningDisclosure) + } + }) + } +} + +// The change is merged into the exceptions the preview read. If those change +// before write_confirm, sending the merged map would undo that change, so the +// confirm is refused and nothing is written. +func TestAutoMergeUpdatePinOnlyRefusesStalePreview(t *testing.T) { + p := &autoMergeProvider{settings: pinOnlyFixture()} + h := autoMergeHandler(p) + _, id := autoMergePreview(t, h, map[string]any{ + "human_merge_pin_only": map[string]any{"org/b": pinOnlyArg([]any{"CODEOWNERS"}, []any{"version-pin"}, []any{"dependabot[bot]"})}, + }) + p.settings["human_merge_pin_only"] = map[string]any{} // someone removed org/a's exception meanwhile + if _, err := h.ConfirmWrite(context.Background(), map[string]any{"confirmation_id": id}); !errors.Is(err, ErrConfirmationStale) { + t.Fatalf("confirm err = %v, want ErrConfirmationStale", err) + } + if len(p.requests) != 0 { + t.Fatalf("a stale confirmation wrote: %+v", p.requests) + } +} + +// What the endpoint would refuse is refused at preview, with no confirmation. +func TestAutoMergeUpdatePinOnlyRefusals(t *testing.T) { + for name, tc := range map[string]struct { + settings map[string]any + args map[string]any + want string + }{ + "repository without human-merge paths": {pinOnlyFixture(), map[string]any{"human_merge_pin_only": map[string]any{"org/c": pinOnlyArg([]any{"Containerfile"}, []any{"image-digest"}, []any{"renovate[bot]"})}}, "org/c has no human_merge_paths"}, + "enabled without trusted authors": {pinOnlyFixture(), map[string]any{"human_merge_pin_only": map[string]any{"org/b": pinOnlyArg([]any{"CODEOWNERS"}, []any{"version-pin"}, nil)}}, "enabled policy requires nonempty trusted_authors"}, + "unknown kind": {pinOnlyFixture(), map[string]any{"human_merge_pin_only": map[string]any{"org/b": pinOnlyArg([]any{"CODEOWNERS"}, []any{"any-line"}, []any{"renovate[bot]"})}}, `unknown kind "any-line"`}, + "unknown entry field": {pinOnlyFixture(), map[string]any{"human_merge_pin_only": map[string]any{"org/b": map[string]any{"enabled": true, "authors": []any{"x"}}}}, `not "authors"`}, + "enabled not given": {pinOnlyFixture(), map[string]any{"human_merge_pin_only": map[string]any{"org/b": map[string]any{"paths": []any{"CODEOWNERS"}}}}, "enabled must be true or false"}, + "remove what is not there": {pinOnlyFixture(), map[string]any{"human_merge_pin_only": map[string]any{"org/b": nil}}, "no entry for org/b to remove"}, + "same entry, other casing": {pinOnlyFixture(), map[string]any{"human_merge_pin_only": map[string]any{"ORG/A": pinOnlyArg([]any{".github/workflows/*.yml", "Containerfile"}, []any{"action-sha", "image-digest"}, []any{"renovate[bot]"})}}, "nothing would change"}, + // A hive whose endpoint has no human_merge_pin_only field would drop + // it silently, so it is refused rather than sent. + "hive that does not report it": {autoMergeFixture(), map[string]any{"human_merge_pin_only": map[string]any{"org/b": pinOnlyArg([]any{"CODEOWNERS"}, []any{"version-pin"}, []any{"dependabot[bot]"})}}, "may run an older build"}, + } { + t.Run(name, func(t *testing.T) { + p := &autoMergeProvider{settings: tc.settings} + h := autoMergeHandler(p) + _, err := h.PreviewWrite(context.Background(), map[string]any{"operation": WriteOpAutoMergeUpdate, "args": tc.args}) + if err == nil || !strings.Contains(err.Error(), tc.want) { + t.Fatalf("err = %v, want it to contain %q", err, tc.want) + } + if pending, _ := h.PendingStore.List(context.Background()); len(pending) != 0 { + t.Fatalf("a refused preview minted a confirmation: %+v", pending) + } + }) + } + + // Setting the human-merge paths in the same change makes it meaningful. + p := &autoMergeProvider{settings: pinOnlyFixture()} + preview, _ := autoMergePreview(t, autoMergeHandler(p), map[string]any{ + "human_merge_paths": map[string]any{"org/c": []any{"Containerfile"}}, + "human_merge_pin_only": map[string]any{"org/c": pinOnlyArg([]any{"Containerfile"}, []any{"image-digest"}, []any{"renovate[bot]"})}, + }) + if !strings.Contains(preview.WideningDisclosure, "human_merge_pin_only[org/c] turned on") { + t.Fatalf("disclosure = %s", preview.WideningDisclosure) + } +} diff --git a/src/pkg/adminmcp/tools_settings.go b/src/pkg/adminmcp/tools_settings.go index 91e6524b14..67200bc2d5 100644 --- a/src/pkg/adminmcp/tools_settings.go +++ b/src/pkg/adminmcp/tools_settings.go @@ -36,7 +36,7 @@ var settingsSections = []SettingsSection{ {"dashboard", "/api/config/dashboard", "Dashboard settings."}, {"channels", "/api/config/channels", "Channels: email, push, Slack, Matrix, Microsoft Teams and Telegram targets, GitHub mentions and Actions identity (secret values are never returned; secrets are named by environment variable)."}, {"escalation", "/api/config/escalation", "Escalation settings."}, - {"auto_merge", "/api/config/auto-merge", "Merge settings, including the per-repository merge policy (squash_only, require_current_base, human_merge_paths)."}, + {"auto_merge", "/api/config/auto-merge", "Merge settings, including the per-repository merge policy (squash_only, require_current_base, human_merge_paths, human_merge_pin_only)."}, {"review", "/api/config/review", "Review settings: reviewers, perspectives, review bots and gates."}, {"convergence", "/api/config/convergence", "Convergence settings."}, {"sla", "/api/config/sla", "SLA settings."}, diff --git a/src/pkg/config/automerge_pin_only.go b/src/pkg/config/automerge_pin_only.go index 11cd07ce39..c6cfa8eda4 100644 --- a/src/pkg/config/automerge_pin_only.go +++ b/src/pkg/config/automerge_pin_only.go @@ -2,6 +2,7 @@ package config import ( "fmt" + "slices" "strings" "github.com/hivecommons/hive/pkg/intent" @@ -22,11 +23,13 @@ type PinOnlyException struct { TrustedAuthors []string `yaml:"trusted_authors" json:"trusted_authors"` } +// PinOnlyKinds is every kind a PinOnlyException may name. The settings +// editors offer exactly these; validate refuses anything else. +var PinOnlyKinds = []string{"action-sha", "image-digest", "version-pin"} + func (p PinOnlyException) validate() error { for _, kind := range p.Kinds { - switch kind { - case "action-sha", "image-digest", "version-pin": - default: + if !slices.Contains(PinOnlyKinds, kind) { return fmt.Errorf("unknown kind %q", kind) } } diff --git a/src/pkg/dashboard/api_config_automerge.go b/src/pkg/dashboard/api_config_automerge.go index 0108bef0e9..3e06204b5c 100644 --- a/src/pkg/dashboard/api_config_automerge.go +++ b/src/pkg/dashboard/api_config_automerge.go @@ -166,6 +166,10 @@ func (s *Server) handleAutoMergePut(w http.ResponseWriter, r *http.Request) { SquashOnly []string `json:"squash_only"` RequireCurrentBase []string `json:"require_current_base"` HumanMergePaths map[string][]string `json:"human_merge_paths"` + // HumanMergePinOnly is the FULL desired auto_merge.human_merge_pin_only + // map, replaced whole like HumanMergePaths: an empty (non-nil) map + // clears it, absent leaves it untouched. + HumanMergePinOnly map[string]config.PinOnlyException `json:"human_merge_pin_only"` // BotTakeoverEnabled is auto_merge.bot_takeover.enabled; flat so the // dialog's plain toggle can stage it. BotTakeoverEnabled *bool `json:"bot_takeover_enabled"` @@ -247,6 +251,21 @@ func (s *Server) handleAutoMergePut(w http.ResponseWriter, r *http.Request) { } humanMergePaths = paths } + var humanMergePinOnly map[string]config.PinOnlyException + if body.HumanMergePinOnly != nil { + // A new or changed exception is checked against the human-merge paths + // this write leaves in place: the ones in the body when it sends them. + pathsAfter := s.deps.Config.AutoMerge.HumanMergePaths + if body.HumanMergePaths != nil { + pathsAfter = humanMergePaths + } + policies, msg := s.autoMergeHumanMergePinOnly(body.HumanMergePinOnly, s.deps.Config.AutoMerge.HumanMergePinOnly, pathsAfter) + if msg != "" { + jsonError(w, msg, http.StatusBadRequest) + return + } + humanMergePinOnly = policies + } var trustedAuthorRepos []string var trustedAuthorLabels []string if body.TrustedAuthors != nil { @@ -363,6 +382,9 @@ func (s *Server) handleAutoMergePut(w http.ResponseWriter, r *http.Request) { if body.HumanMergePaths != nil { cfg.AutoMerge.HumanMergePaths = humanMergePaths } + if body.HumanMergePinOnly != nil { + cfg.AutoMerge.HumanMergePinOnly = humanMergePinOnly + } if body.BotTakeoverEnabled != nil { v := *body.BotTakeoverEnabled cfg.AutoMerge.BotTakeover.Enabled = &v @@ -430,7 +452,9 @@ func (s *Server) handleAutoMergePut(w http.ResponseWriter, r *http.Request) { if err := s.saveConfig(); err != nil { s.logger.Error("failed to persist config after auto-merge update", "error", err) - if body.NativeMergeQueue != nil || body.MergeTrain != nil { + // A pin-only exception lets PRs past a human-merge hold, so one that + // cannot be saved is not left running until the next restart drops it. + if body.NativeMergeQueue != nil || body.MergeTrain != nil || body.HumanMergePinOnly != nil { cfg.AutoMerge = previousAutoMerge syncAutoMergePolicyToGitHubClient(cfg, s.deps.GHClient) jsonError(w, "failed to persist auto-merge settings", http.StatusInternalServerError) @@ -477,6 +501,13 @@ func autoMergeSectionResponse(cfg *config.Config) map[string]interface{} { if humanMergePaths == nil { humanMergePaths = map[string][]string{} } + humanMergePinOnly := make(map[string]config.PinOnlyException, len(am.HumanMergePinOnly)) + for repo, policy := range am.HumanMergePinOnly { + policy.Paths = emptyIfNilStrings(policy.Paths) + policy.Kinds = emptyIfNilStrings(policy.Kinds) + policy.TrustedAuthors = emptyIfNilStrings(policy.TrustedAuthors) + humanMergePinOnly[repo] = policy + } projectRepos := make([]string, 0, len(cfg.Project.Repos)) for _, repo := range cfg.Project.Repos { if full := config.QualifyRepo(cfg.Project.Org, repo); full != "" { @@ -516,6 +547,8 @@ func autoMergeSectionResponse(cfg *config.Config) map[string]interface{} { "squash_only": squashOnly, "require_current_base": requireCurrentBase, "human_merge_paths": humanMergePaths, + "human_merge_pin_only": humanMergePinOnly, + "pin_only_kinds": config.PinOnlyKinds, "project_repos": projectRepos, "trusted_bot_authors": trustedBots, "trusted_bot_authors_set": am.TrustedBotAuthors != nil, @@ -642,6 +675,16 @@ func syncAutoMergePolicyToGitHubClient(cfg *config.Config, ghClient *ghpkg.Clien ghClient.SetMergeRequestAllowUnprotectedBaseRepos(cfg.AutoMerge.AllowUnprotectedBaseSet()) ghClient.SetMergeRequestNoCIAllowedRepos(cfg.AutoMerge.NoCIOKSet()) ghClient.SetHumanMergePaths(cfg.AutoMerge.HumanMergePaths) + // The merge-request relay holds its own copy of the pin-only exception + // (cmd/hive's syncAutoMergePolicyToGitHubClient installs it the same way + // on boot and reload); the sweep lanes and /approve read cfg directly. + pinOnly := make(map[string]ghpkg.PinOnlySpec) + for repo := range cfg.AutoMerge.HumanMergePinOnly { + if ex, enabled := cfg.AutoMerge.HumanMergePinOnlyFor(repo); enabled { + pinOnly[repo] = ghpkg.PinOnlySpec{Enabled: true, Paths: ex.Paths, Kinds: ex.Kinds, TrustedAuthors: ex.TrustedAuthors} + } + } + ghClient.SetHumanMergePinOnly(pinOnly) ghClient.SetAutoMergeMinHeadAge(cfg.AutoMerge.EffectiveMinHeadAge()) } @@ -720,6 +763,92 @@ func (s *Server) autoMergeHumanMergePaths(paths map[string][]string) (map[string return out, "" } +// autoMergeHumanMergePinOnly validates auto_merge.human_merge_pin_only sent by +// the dashboard or admin MCP. Keys follow autoMergeWatchedRepo; each list is +// trimmed and de-duplicated; a disabled entry with nothing in it is dropped; +// the result must pass config.ValidateHumanMergePinOnly, the rule hive.yaml +// loads under. An enabled entry the write adds or changes also needs +// human_merge_paths for its repository (pathsAfter), because the exception +// only ever lifts a human-merge-path hold: without one it would never apply. +// A non-empty msg is the 400 to return. +func (s *Server) autoMergeHumanMergePinOnly(in, current map[string]config.PinOnlyException, pathsAfter map[string][]string) (map[string]config.PinOnlyException, string) { + keys := make([]string, 0, len(in)) + for k := range in { + keys = append(keys, k) + } + sort.Strings(keys) + out := map[string]config.PinOnlyException{} + seen := map[string]bool{} + for _, k := range keys { + full, msg := s.autoMergeWatchedRepo("human_merge_pin_only", strings.TrimSpace(k)) + if msg != "" { + return nil, msg + } + if seen[strings.ToLower(full)] { + return nil, "human_merge_pin_only names " + full + " twice" + } + seen[strings.ToLower(full)] = true + policy := config.PinOnlyException{ + Enabled: in[k].Enabled, + Paths: dedupeTrimmedStrings(in[k].Paths), + Kinds: dedupeTrimmedStrings(in[k].Kinds), + TrustedAuthors: dedupeTrimmedStrings(in[k].TrustedAuthors), + } + if !policy.Enabled && len(policy.Paths)+len(policy.Kinds)+len(policy.TrustedAuthors) == 0 { + continue + } + out[full] = policy + } + if err := (config.AutoMergeConfig{HumanMergePinOnly: out}).ValidateHumanMergePinOnly(); err != nil { + return nil, err.Error() + } + guarded := config.AutoMergeConfig{HumanMergePaths: pathsAfter} + for _, repo := range sortedPinOnlyRepos(out) { + policy := out[repo] + if !policy.Enabled || pinOnlyUnchanged(current, repo, policy) { + continue + } + if len(guarded.HumanMergePathsFor(repo)) == 0 { + return nil, "human_merge_pin_only: " + repo + " has no human_merge_paths, so a pin-only exception there would never apply; set its human-merge paths first" + } + } + if len(out) == 0 { + return nil, "" + } + return out, "" +} + +// pinOnlyUnchanged reports whether current already holds policy for repo, so +// an entry the write sends back untouched is not re-checked. +func pinOnlyUnchanged(current map[string]config.PinOnlyException, repo string, policy config.PinOnlyException) bool { + for k, was := range current { + if strings.EqualFold(strings.TrimSpace(k), repo) { + return was.Enabled == policy.Enabled && slices.Equal(was.Paths, policy.Paths) && + slices.Equal(was.Kinds, policy.Kinds) && slices.Equal(was.TrustedAuthors, policy.TrustedAuthors) + } + } + return false +} + +func sortedPinOnlyRepos(m map[string]config.PinOnlyException) []string { + keys := make([]string, 0, len(m)) + for k := range m { + keys = append(keys, k) + } + sort.Strings(keys) + return keys +} + +func dedupeTrimmedStrings(list []string) []string { + var out []string + for _, v := range normalizeAutoMergeRepoList(list) { + if !slices.Contains(out, v) { + out = append(out, v) + } + } + return out +} + func emptyIfNilStrings(list []string) []string { if list == nil { return []string{} diff --git a/src/pkg/dashboard/api_config_automerge_pin_only_test.go b/src/pkg/dashboard/api_config_automerge_pin_only_test.go new file mode 100644 index 0000000000..e7290bf433 --- /dev/null +++ b/src/pkg/dashboard/api_config_automerge_pin_only_test.go @@ -0,0 +1,269 @@ +package dashboard + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "gopkg.in/yaml.v3" + + "github.com/hivecommons/hive/pkg/config" + ghpkg "github.com/hivecommons/hive/pkg/github" +) + +// Tests for auto_merge.human_merge_pin_only on PUT/PATCH +// /api/config/auto-merge: the pin-only exception to human_merge_paths +// (#16377) set from the dashboard instead of hive.yaml. + +// pinOnlyServer is repoPolicyServer with human-merge paths on acme/api, the +// repository the exception is set for. +func pinOnlyServer(t *testing.T) *Server { + t.Helper() + s := repoPolicyServer(t) + s.deps.Config.AutoMerge.HumanMergePaths = map[string][]string{"acme/api": {".github/workflows/**", "Containerfile"}} + return s +} + +func pinOnlyEntry() map[string]any { + return map[string]any{ + "enabled": true, + "paths": []string{" .github/workflows/*.yml ", "Containerfile", "Containerfile", ""}, + "kinds": []string{"action-sha", "image-digest"}, + "trusted_authors": []string{"renovate[bot]"}, + } +} + +func TestAutoMergePinOnly_PutGetRoundTrip(t *testing.T) { + s := pinOnlyServer(t) + rec := doPut(s, "/api/config/auto-merge", map[string]any{ + "human_merge_pin_only": map[string]any{"api": pinOnlyEntry()}, + }) + if rec.Code != http.StatusOK { + t.Fatalf("valid put: expected 200, got %d: %s", rec.Code, rec.Body.String()) + } + // The key is stored as owner/repo, and each list trimmed and de-duplicated. + policy, ok := s.deps.Config.AutoMerge.HumanMergePinOnlyFor("acme/api") + if !ok { + t.Fatalf("acme/api has no enabled exception after the put: %+v", s.deps.Config.AutoMerge.HumanMergePinOnly) + } + if strings.Join(policy.Paths, ",") != ".github/workflows/*.yml,Containerfile" || + strings.Join(policy.Kinds, ",") != "action-sha,image-digest" || + strings.Join(policy.TrustedAuthors, ",") != "renovate[bot]" { + t.Fatalf("stored policy = %+v", policy) + } + if _, ok := s.deps.Config.AutoMerge.HumanMergePinOnly["acme/api"]; !ok { + t.Fatalf("key not stored as owner/repo: %+v", s.deps.Config.AutoMerge.HumanMergePinOnly) + } + + rec = doOwnerGet(s, "/api/config/auto-merge") + if rec.Code != http.StatusOK { + t.Fatalf("GET after put: expected 200, got %d", rec.Code) + } + var got struct { + PinOnly map[string]config.PinOnlyException `json:"human_merge_pin_only"` + Kinds []string `json:"pin_only_kinds"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil { + t.Fatalf("decode GET: %v", err) + } + entry, ok := got.PinOnly["acme/api"] + if !ok || !entry.Enabled || strings.Join(entry.Paths, ",") != ".github/workflows/*.yml,Containerfile" || strings.Join(entry.TrustedAuthors, ",") != "renovate[bot]" { + t.Fatalf("human_merge_pin_only did not round-trip: %+v", got.PinOnly) + } + if strings.Join(got.Kinds, ",") != "action-sha,image-digest,version-pin" { + t.Fatalf("pin_only_kinds = %v", got.Kinds) + } + + // Absent leaves it alone; an empty map clears it, like human_merge_paths. + if rec := doPut(s, "/api/config/auto-merge", map[string]any{"max_merges": 2}); rec.Code != http.StatusOK { + t.Fatalf("unrelated put: %d %s", rec.Code, rec.Body.String()) + } + if _, ok := s.deps.Config.AutoMerge.HumanMergePinOnlyFor("acme/api"); !ok { + t.Fatal("a put without human_merge_pin_only changed it") + } + if rec := doPut(s, "/api/config/auto-merge", map[string]any{"human_merge_pin_only": map[string]any{}}); rec.Code != http.StatusOK { + t.Fatalf("clear put: %d %s", rec.Code, rec.Body.String()) + } + if s.deps.Config.AutoMerge.HumanMergePinOnly != nil { + t.Fatalf("an empty map did not clear the exception: %+v", s.deps.Config.AutoMerge.HumanMergePinOnly) + } +} + +func TestAutoMergePinOnly_InvalidIsRefusedWithNoChange(t *testing.T) { + s := pinOnlyServer(t) + if rec := doPut(s, "/api/config/auto-merge", map[string]any{"human_merge_pin_only": map[string]any{"api": pinOnlyEntry()}}); rec.Code != http.StatusOK { + t.Fatalf("seed put: %d %s", rec.Code, rec.Body.String()) + } + with := func(key string, value any) map[string]any { + e := pinOnlyEntry() + e[key] = value + return e + } + for _, tc := range []struct { + name string + body map[string]any + want string + }{ + {"unknown repo", map[string]any{"human_merge_pin_only": map[string]any{"other/repo": pinOnlyEntry()}}, "human_merge_pin_only: other/repo is not in project.repos"}, + {"twice", map[string]any{"human_merge_pin_only": map[string]any{"api": pinOnlyEntry(), "ACME/api": pinOnlyEntry()}}, "names acme/api twice"}, + {"no trusted authors", map[string]any{"human_merge_pin_only": map[string]any{"api": with("trusted_authors", []string{" "})}}, "enabled policy requires nonempty trusted_authors"}, + {"no paths", map[string]any{"human_merge_pin_only": map[string]any{"api": with("paths", []string{})}}, "enabled policy requires nonempty paths"}, + {"unknown kind", map[string]any{"human_merge_pin_only": map[string]any{"api": with("kinds", []string{"any-line"})}}, "unknown kind"}, + {"unknown kind while disabled", map[string]any{"human_merge_pin_only": map[string]any{"api": map[string]any{"enabled": false, "kinds": []string{"any-line"}}}}, "unknown kind"}, + // The exception only lifts a human-merge-path hold, so on a repository + // with no such paths it would never apply. + {"no human-merge paths", map[string]any{"human_merge_pin_only": map[string]any{"api": pinOnlyEntry(), "web": pinOnlyEntry()}}, "acme/web has no human_merge_paths"}, + {"paths cleared in the same write", map[string]any{"human_merge_paths": map[string][]string{}, "human_merge_pin_only": map[string]any{"api": with("kinds", []string{"version-pin"})}}, "acme/api has no human_merge_paths"}, + // A valid key alongside an invalid one must not half-apply. + {"mixed", map[string]any{"max_merges": 7, "squash_only": []string{"api"}, "human_merge_pin_only": map[string]any{"api": with("kinds", []string{"nope"})}}, "unknown kind"}, + } { + rec := doPut(s, "/api/config/auto-merge", tc.body) + if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), tc.want) { + t.Fatalf("%s: expected 400 containing %q, got %d: %s", tc.name, tc.want, rec.Code, rec.Body.String()) + } + } + am := s.deps.Config.AutoMerge + policy, ok := am.HumanMergePinOnlyFor("acme/api") + if !ok || len(am.HumanMergePinOnly) != 1 || strings.Join(policy.Kinds, ",") != "action-sha,image-digest" { + t.Fatalf("rejected writes changed human_merge_pin_only: %+v", am.HumanMergePinOnly) + } + if am.MaxMerges != 0 || am.SquashOnly != nil || len(am.HumanMergePathsFor("acme/api")) != 2 { + t.Fatalf("rejected writes changed other settings: %+v", am) + } +} + +// An entry hive.yaml already holds is not re-checked when a write sends it +// back unchanged, so a full-map save from the dashboard still works on a hive +// whose file carries an exception for a repository without human-merge paths. +func TestAutoMergePinOnly_UnchangedEntryIsNotRechecked(t *testing.T) { + s := pinOnlyServer(t) + s.deps.Config.AutoMerge.HumanMergePinOnly = map[string]config.PinOnlyException{ + "acme/web": {Enabled: true, Paths: []string{"Containerfile"}, Kinds: []string{"image-digest"}, TrustedAuthors: []string{"renovate[bot]"}}, + } + rec := doPut(s, "/api/config/auto-merge", map[string]any{"human_merge_pin_only": map[string]any{ + "acme/web": map[string]any{"enabled": true, "paths": []string{"Containerfile"}, "kinds": []string{"image-digest"}, "trusted_authors": []string{"renovate[bot]"}}, + "api": pinOnlyEntry(), + }}) + if rec.Code != http.StatusOK { + t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body.String()) + } + if len(s.deps.Config.AutoMerge.HumanMergePinOnly) != 2 { + t.Fatalf("human_merge_pin_only = %+v", s.deps.Config.AutoMerge.HumanMergePinOnly) + } +} + +func TestAutoMergePinOnly_NonOwnerIsForbidden(t *testing.T) { + s := pinOnlyServer(t) + for _, tc := range []struct { + name string + role string + verified bool + }{ + {"merger", "merger", true}, + {"unverified owner", "owner", false}, + {"no role", "", false}, + } { + body, _ := json.Marshal(map[string]any{"human_merge_pin_only": map[string]any{"api": pinOnlyEntry()}}) + for _, method := range []string{http.MethodPut, http.MethodPatch} { + req := httptest.NewRequest(method, "/api/config/auto-merge", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + if tc.role != "" { + req.Header.Set("X-Hive-Role", tc.role) + } + if tc.verified { + req.Header.Set(ownerRoleVerifiedHeader, "true") + } + rec := httptest.NewRecorder() + s.mux.ServeHTTP(rec, req) + if rec.Code != http.StatusForbidden { + t.Fatalf("%s %s: expected 403, got %d: %s", tc.name, method, rec.Code, rec.Body.String()) + } + } + } + if s.deps.Config.AutoMerge.HumanMergePinOnly != nil { + t.Fatalf("a non-owner write changed human_merge_pin_only: %+v", s.deps.Config.AutoMerge.HumanMergePinOnly) + } +} + +// The sweep lanes and /approve read the exception through the shared config +// on every evaluation (cmd/hive humanMergePinOnlyFor), and the merge-request +// relay holds a copy the write must refresh. Both see a write at once, with +// no restart, and both lose it when it is cleared. +func TestAutoMergePinOnly_ReachesRunningHiveWithoutRestart(t *testing.T) { + s := pinOnlyServer(t) + client := ghpkg.NewClientForTest("http://127.0.0.1:1", "acme", []string{"api"}, covBLogger()) + s.deps.GHClient = client + live := s.deps.Config // the pointer the sweeps were built with + + if rec := doPut(s, "/api/config/auto-merge", map[string]any{"human_merge_pin_only": map[string]any{"api": pinOnlyEntry()}}); rec.Code != http.StatusOK { + t.Fatalf("put: %d %s", rec.Code, rec.Body.String()) + } + if policy, ok := live.AutoMerge.HumanMergePinOnlyFor("acme/api"); !ok || strings.Join(policy.TrustedAuthors, ",") != "renovate[bot]" { + t.Fatalf("the sweep's config does not hold the exception: %+v", live.AutoMerge.HumanMergePinOnly) + } + relay := client.HumanMergePinOnlyFor("acme/api") + if !relay.Enabled || strings.Join(relay.Paths, ",") != ".github/workflows/*.yml,Containerfile" || + strings.Join(relay.Kinds, ",") != "action-sha,image-digest" || strings.Join(relay.TrustedAuthors, ",") != "renovate[bot]" { + t.Fatalf("the merge-request relay did not pick up the exception: %+v", relay) + } + + if rec := doPut(s, "/api/config/auto-merge", map[string]any{"human_merge_pin_only": map[string]any{}}); rec.Code != http.StatusOK { + t.Fatalf("clear: %d %s", rec.Code, rec.Body.String()) + } + if _, ok := live.AutoMerge.HumanMergePinOnlyFor("acme/api"); ok { + t.Fatal("the sweep still sees a cleared exception") + } + if client.HumanMergePinOnlyFor("acme/api").Enabled { + t.Fatal("the relay still holds a cleared exception") + } +} + +func TestAutoMergePinOnly_PersistsToSavedConfig(t *testing.T) { + s := pinOnlyServer(t) + s.deps.Config.SourcePath = filepath.Join(t.TempDir(), "hive.yaml") + if rec := doPut(s, "/api/config/auto-merge", map[string]any{"human_merge_pin_only": map[string]any{"api": pinOnlyEntry()}}); rec.Code != http.StatusOK { + t.Fatalf("put: %d %s", rec.Code, rec.Body.String()) + } + data, err := os.ReadFile(s.deps.Config.SourcePath) + if err != nil { + t.Fatalf("read saved config: %v", err) + } + var saved struct { + AutoMerge config.AutoMergeConfig `yaml:"auto_merge"` + } + if err := yaml.Unmarshal(data, &saved); err != nil { + t.Fatalf("decode saved config: %v", err) + } + if policy, ok := saved.AutoMerge.HumanMergePinOnlyFor("acme/api"); !ok || strings.Join(policy.Kinds, ",") != "action-sha,image-digest" { + t.Fatalf("saved auto_merge missing human_merge_pin_only: %+v", saved.AutoMerge.HumanMergePinOnly) + } +} + +// The Merge settings page edits the exception next to the human-merge paths +// and stages the whole map under human_merge_pin_only. +func TestAutoMergePinOnlySettingsStaticWiring(t *testing.T) { + html, err := os.ReadFile("static/index.html") + if err != nil { + t.Fatalf("read static index: %v", err) + } + s := string(html) + for _, want := range []string{ + "id=\"am-human-merge-pin-only\"", + "class=\"am-pin-only-enabled\"", + "class=\"am-pin-only-kind\"", + "data-change-action=\"markDirtyAutoMergePinOnly\"", + "function markDirtyAutoMergePinOnly()", + "markDirty('auto-merge', 'human_merge_pin_only'", + "am.human_merge_pin_only", + "am.pin_only_kinds", + } { + if !strings.Contains(s, want) { + t.Fatalf("static dashboard missing %q", want) + } + } +} diff --git a/src/pkg/dashboard/settings_parity_allowlist.txt b/src/pkg/dashboard/settings_parity_allowlist.txt index 8885bb10cd..e4381b0610 100644 --- a/src/pkg/dashboard/settings_parity_allowlist.txt +++ b/src/pkg/dashboard/settings_parity_allowlist.txt @@ -160,10 +160,6 @@ agents.session_recycle.max_rss_mb # TODO #11854 agents.session_recycle.min_idle # TODO #11854 auto_merge.credit_issue_authors # merge-time Co-authored-by credit (#14581); yaml-only auto_merge.allow_unprotected_base[] # TODO #11854 -auto_merge.human_merge_pin_only..enabled # bounded pin-only human-merge policy (#16262); yaml-only -auto_merge.human_merge_pin_only..kinds[] # bounded pin-only human-merge policy (#16262); yaml-only -auto_merge.human_merge_pin_only..paths[] # bounded pin-only human-merge policy (#16262); yaml-only -auto_merge.human_merge_pin_only..trusted_authors[] # bounded pin-only human-merge policy (#16262); yaml-only auto_merge.human_merge_title_prefixes[] # breaking-titled PRs wait for a human; yaml-only auto_merge.human_merge_labels[] # needs-owner-merge PRs wait for a human; yaml-only auto_merge.merge_forward_trusted_human[] # TODO #11854 diff --git a/src/pkg/dashboard/static-src/css/config-dialog.css b/src/pkg/dashboard/static-src/css/config-dialog.css index e3fc78bf03..869b4b2149 100644 --- a/src/pkg/dashboard/static-src/css/config-dialog.css +++ b/src/pkg/dashboard/static-src/css/config-dialog.css @@ -255,6 +255,8 @@ .am-bot-source { color: var(--muted); font-weight: 400; } #am-trusted-authors { margin-top: var(--sp-5); border-top: 1px solid var(--border); } .am-trusted-authors-note { font-size: var(--fs-xs); color: var(--muted); margin: var(--sp-2) var(--sp-0) var(--sp-0); } + .am-pin-only-row .am-pin-only-opt { display: inline-flex; align-items: center; gap: var(--sp-1); margin: var(--sp-1) var(--sp-3) var(--sp-1) var(--sp-0); font-size: var(--fs-xs); } + .am-pin-only-row input[type="text"] { margin-top: var(--sp-1); } .rv-reviewer-list { padding: var(--sp-2) var(--sp-3); border: 1px solid var(--border); border-radius: var(--r); } .rv-reviewer-row { display: flex; align-items: center; gap: var(--sp-3); font-size: var(--fs-sm); padding: var(--sp-1) var(--sp-0); cursor: pointer; } .rv-reviewer-row.rv-reviewer-unavailable { opacity: 0.6; } diff --git a/src/pkg/dashboard/static-src/js/config-features.js b/src/pkg/dashboard/static-src/js/config-features.js index 04668fdcc2..4dd4ccf8a6 100644 --- a/src/pkg/dashboard/static-src/js/config-features.js +++ b/src/pkg/dashboard/static-src/js/config-features.js @@ -421,6 +421,19 @@ const key = Object.keys(amHumanMergePaths).find(k => k.toLowerCase() === String(repo).toLowerCase()); return key && Array.isArray(amHumanMergePaths[key]) ? amHumanMergePaths[key] : []; }; + // auto_merge.human_merge_pin_only: one row per repository that has + // human-merge paths or already holds an exception (it only ever lifts a + // human-merge-path hold, so elsewhere it would never apply). + const amPinOnly = (am.human_merge_pin_only && typeof am.human_merge_pin_only === 'object') ? am.human_merge_pin_only : {}; + const amPinOnlyKinds = Array.isArray(am.pin_only_kinds) && am.pin_only_kinds.length ? am.pin_only_kinds : ['action-sha', 'image-digest', 'version-pin']; + const amPinOnlyFor = (repo) => { + const key = Object.keys(amPinOnly).find(k => k.toLowerCase() === String(repo).toLowerCase()); + const e = key && amPinOnly[key] && typeof amPinOnly[key] === 'object' ? amPinOnly[key] : {}; + const list = (v) => Array.isArray(v) ? v : []; + return { enabled: e.enabled === true, paths: list(e.paths), kinds: list(e.kinds), trusted_authors: list(e.trusted_authors) }; + }; + const amPinOnlyRepos = amHumanMergePathRepos.filter(r => amHumanMergePathsFor(r).length || Object.keys(amPinOnly).some(k => k.toLowerCase() === String(r).toLowerCase())) + .concat(Object.keys(amPinOnly).filter(k => !amHumanMergePathRepos.some(r => String(r).toLowerCase() === k.toLowerCase()))); const amBotSourceLabel = { known: 'known bot', discovered: 'seen in open PRs', custom: 'added manually' }; const amBotRow = (b) => `
@@ -558,7 +571,17 @@
`).join('') : '

No repositories in project.repos yet.

'} -

Select nothing (or leave paths empty) to turn a rule off for every repo. YAML keys: auto_merge.require_current_base[], auto_merge.squash_only[], ${esc('auto_merge.human_merge_paths.')}.

+
+ + ${amPinOnlyRepos.length ? amPinOnlyRepos.map(r => { const p = amPinOnlyFor(r); return `
+ + + + ${amPinOnlyKinds.map(k => ``).join(' ')} + +
`; }).join('') : '

Set paths a person must merge for a repository first; its pin-only exception is edited here.

'} +
+

Select nothing (or leave paths empty) to turn a rule off for every repo. YAML keys: auto_merge.require_current_base[], auto_merge.squash_only[], ${esc('auto_merge.human_merge_paths.')}, ${esc('auto_merge.human_merge_pin_only..enabled')}, ${esc('auto_merge.human_merge_pin_only..paths[]')}, ${esc('auto_merge.human_merge_pin_only..kinds[]')}, ${esc('auto_merge.human_merge_pin_only..trusted_authors[]')}.

diff --git a/src/pkg/dashboard/static-src/js/config-helpers.js b/src/pkg/dashboard/static-src/js/config-helpers.js index d0a6d98b98..4e8be32c88 100644 --- a/src/pkg/dashboard/static-src/js/config-helpers.js +++ b/src/pkg/dashboard/static-src/js/config-helpers.js @@ -431,6 +431,26 @@ } } + // Settings → Features → Auto-merge → Pin bumps that skip the hand merge. + // Stages auto_merge.human_merge_pin_only in full, one entry per row; a + // row that is off with nothing filled in drops out. + function markDirtyAutoMergePinOnly() { + const policies = {}; + document.querySelectorAll('#am-human-merge-pin-only .am-pin-only-row').forEach(row => { + const enabled = row.querySelector('.am-pin-only-enabled'); + const paths = row.querySelector('.am-pin-only-paths'); + const authors = row.querySelector('.am-pin-only-authors'); + const entry = { + enabled: !!(enabled && enabled.checked), + paths: splitConfigLines(paths ? paths.value : ''), + kinds: Array.from(row.querySelectorAll('.am-pin-only-kind')).filter(k => k.checked).map(k => k.value), + trusted_authors: splitConfigLines(authors ? authors.value : '') + }; + if (row.dataset.repo && (entry.enabled || entry.paths.length || entry.kinds.length || entry.trusted_authors.length)) policies[row.dataset.repo] = entry; + }); + markDirty('auto-merge', 'human_merge_pin_only', policies); + } + function markDirtyContributorLane() { const enabled = document.getElementById('am-contributor-lane-enabled'); const verdict = document.getElementById('am-contributor-lane-require-reviewer-verdict'); diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 0fa54f9591..ef183f59bc 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -4757,6 +4757,8 @@ .am-bot-source { color: var(--muted); font-weight: 400; } #am-trusted-authors { margin-top: var(--sp-5); border-top: 1px solid var(--border); } .am-trusted-authors-note { font-size: var(--fs-xs); color: var(--muted); margin: var(--sp-2) var(--sp-0) var(--sp-0); } + .am-pin-only-row .am-pin-only-opt { display: inline-flex; align-items: center; gap: var(--sp-1); margin: var(--sp-1) var(--sp-3) var(--sp-1) var(--sp-0); font-size: var(--fs-xs); } + .am-pin-only-row input[type="text"] { margin-top: var(--sp-1); } .rv-reviewer-list { padding: var(--sp-2) var(--sp-3); border: 1px solid var(--border); border-radius: var(--r); } .rv-reviewer-row { display: flex; align-items: center; gap: var(--sp-3); font-size: var(--fs-sm); padding: var(--sp-1) var(--sp-0); cursor: pointer; } .rv-reviewer-row.rv-reviewer-unavailable { opacity: 0.6; } @@ -66871,6 +66873,19 @@

${esc(s.title)}

const key = Object.keys(amHumanMergePaths).find(k => k.toLowerCase() === String(repo).toLowerCase()); return key && Array.isArray(amHumanMergePaths[key]) ? amHumanMergePaths[key] : []; }; + // auto_merge.human_merge_pin_only: one row per repository that has + // human-merge paths or already holds an exception (it only ever lifts a + // human-merge-path hold, so elsewhere it would never apply). + const amPinOnly = (am.human_merge_pin_only && typeof am.human_merge_pin_only === 'object') ? am.human_merge_pin_only : {}; + const amPinOnlyKinds = Array.isArray(am.pin_only_kinds) && am.pin_only_kinds.length ? am.pin_only_kinds : ['action-sha', 'image-digest', 'version-pin']; + const amPinOnlyFor = (repo) => { + const key = Object.keys(amPinOnly).find(k => k.toLowerCase() === String(repo).toLowerCase()); + const e = key && amPinOnly[key] && typeof amPinOnly[key] === 'object' ? amPinOnly[key] : {}; + const list = (v) => Array.isArray(v) ? v : []; + return { enabled: e.enabled === true, paths: list(e.paths), kinds: list(e.kinds), trusted_authors: list(e.trusted_authors) }; + }; + const amPinOnlyRepos = amHumanMergePathRepos.filter(r => amHumanMergePathsFor(r).length || Object.keys(amPinOnly).some(k => k.toLowerCase() === String(r).toLowerCase())) + .concat(Object.keys(amPinOnly).filter(k => !amHumanMergePathRepos.some(r => String(r).toLowerCase() === k.toLowerCase()))); const amBotSourceLabel = { known: 'known bot', discovered: 'seen in open PRs', custom: 'added manually' }; const amBotRow = (b) => `
@@ -67008,7 +67023,17 @@

${esc(s.title)}

`).join('') : '

No repositories in project.repos yet.

'}
-

Select nothing (or leave paths empty) to turn a rule off for every repo. YAML keys: auto_merge.require_current_base[], auto_merge.squash_only[], ${esc('auto_merge.human_merge_paths.')}.

+
+ + ${amPinOnlyRepos.length ? amPinOnlyRepos.map(r => { const p = amPinOnlyFor(r); return `
+ + + + ${amPinOnlyKinds.map(k => ``).join(' ')} + +
`; }).join('') : '

Set paths a person must merge for a repository first; its pin-only exception is edited here.

'} +
+

Select nothing (or leave paths empty) to turn a rule off for every repo. YAML keys: auto_merge.require_current_base[], auto_merge.squash_only[], ${esc('auto_merge.human_merge_paths.')}, ${esc('auto_merge.human_merge_pin_only..enabled')}, ${esc('auto_merge.human_merge_pin_only..paths[]')}, ${esc('auto_merge.human_merge_pin_only..kinds[]')}, ${esc('auto_merge.human_merge_pin_only..trusted_authors[]')}.

@@ -70226,6 +70251,26 @@

${model.editIndex === null ? 'Add Event trigger' : 'Edit Event trigger'}

{ + const enabled = row.querySelector('.am-pin-only-enabled'); + const paths = row.querySelector('.am-pin-only-paths'); + const authors = row.querySelector('.am-pin-only-authors'); + const entry = { + enabled: !!(enabled && enabled.checked), + paths: splitConfigLines(paths ? paths.value : ''), + kinds: Array.from(row.querySelectorAll('.am-pin-only-kind')).filter(k => k.checked).map(k => k.value), + trusted_authors: splitConfigLines(authors ? authors.value : '') + }; + if (row.dataset.repo && (entry.enabled || entry.paths.length || entry.kinds.length || entry.trusted_authors.length)) policies[row.dataset.repo] = entry; + }); + markDirty('auto-merge', 'human_merge_pin_only', policies); + } + function markDirtyContributorLane() { const enabled = document.getElementById('am-contributor-lane-enabled'); const verdict = document.getElementById('am-contributor-lane-require-reviewer-verdict'); diff --git a/src/pkg/github/human_merge_paths.go b/src/pkg/github/human_merge_paths.go index 5082e66f73..74623ba133 100644 --- a/src/pkg/github/human_merge_paths.go +++ b/src/pkg/github/human_merge_paths.go @@ -232,6 +232,13 @@ func (c *Client) SetHumanMergePinOnly(policies map[string]PinOnlySpec) { c.humanMergePinOnly = normalized } +// HumanMergePinOnlyFor returns a copy of the relay's pin-only policy for repo +// (owner/repo or a bare name in the client's org), the value the last +// SetHumanMergePinOnly installed; disabled when none. +func (c *Client) HumanMergePinOnlyFor(repo string) PinOnlySpec { + return c.humanMergePinOnlyFor(repo) +} + func (c *Client) humanMergePinOnlyFor(repo string) PinOnlySpec { if c == nil { return PinOnlySpec{} From 11858dd22fddb1d908f27597ed93b853916f880b Mon Sep 17 00:00:00 2001 From: Danathar Date: Mon, 9 Nov 2026 20:07:00 -0500 Subject: [PATCH 4/4] =?UTF-8?q?=F0=9F=8C=B1=20chore(automerge):=20prefix?= =?UTF-8?q?=20the=20pin-only=20helpers=20with=20the=20op=20name?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BQYnPGFJx81c8JXR3o1sg1 Signed-off-by: Danathar --- src/pkg/adminmcp/tools_automerge_ops.go | 72 +++++++++---------- .../adminmcp/tools_automerge_pin_only_test.go | 40 +++++------ src/pkg/dashboard/api_config_automerge.go | 18 ++--- .../api_config_automerge_pin_only_test.go | 38 +++++----- 4 files changed, 84 insertions(+), 84 deletions(-) diff --git a/src/pkg/adminmcp/tools_automerge_ops.go b/src/pkg/adminmcp/tools_automerge_ops.go index 1756d72bb9..63444a6925 100644 --- a/src/pkg/adminmcp/tools_automerge_ops.go +++ b/src/pkg/adminmcp/tools_automerge_ops.go @@ -301,10 +301,10 @@ type amRow struct { // rather than as keys. func (c amPlanned) rows() []amRow { if c.field.kind == amPinOnly { - before := pinOnlyValue(c.before) - after, _ := c.after.(map[string]amPin) + before := autoMergePinOnlyValue(c.before) + after, _ := c.after.(map[string]autoMergePinOnlyEntry) var rows []amRow - for _, repo := range unionPinOnlyKeys(before, after) { + for _, repo := range autoMergePinOnlyKeys(before, after) { b, hadB := before[repo] a, hasA := after[repo] if hadB == hasA && compactJSON(b) == compactJSON(a) { @@ -417,7 +417,7 @@ func planAutoMergeUpdate(ctx context.Context, args map[string]any, provider Prov if len(plan.changes) == 0 { return amPlan{}, fmt.Errorf("nothing would change: %s already as requested", strings.Join(plan.unchanged, ", ")) } - if err := checkPinOnlyGuarded(plan, current); err != nil { + if err := autoMergeCheckPinOnlyGuarded(plan, current); err != nil { return amPlan{}, err } plan.fingerprint = settingsFingerprint(beforeValues) @@ -518,7 +518,7 @@ func (f *amField) apply(before, raw any, projectRepos []string) (any, error) { case amRepoPaths: return applyRepoPaths(before, raw, projectRepos) case amPinOnly: - return applyPinOnly(before, raw, projectRepos) + return autoMergeApplyPinOnly(before, raw, projectRepos) default: return f.applyList(before, raw, projectRepos) } @@ -685,33 +685,33 @@ func applyRepoPaths(before, raw any, projectRepos []string) (map[string][]string return out, nil } -// amPin is one repository's auto_merge.human_merge_pin_only entry as the +// autoMergePinOnlyEntry is one repository's auto_merge.human_merge_pin_only entry as the // endpoint reports and takes it. The fields are in the order encoding/json // sorts map keys, so a value read back from the hive and one built here // encode the same. -type amPin struct { +type autoMergePinOnlyEntry struct { Enabled bool `json:"enabled"` Kinds []string `json:"kinds"` Paths []string `json:"paths"` TrustedAuthors []string `json:"trusted_authors"` } -// pinOnlyValue reads human_merge_pin_only as the hive reported it. -func pinOnlyValue(v any) map[string]amPin { - out := map[string]amPin{} +// autoMergePinOnlyValue reads human_merge_pin_only as the hive reported it. +func autoMergePinOnlyValue(v any) map[string]autoMergePinOnlyEntry { + out := map[string]autoMergePinOnlyEntry{} switch m := v.(type) { case map[string]any: for repo, raw := range m { e, _ := raw.(map[string]any) enabled, _ := e["enabled"].(bool) - out[repo] = amPin{ + out[repo] = autoMergePinOnlyEntry{ Enabled: enabled, Kinds: nilAsEmpty(stringListValueLoose(e["kinds"])), Paths: nilAsEmpty(stringListValueLoose(e["paths"])), TrustedAuthors: nilAsEmpty(stringListValueLoose(e["trusted_authors"])), } } - case map[string]amPin: + case map[string]autoMergePinOnlyEntry: for repo, e := range m { out[repo] = e } @@ -719,7 +719,7 @@ func pinOnlyValue(v any) map[string]amPin { return out } -func unionPinOnlyKeys(a, b map[string]amPin) []string { +func autoMergePinOnlyKeys(a, b map[string]autoMergePinOnlyEntry) []string { keys := map[string]any{} for k := range a { keys[k] = nil @@ -730,16 +730,16 @@ func unionPinOnlyKeys(a, b map[string]amPin) []string { return SortKeys(keys) } -// applyPinOnly sets or unsets the named repositories' whole pin-only +// autoMergeApplyPinOnly sets or unsets the named repositories' whole pin-only // exception and keeps every other repository's entry. The merged map must // pass the same validation hive.yaml loads under. -func applyPinOnly(before, raw any, projectRepos []string) (map[string]amPin, error) { +func autoMergeApplyPinOnly(before, raw any, projectRepos []string) (map[string]autoMergePinOnlyEntry, error) { const shape = `human_merge_pin_only takes {"owner/repo": {"enabled": true, "paths": [...], "kinds": [...], "trusted_authors": [...]}}; null removes that repository` change, ok := raw.(map[string]any) if !ok || len(change) == 0 { return nil, fmt.Errorf("%s", shape) } - out := pinOnlyValue(before) + out := autoMergePinOnlyValue(before) touched := map[string]bool{} for _, key := range SortKeys(change) { repo := qualifyProjectRepo(strings.TrimSpace(key), projectRepos) @@ -764,7 +764,7 @@ func applyPinOnly(before, raw any, projectRepos []string) (map[string]amPin, err delete(out, existing) continue } - entry, err := pinOnlyEntryArg(repo, change[key]) + entry, err := autoMergePinOnlyEntryArg(repo, change[key]) if err != nil { return nil, err } @@ -783,37 +783,37 @@ func applyPinOnly(before, raw any, projectRepos []string) (map[string]amPin, err return out, nil } -// pinOnlyEntryArg reads one repository's exception from the arguments. -func pinOnlyEntryArg(repo string, raw any) (amPin, error) { +// autoMergePinOnlyEntryArg reads one repository's exception from the arguments. +func autoMergePinOnlyEntryArg(repo string, raw any) (autoMergePinOnlyEntry, error) { obj, ok := raw.(map[string]any) if !ok { - return amPin{}, fmt.Errorf("human_merge_pin_only[%s] must be an object with enabled, paths, kinds and trusted_authors, or null", repo) + return autoMergePinOnlyEntry{}, fmt.Errorf("human_merge_pin_only[%s] must be an object with enabled, paths, kinds and trusted_authors, or null", repo) } for k := range obj { switch k { case "enabled", "paths", "kinds", "trusted_authors": default: - return amPin{}, fmt.Errorf("human_merge_pin_only[%s] takes enabled, paths, kinds and trusted_authors, not %q", repo, k) + return autoMergePinOnlyEntry{}, fmt.Errorf("human_merge_pin_only[%s] takes enabled, paths, kinds and trusted_authors, not %q", repo, k) } } enabled, ok := obj["enabled"].(bool) if !ok { - return amPin{}, fmt.Errorf("human_merge_pin_only[%s].enabled must be true or false", repo) + return autoMergePinOnlyEntry{}, fmt.Errorf("human_merge_pin_only[%s].enabled must be true or false", repo) } - entry := amPin{Enabled: enabled} + entry := autoMergePinOnlyEntry{Enabled: enabled} for _, f := range []struct { name string dst *[]string }{{"kinds", &entry.Kinds}, {"paths", &entry.Paths}, {"trusted_authors", &entry.TrustedAuthors}} { list, err := stringListValue(obj[f.name]) if err != nil { - return amPin{}, fmt.Errorf("human_merge_pin_only[%s].%s must be a list of strings", repo, f.name) + return autoMergePinOnlyEntry{}, fmt.Errorf("human_merge_pin_only[%s].%s must be a list of strings", repo, f.name) } vals := []string{} for _, v := range list { v = strings.TrimSpace(v) if v == "" { - return amPin{}, fmt.Errorf("human_merge_pin_only[%s].%s entries must be non-empty", repo, f.name) + return autoMergePinOnlyEntry{}, fmt.Errorf("human_merge_pin_only[%s].%s entries must be non-empty", repo, f.name) } if !slices.Contains(vals, v) { vals = append(vals, v) @@ -824,11 +824,11 @@ func pinOnlyEntryArg(repo string, raw any) (amPin, error) { return entry, nil } -// checkPinOnlyGuarded refuses an enabled pin-only exception the change adds +// autoMergeCheckPinOnlyGuarded refuses an enabled pin-only exception the change adds // or alters for a repository that has no human_merge_paths after the change, // as the endpoint does: the exception only lifts a human-merge-path hold, so // there it would never apply. -func checkPinOnlyGuarded(plan amPlan, current map[string]any) error { +func autoMergeCheckPinOnlyGuarded(plan amPlan, current map[string]any) error { var pin *amPlanned for i := range plan.changes { if plan.changes[i].field.kind == amPinOnly { @@ -842,9 +842,9 @@ func checkPinOnlyGuarded(plan amPlan, current map[string]any) error { if sent, ok := plan.body["human_merge_paths"]; ok { paths = repoPathsValue(sent) } - before := pinOnlyValue(pin.before) - after, _ := pin.after.(map[string]amPin) - for _, repo := range unionPinOnlyKeys(after, nil) { + before := autoMergePinOnlyValue(pin.before) + after, _ := pin.after.(map[string]autoMergePinOnlyEntry) + for _, repo := range autoMergePinOnlyKeys(after, nil) { e := after[repo] if b, had := before[repo]; !e.Enabled || (had && compactJSON(b) == compactJSON(e)) { continue @@ -862,14 +862,14 @@ func checkPinOnlyGuarded(plan amPlan, current map[string]any) error { return nil } -// pinOnlyWidening names what a human_merge_pin_only change lets merge without +// autoMergePinOnlyWidening names what a human_merge_pin_only change lets merge without // a hand merge: a repository whose exception turns on, or an enabled one that // gains paths, kinds or trusted authors. Removing any of those narrows it. -func pinOnlyWidening(before, after any) []string { - was := pinOnlyValue(before) - now := pinOnlyValue(after) +func autoMergePinOnlyWidening(before, after any) []string { + was := autoMergePinOnlyValue(before) + now := autoMergePinOnlyValue(after) var notes []string - for _, repo := range unionPinOnlyKeys(now, nil) { + for _, repo := range autoMergePinOnlyKeys(now, nil) { e := now[repo] if !e.Enabled { continue @@ -956,7 +956,7 @@ func (f *amField) widening(before, after any, projectRepos []string) []string { return note("repo → hive") } case amWidenPinOnly: - return pinOnlyWidening(before, after) + return autoMergePinOnlyWidening(before, after) case amWidenPaths: was := repoPathsValue(before) now, _ := after.(map[string][]string) diff --git a/src/pkg/adminmcp/tools_automerge_pin_only_test.go b/src/pkg/adminmcp/tools_automerge_pin_only_test.go index 80fe4dd8eb..94845ba960 100644 --- a/src/pkg/adminmcp/tools_automerge_pin_only_test.go +++ b/src/pkg/adminmcp/tools_automerge_pin_only_test.go @@ -10,9 +10,9 @@ import ( // auto_merge.update and auto_merge.human_merge_pin_only: the pin-only // exception to human_merge_paths (#16377), set one repository at a time. -// pinOnlyFixture is autoMergeFixture on a hive that reports +// autoMergePinOnlyFixture is autoMergeFixture on a hive that reports // human_merge_pin_only, with an exception already set for org/a. -func pinOnlyFixture() map[string]any { +func autoMergePinOnlyFixture() map[string]any { f := autoMergeFixture() f["human_merge_pin_only"] = map[string]any{ "org/a": map[string]any{"enabled": true, "paths": []string{".github/workflows/*.yml", "Containerfile"}, "kinds": []string{"action-sha", "image-digest"}, "trusted_authors": []string{"renovate[bot]"}}, @@ -20,17 +20,17 @@ func pinOnlyFixture() map[string]any { return f } -func pinOnlyArg(paths, kinds, authors []any) map[string]any { +func autoMergePinOnlyArg(paths, kinds, authors []any) map[string]any { return map[string]any{"enabled": true, "paths": paths, "kinds": kinds, "trusted_authors": authors} } // Setting one repository's exception sends the whole map back with every // other repository's entry unchanged, and says what will now merge on its own. func TestAutoMergeUpdatePinOnlySetKeepsOtherRepos(t *testing.T) { - p := &autoMergeProvider{settings: pinOnlyFixture()} + p := &autoMergeProvider{settings: autoMergePinOnlyFixture()} h := autoMergeHandler(p) preview, id := autoMergePreview(t, h, map[string]any{ - "human_merge_pin_only": map[string]any{"b": pinOnlyArg([]any{"CODEOWNERS", " CODEOWNERS "}, []any{"version-pin"}, []any{"dependabot[bot]"})}, + "human_merge_pin_only": map[string]any{"b": autoMergePinOnlyArg([]any{"CODEOWNERS", " CODEOWNERS "}, []any{"version-pin"}, []any{"dependabot[bot]"})}, }) want := `{"human_merge_pin_only":{` + `"org/a":{"enabled":true,"kinds":["action-sha","image-digest"],"paths":[".github/workflows/*.yml","Containerfile"],"trusted_authors":["renovate[bot]"]},` + @@ -62,7 +62,7 @@ func TestAutoMergeUpdatePinOnlySetKeepsOtherRepos(t *testing.T) { // pull requests past a human-merge hold. Taking any of those away does not. func TestAutoMergeUpdatePinOnlyWidening(t *testing.T) { a := func(paths, kinds, authors []any) map[string]any { - return map[string]any{"human_merge_pin_only": map[string]any{"org/a": pinOnlyArg(paths, kinds, authors)}} + return map[string]any{"human_merge_pin_only": map[string]any{"org/a": autoMergePinOnlyArg(paths, kinds, authors)}} } paths, kinds, ra := []any{".github/workflows/*.yml", "Containerfile"}, []any{"action-sha", "image-digest"}, []any{"renovate[bot]"} for name, tc := range map[string]struct { @@ -70,7 +70,7 @@ func TestAutoMergeUpdatePinOnlyWidening(t *testing.T) { widen bool names string }{ - "new repository": {map[string]any{"human_merge_pin_only": map[string]any{"org/b": pinOnlyArg([]any{"CODEOWNERS"}, []any{"action-sha"}, ra)}}, true, "human_merge_pin_only[org/b] turned on"}, + "new repository": {map[string]any{"human_merge_pin_only": map[string]any{"org/b": autoMergePinOnlyArg([]any{"CODEOWNERS"}, []any{"action-sha"}, ra)}}, true, "human_merge_pin_only[org/b] turned on"}, "adds a path": {a(append([]any{".claude/hooks/*.sh"}, paths...), kinds, ra), true, "paths .claude/hooks/*.sh"}, "adds a kind": {a(paths, []any{"action-sha", "image-digest", "version-pin"}, ra), true, "kinds version-pin"}, "adds an author": {a(paths, kinds, []any{"renovate[bot]", "someone"}), true, "trusted_authors someone"}, @@ -81,7 +81,7 @@ func TestAutoMergeUpdatePinOnlyWidening(t *testing.T) { "unset with null": {map[string]any{"human_merge_pin_only": map[string]any{"org/a": nil}}, false, ""}, } { t.Run(name, func(t *testing.T) { - preview, _ := autoMergePreview(t, autoMergeHandler(&autoMergeProvider{settings: pinOnlyFixture()}), tc.args) + preview, _ := autoMergePreview(t, autoMergeHandler(&autoMergeProvider{settings: autoMergePinOnlyFixture()}), tc.args) if got := strings.HasPrefix(preview.WideningDisclosure, "Widening:"); got != tc.widen { t.Fatalf("widening = %v, want %v: %s", got, tc.widen, preview.WideningDisclosure) } @@ -99,10 +99,10 @@ func TestAutoMergeUpdatePinOnlyWidening(t *testing.T) { // before write_confirm, sending the merged map would undo that change, so the // confirm is refused and nothing is written. func TestAutoMergeUpdatePinOnlyRefusesStalePreview(t *testing.T) { - p := &autoMergeProvider{settings: pinOnlyFixture()} + p := &autoMergeProvider{settings: autoMergePinOnlyFixture()} h := autoMergeHandler(p) _, id := autoMergePreview(t, h, map[string]any{ - "human_merge_pin_only": map[string]any{"org/b": pinOnlyArg([]any{"CODEOWNERS"}, []any{"version-pin"}, []any{"dependabot[bot]"})}, + "human_merge_pin_only": map[string]any{"org/b": autoMergePinOnlyArg([]any{"CODEOWNERS"}, []any{"version-pin"}, []any{"dependabot[bot]"})}, }) p.settings["human_merge_pin_only"] = map[string]any{} // someone removed org/a's exception meanwhile if _, err := h.ConfirmWrite(context.Background(), map[string]any{"confirmation_id": id}); !errors.Is(err, ErrConfirmationStale) { @@ -120,16 +120,16 @@ func TestAutoMergeUpdatePinOnlyRefusals(t *testing.T) { args map[string]any want string }{ - "repository without human-merge paths": {pinOnlyFixture(), map[string]any{"human_merge_pin_only": map[string]any{"org/c": pinOnlyArg([]any{"Containerfile"}, []any{"image-digest"}, []any{"renovate[bot]"})}}, "org/c has no human_merge_paths"}, - "enabled without trusted authors": {pinOnlyFixture(), map[string]any{"human_merge_pin_only": map[string]any{"org/b": pinOnlyArg([]any{"CODEOWNERS"}, []any{"version-pin"}, nil)}}, "enabled policy requires nonempty trusted_authors"}, - "unknown kind": {pinOnlyFixture(), map[string]any{"human_merge_pin_only": map[string]any{"org/b": pinOnlyArg([]any{"CODEOWNERS"}, []any{"any-line"}, []any{"renovate[bot]"})}}, `unknown kind "any-line"`}, - "unknown entry field": {pinOnlyFixture(), map[string]any{"human_merge_pin_only": map[string]any{"org/b": map[string]any{"enabled": true, "authors": []any{"x"}}}}, `not "authors"`}, - "enabled not given": {pinOnlyFixture(), map[string]any{"human_merge_pin_only": map[string]any{"org/b": map[string]any{"paths": []any{"CODEOWNERS"}}}}, "enabled must be true or false"}, - "remove what is not there": {pinOnlyFixture(), map[string]any{"human_merge_pin_only": map[string]any{"org/b": nil}}, "no entry for org/b to remove"}, - "same entry, other casing": {pinOnlyFixture(), map[string]any{"human_merge_pin_only": map[string]any{"ORG/A": pinOnlyArg([]any{".github/workflows/*.yml", "Containerfile"}, []any{"action-sha", "image-digest"}, []any{"renovate[bot]"})}}, "nothing would change"}, + "repository without human-merge paths": {autoMergePinOnlyFixture(), map[string]any{"human_merge_pin_only": map[string]any{"org/c": autoMergePinOnlyArg([]any{"Containerfile"}, []any{"image-digest"}, []any{"renovate[bot]"})}}, "org/c has no human_merge_paths"}, + "enabled without trusted authors": {autoMergePinOnlyFixture(), map[string]any{"human_merge_pin_only": map[string]any{"org/b": autoMergePinOnlyArg([]any{"CODEOWNERS"}, []any{"version-pin"}, nil)}}, "enabled policy requires nonempty trusted_authors"}, + "unknown kind": {autoMergePinOnlyFixture(), map[string]any{"human_merge_pin_only": map[string]any{"org/b": autoMergePinOnlyArg([]any{"CODEOWNERS"}, []any{"any-line"}, []any{"renovate[bot]"})}}, `unknown kind "any-line"`}, + "unknown entry field": {autoMergePinOnlyFixture(), map[string]any{"human_merge_pin_only": map[string]any{"org/b": map[string]any{"enabled": true, "authors": []any{"x"}}}}, `not "authors"`}, + "enabled not given": {autoMergePinOnlyFixture(), map[string]any{"human_merge_pin_only": map[string]any{"org/b": map[string]any{"paths": []any{"CODEOWNERS"}}}}, "enabled must be true or false"}, + "remove what is not there": {autoMergePinOnlyFixture(), map[string]any{"human_merge_pin_only": map[string]any{"org/b": nil}}, "no entry for org/b to remove"}, + "same entry, other casing": {autoMergePinOnlyFixture(), map[string]any{"human_merge_pin_only": map[string]any{"ORG/A": autoMergePinOnlyArg([]any{".github/workflows/*.yml", "Containerfile"}, []any{"action-sha", "image-digest"}, []any{"renovate[bot]"})}}, "nothing would change"}, // A hive whose endpoint has no human_merge_pin_only field would drop // it silently, so it is refused rather than sent. - "hive that does not report it": {autoMergeFixture(), map[string]any{"human_merge_pin_only": map[string]any{"org/b": pinOnlyArg([]any{"CODEOWNERS"}, []any{"version-pin"}, []any{"dependabot[bot]"})}}, "may run an older build"}, + "hive that does not report it": {autoMergeFixture(), map[string]any{"human_merge_pin_only": map[string]any{"org/b": autoMergePinOnlyArg([]any{"CODEOWNERS"}, []any{"version-pin"}, []any{"dependabot[bot]"})}}, "may run an older build"}, } { t.Run(name, func(t *testing.T) { p := &autoMergeProvider{settings: tc.settings} @@ -145,10 +145,10 @@ func TestAutoMergeUpdatePinOnlyRefusals(t *testing.T) { } // Setting the human-merge paths in the same change makes it meaningful. - p := &autoMergeProvider{settings: pinOnlyFixture()} + p := &autoMergeProvider{settings: autoMergePinOnlyFixture()} preview, _ := autoMergePreview(t, autoMergeHandler(p), map[string]any{ "human_merge_paths": map[string]any{"org/c": []any{"Containerfile"}}, - "human_merge_pin_only": map[string]any{"org/c": pinOnlyArg([]any{"Containerfile"}, []any{"image-digest"}, []any{"renovate[bot]"})}, + "human_merge_pin_only": map[string]any{"org/c": autoMergePinOnlyArg([]any{"Containerfile"}, []any{"image-digest"}, []any{"renovate[bot]"})}, }) if !strings.Contains(preview.WideningDisclosure, "human_merge_pin_only[org/c] turned on") { t.Fatalf("disclosure = %s", preview.WideningDisclosure) diff --git a/src/pkg/dashboard/api_config_automerge.go b/src/pkg/dashboard/api_config_automerge.go index 3e06204b5c..b6cd5cb012 100644 --- a/src/pkg/dashboard/api_config_automerge.go +++ b/src/pkg/dashboard/api_config_automerge.go @@ -790,9 +790,9 @@ func (s *Server) autoMergeHumanMergePinOnly(in, current map[string]config.PinOnl seen[strings.ToLower(full)] = true policy := config.PinOnlyException{ Enabled: in[k].Enabled, - Paths: dedupeTrimmedStrings(in[k].Paths), - Kinds: dedupeTrimmedStrings(in[k].Kinds), - TrustedAuthors: dedupeTrimmedStrings(in[k].TrustedAuthors), + Paths: autoMergeDedupeStrings(in[k].Paths), + Kinds: autoMergeDedupeStrings(in[k].Kinds), + TrustedAuthors: autoMergeDedupeStrings(in[k].TrustedAuthors), } if !policy.Enabled && len(policy.Paths)+len(policy.Kinds)+len(policy.TrustedAuthors) == 0 { continue @@ -803,9 +803,9 @@ func (s *Server) autoMergeHumanMergePinOnly(in, current map[string]config.PinOnl return nil, err.Error() } guarded := config.AutoMergeConfig{HumanMergePaths: pathsAfter} - for _, repo := range sortedPinOnlyRepos(out) { + for _, repo := range autoMergePinOnlyRepos(out) { policy := out[repo] - if !policy.Enabled || pinOnlyUnchanged(current, repo, policy) { + if !policy.Enabled || autoMergePinOnlyUnchanged(current, repo, policy) { continue } if len(guarded.HumanMergePathsFor(repo)) == 0 { @@ -818,9 +818,9 @@ func (s *Server) autoMergeHumanMergePinOnly(in, current map[string]config.PinOnl return out, "" } -// pinOnlyUnchanged reports whether current already holds policy for repo, so +// autoMergePinOnlyUnchanged reports whether current already holds policy for repo, so // an entry the write sends back untouched is not re-checked. -func pinOnlyUnchanged(current map[string]config.PinOnlyException, repo string, policy config.PinOnlyException) bool { +func autoMergePinOnlyUnchanged(current map[string]config.PinOnlyException, repo string, policy config.PinOnlyException) bool { for k, was := range current { if strings.EqualFold(strings.TrimSpace(k), repo) { return was.Enabled == policy.Enabled && slices.Equal(was.Paths, policy.Paths) && @@ -830,7 +830,7 @@ func pinOnlyUnchanged(current map[string]config.PinOnlyException, repo string, p return false } -func sortedPinOnlyRepos(m map[string]config.PinOnlyException) []string { +func autoMergePinOnlyRepos(m map[string]config.PinOnlyException) []string { keys := make([]string, 0, len(m)) for k := range m { keys = append(keys, k) @@ -839,7 +839,7 @@ func sortedPinOnlyRepos(m map[string]config.PinOnlyException) []string { return keys } -func dedupeTrimmedStrings(list []string) []string { +func autoMergeDedupeStrings(list []string) []string { var out []string for _, v := range normalizeAutoMergeRepoList(list) { if !slices.Contains(out, v) { diff --git a/src/pkg/dashboard/api_config_automerge_pin_only_test.go b/src/pkg/dashboard/api_config_automerge_pin_only_test.go index e7290bf433..deb2c9eb6a 100644 --- a/src/pkg/dashboard/api_config_automerge_pin_only_test.go +++ b/src/pkg/dashboard/api_config_automerge_pin_only_test.go @@ -20,16 +20,16 @@ import ( // /api/config/auto-merge: the pin-only exception to human_merge_paths // (#16377) set from the dashboard instead of hive.yaml. -// pinOnlyServer is repoPolicyServer with human-merge paths on acme/api, the +// autoMergePinOnlyServer is repoPolicyServer with human-merge paths on acme/api, the // repository the exception is set for. -func pinOnlyServer(t *testing.T) *Server { +func autoMergePinOnlyServer(t *testing.T) *Server { t.Helper() s := repoPolicyServer(t) s.deps.Config.AutoMerge.HumanMergePaths = map[string][]string{"acme/api": {".github/workflows/**", "Containerfile"}} return s } -func pinOnlyEntry() map[string]any { +func autoMergePinOnlyEntryBody() map[string]any { return map[string]any{ "enabled": true, "paths": []string{" .github/workflows/*.yml ", "Containerfile", "Containerfile", ""}, @@ -39,9 +39,9 @@ func pinOnlyEntry() map[string]any { } func TestAutoMergePinOnly_PutGetRoundTrip(t *testing.T) { - s := pinOnlyServer(t) + s := autoMergePinOnlyServer(t) rec := doPut(s, "/api/config/auto-merge", map[string]any{ - "human_merge_pin_only": map[string]any{"api": pinOnlyEntry()}, + "human_merge_pin_only": map[string]any{"api": autoMergePinOnlyEntryBody()}, }) if rec.Code != http.StatusOK { t.Fatalf("valid put: expected 200, got %d: %s", rec.Code, rec.Body.String()) @@ -95,12 +95,12 @@ func TestAutoMergePinOnly_PutGetRoundTrip(t *testing.T) { } func TestAutoMergePinOnly_InvalidIsRefusedWithNoChange(t *testing.T) { - s := pinOnlyServer(t) - if rec := doPut(s, "/api/config/auto-merge", map[string]any{"human_merge_pin_only": map[string]any{"api": pinOnlyEntry()}}); rec.Code != http.StatusOK { + s := autoMergePinOnlyServer(t) + if rec := doPut(s, "/api/config/auto-merge", map[string]any{"human_merge_pin_only": map[string]any{"api": autoMergePinOnlyEntryBody()}}); rec.Code != http.StatusOK { t.Fatalf("seed put: %d %s", rec.Code, rec.Body.String()) } with := func(key string, value any) map[string]any { - e := pinOnlyEntry() + e := autoMergePinOnlyEntryBody() e[key] = value return e } @@ -109,15 +109,15 @@ func TestAutoMergePinOnly_InvalidIsRefusedWithNoChange(t *testing.T) { body map[string]any want string }{ - {"unknown repo", map[string]any{"human_merge_pin_only": map[string]any{"other/repo": pinOnlyEntry()}}, "human_merge_pin_only: other/repo is not in project.repos"}, - {"twice", map[string]any{"human_merge_pin_only": map[string]any{"api": pinOnlyEntry(), "ACME/api": pinOnlyEntry()}}, "names acme/api twice"}, + {"unknown repo", map[string]any{"human_merge_pin_only": map[string]any{"other/repo": autoMergePinOnlyEntryBody()}}, "human_merge_pin_only: other/repo is not in project.repos"}, + {"twice", map[string]any{"human_merge_pin_only": map[string]any{"api": autoMergePinOnlyEntryBody(), "ACME/api": autoMergePinOnlyEntryBody()}}, "names acme/api twice"}, {"no trusted authors", map[string]any{"human_merge_pin_only": map[string]any{"api": with("trusted_authors", []string{" "})}}, "enabled policy requires nonempty trusted_authors"}, {"no paths", map[string]any{"human_merge_pin_only": map[string]any{"api": with("paths", []string{})}}, "enabled policy requires nonempty paths"}, {"unknown kind", map[string]any{"human_merge_pin_only": map[string]any{"api": with("kinds", []string{"any-line"})}}, "unknown kind"}, {"unknown kind while disabled", map[string]any{"human_merge_pin_only": map[string]any{"api": map[string]any{"enabled": false, "kinds": []string{"any-line"}}}}, "unknown kind"}, // The exception only lifts a human-merge-path hold, so on a repository // with no such paths it would never apply. - {"no human-merge paths", map[string]any{"human_merge_pin_only": map[string]any{"api": pinOnlyEntry(), "web": pinOnlyEntry()}}, "acme/web has no human_merge_paths"}, + {"no human-merge paths", map[string]any{"human_merge_pin_only": map[string]any{"api": autoMergePinOnlyEntryBody(), "web": autoMergePinOnlyEntryBody()}}, "acme/web has no human_merge_paths"}, {"paths cleared in the same write", map[string]any{"human_merge_paths": map[string][]string{}, "human_merge_pin_only": map[string]any{"api": with("kinds", []string{"version-pin"})}}, "acme/api has no human_merge_paths"}, // A valid key alongside an invalid one must not half-apply. {"mixed", map[string]any{"max_merges": 7, "squash_only": []string{"api"}, "human_merge_pin_only": map[string]any{"api": with("kinds", []string{"nope"})}}, "unknown kind"}, @@ -141,13 +141,13 @@ func TestAutoMergePinOnly_InvalidIsRefusedWithNoChange(t *testing.T) { // back unchanged, so a full-map save from the dashboard still works on a hive // whose file carries an exception for a repository without human-merge paths. func TestAutoMergePinOnly_UnchangedEntryIsNotRechecked(t *testing.T) { - s := pinOnlyServer(t) + s := autoMergePinOnlyServer(t) s.deps.Config.AutoMerge.HumanMergePinOnly = map[string]config.PinOnlyException{ "acme/web": {Enabled: true, Paths: []string{"Containerfile"}, Kinds: []string{"image-digest"}, TrustedAuthors: []string{"renovate[bot]"}}, } rec := doPut(s, "/api/config/auto-merge", map[string]any{"human_merge_pin_only": map[string]any{ "acme/web": map[string]any{"enabled": true, "paths": []string{"Containerfile"}, "kinds": []string{"image-digest"}, "trusted_authors": []string{"renovate[bot]"}}, - "api": pinOnlyEntry(), + "api": autoMergePinOnlyEntryBody(), }}) if rec.Code != http.StatusOK { t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body.String()) @@ -158,7 +158,7 @@ func TestAutoMergePinOnly_UnchangedEntryIsNotRechecked(t *testing.T) { } func TestAutoMergePinOnly_NonOwnerIsForbidden(t *testing.T) { - s := pinOnlyServer(t) + s := autoMergePinOnlyServer(t) for _, tc := range []struct { name string role string @@ -168,7 +168,7 @@ func TestAutoMergePinOnly_NonOwnerIsForbidden(t *testing.T) { {"unverified owner", "owner", false}, {"no role", "", false}, } { - body, _ := json.Marshal(map[string]any{"human_merge_pin_only": map[string]any{"api": pinOnlyEntry()}}) + body, _ := json.Marshal(map[string]any{"human_merge_pin_only": map[string]any{"api": autoMergePinOnlyEntryBody()}}) for _, method := range []string{http.MethodPut, http.MethodPatch} { req := httptest.NewRequest(method, "/api/config/auto-merge", bytes.NewReader(body)) req.Header.Set("Content-Type", "application/json") @@ -195,12 +195,12 @@ func TestAutoMergePinOnly_NonOwnerIsForbidden(t *testing.T) { // relay holds a copy the write must refresh. Both see a write at once, with // no restart, and both lose it when it is cleared. func TestAutoMergePinOnly_ReachesRunningHiveWithoutRestart(t *testing.T) { - s := pinOnlyServer(t) + s := autoMergePinOnlyServer(t) client := ghpkg.NewClientForTest("http://127.0.0.1:1", "acme", []string{"api"}, covBLogger()) s.deps.GHClient = client live := s.deps.Config // the pointer the sweeps were built with - if rec := doPut(s, "/api/config/auto-merge", map[string]any{"human_merge_pin_only": map[string]any{"api": pinOnlyEntry()}}); rec.Code != http.StatusOK { + if rec := doPut(s, "/api/config/auto-merge", map[string]any{"human_merge_pin_only": map[string]any{"api": autoMergePinOnlyEntryBody()}}); rec.Code != http.StatusOK { t.Fatalf("put: %d %s", rec.Code, rec.Body.String()) } if policy, ok := live.AutoMerge.HumanMergePinOnlyFor("acme/api"); !ok || strings.Join(policy.TrustedAuthors, ",") != "renovate[bot]" { @@ -224,9 +224,9 @@ func TestAutoMergePinOnly_ReachesRunningHiveWithoutRestart(t *testing.T) { } func TestAutoMergePinOnly_PersistsToSavedConfig(t *testing.T) { - s := pinOnlyServer(t) + s := autoMergePinOnlyServer(t) s.deps.Config.SourcePath = filepath.Join(t.TempDir(), "hive.yaml") - if rec := doPut(s, "/api/config/auto-merge", map[string]any{"human_merge_pin_only": map[string]any{"api": pinOnlyEntry()}}); rec.Code != http.StatusOK { + if rec := doPut(s, "/api/config/auto-merge", map[string]any{"human_merge_pin_only": map[string]any{"api": autoMergePinOnlyEntryBody()}}); rec.Code != http.StatusOK { t.Fatalf("put: %d %s", rec.Code, rec.Body.String()) } data, err := os.ReadFile(s.deps.Config.SourcePath)