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 03e69c8c2a..4767856175 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 e640ddd7fa..9d92dca7f9 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. | @@ -562,11 +562,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`. @@ -604,14 +604,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..63444a6925 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 := autoMergePinOnlyValue(c.before) + after, _ := c.after.(map[string]autoMergePinOnlyEntry) + var rows []amRow + for _, repo := range autoMergePinOnlyKeys(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 := autoMergeCheckPinOnlyGuarded(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 autoMergeApplyPinOnly(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 } +// 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 autoMergePinOnlyEntry struct { + Enabled bool `json:"enabled"` + Kinds []string `json:"kinds"` + Paths []string `json:"paths"` + TrustedAuthors []string `json:"trusted_authors"` +} + +// 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] = autoMergePinOnlyEntry{ + Enabled: enabled, + Kinds: nilAsEmpty(stringListValueLoose(e["kinds"])), + Paths: nilAsEmpty(stringListValueLoose(e["paths"])), + TrustedAuthors: nilAsEmpty(stringListValueLoose(e["trusted_authors"])), + } + } + case map[string]autoMergePinOnlyEntry: + for repo, e := range m { + out[repo] = e + } + } + return out +} + +func autoMergePinOnlyKeys(a, b map[string]autoMergePinOnlyEntry) []string { + keys := map[string]any{} + for k := range a { + keys[k] = nil + } + for k := range b { + keys[k] = nil + } + return SortKeys(keys) +} + +// 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 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 := autoMergePinOnlyValue(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 := autoMergePinOnlyEntryArg(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 +} + +// 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 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 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 autoMergePinOnlyEntry{}, fmt.Errorf("human_merge_pin_only[%s].enabled must be true or false", repo) + } + 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 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 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) + } + } + *f.dst = vals + } + return entry, nil +} + +// 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 autoMergeCheckPinOnlyGuarded(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 := 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 + } + 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 +} + +// 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 autoMergePinOnlyWidening(before, after any) []string { + was := autoMergePinOnlyValue(before) + now := autoMergePinOnlyValue(after) + var notes []string + for _, repo := range autoMergePinOnlyKeys(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 autoMergePinOnlyWidening(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..94845ba960 --- /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. + +// autoMergePinOnlyFixture is autoMergeFixture on a hive that reports +// human_merge_pin_only, with an exception already set for org/a. +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]"}}, + } + return f +} + +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: autoMergePinOnlyFixture()} + h := autoMergeHandler(p) + preview, id := autoMergePreview(t, h, map[string]any{ + "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]"]},` + + `"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": 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 { + args map[string]any + widen bool + names string + }{ + "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"}, + "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: 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) + } + 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: autoMergePinOnlyFixture()} + h := autoMergeHandler(p) + _, id := autoMergePreview(t, h, map[string]any{ + "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) { + 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": {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": 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} + 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: 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": 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/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 30cd6fff02..5a9da70eec 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"` @@ -248,6 +252,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 { @@ -375,6 +394,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 @@ -445,7 +467,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) @@ -492,6 +516,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 != "" { @@ -531,6 +562,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, @@ -659,6 +692,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()) } @@ -737,6 +780,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: 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 + } + out[full] = policy + } + if err := (config.AutoMergeConfig{HumanMergePinOnly: out}).ValidateHumanMergePinOnly(); err != nil { + return nil, err.Error() + } + guarded := config.AutoMergeConfig{HumanMergePaths: pathsAfter} + for _, repo := range autoMergePinOnlyRepos(out) { + policy := out[repo] + if !policy.Enabled || autoMergePinOnlyUnchanged(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, "" +} + +// autoMergePinOnlyUnchanged reports whether current already holds policy for repo, so +// an entry the write sends back untouched is not re-checked. +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) && + slices.Equal(was.Kinds, policy.Kinds) && slices.Equal(was.TrustedAuthors, policy.TrustedAuthors) + } + } + return false +} + +func autoMergePinOnlyRepos(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 autoMergeDedupeStrings(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..deb2c9eb6a --- /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. + +// autoMergePinOnlyServer is repoPolicyServer with human-merge paths on acme/api, the +// repository the exception is set for. +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 autoMergePinOnlyEntryBody() 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 := autoMergePinOnlyServer(t) + rec := doPut(s, "/api/config/auto-merge", map[string]any{ + "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()) + } + // 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 := 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 := autoMergePinOnlyEntryBody() + 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": 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": 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"}, + } { + 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 := 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": autoMergePinOnlyEntryBody(), + }}) + 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 := autoMergePinOnlyServer(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": 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") + 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 := 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": 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]" { + 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 := 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": autoMergePinOnlyEntryBody()}}); 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 b568f4421f..901432fd52 100644 --- a/src/pkg/dashboard/static-src/js/config-features.js +++ b/src/pkg/dashboard/static-src/js/config-features.js @@ -425,6 +425,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) => `
@@ -562,7 +575,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 2c55343a89..34c011b28d 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 a4e2d13c01..88c292f58b 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; } @@ -66875,6 +66877,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) => `
@@ -67012,7 +67027,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[]')}.

@@ -70235,6 +70260,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{}