Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/added-pin-only-human-merge-config.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- Add validated per-repository `auto_merge.human_merge_pin_only` schema, changed-file patch evidence and a fail-closed pin-replacement syntax classifier as building blocks for #16242; merge-path exceptions are not yet enabled and existing human-merge protections remain unchanged.
50 changes: 50 additions & 0 deletions src/docs/hive-merge.md
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,56 @@ sweep lanes whatever the intent tier. If the changed-file list for a configured
repo cannot be fetched completely, the merge is withheld (fail closed). See
[operator-reference.md](operator-reference.md).

**Staged pin-only policy (not yet enforced).**

`auto_merge.human_merge_pin_only` provides the schema and conservative diff
classifier for #16242 / #16262. **It does not currently enable an exception:**
relay, sweep, `/approve` and native-queue gates still require the existing
human-merge path policy. Do not remove `human_merge_paths` or manually clear a
hold to simulate this feature.

```yaml
auto_merge:
human_merge_paths:
owner/repo: [".github/workflows/*.yml", "Containerfile"]
human_merge_pin_only:
owner/repo:
enabled: true
paths: [".github/workflows/*.yml", "Containerfile"]
kinds: [action-sha, image-digest, version-pin]
trusted_authors: [maintainer-login]
```

Repository keys are case-insensitive; duplicate normalized keys are rejected.
Absent/disabled entries have no effect. Enabled entries require nonempty paths,
kinds and trusted authors; unknown kinds are rejected, including when disabled.
The classifier accepts only existing modified files in both the actual guarded
path matches and exception paths, and checks **all** files in the PR. Every
changed line must be a paired pin replacement. Supported forms are unquoted
`uses: owner/repo[/path]@<40-hex>` (an existing simple `# vN[.N[.N]]`
comment may change), `FROM image@sha256:<64-hex>` / `image: image@sha256:...`,
and literal `version: 1.2.3` / `ARG TOOL_VERSION=1.2.3` updates. Other syntax,
missing patches, line-count mismatches, added/renamed files, owner files,
permission/credential/signing text and non-pin edits fail closed.

This classifier proves **syntax only**, not authenticated identity, exact-head
binding, file-list completeness, semantic interpretation or review of upstream
references. Those proofs must be added by the integration children (#16265,
#16266); attribution and safe hold release are tracked in #16269. None of the
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. The existing config-file watcher reloads the seed with the
dashboard overlay via `LoadWithDashboardOverlay`; invalid configuration is not
installed. Reloading this schema alone still does **not** enable admission. The
integration PRs must wire live policy updates into every merge path.

There is **no minimum deployable version enabling this lane yet**. Utah rollout
and current-head positive/negative deployment evidence remain tracked by
projectbluefin/utah#1082 and #16242; projectbluefin/utah#1068 is not pre-authorized.

**Contributor PRs are held to the contributor-lane policy.** A merge request
for a PR whose author is not the hive App, a configured trusted bot, or a
trusted-author role is evaluated against the same `auto_merge.contributor_lane`
Expand Down
1 change: 1 addition & 0 deletions src/docs/operator-reference/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,7 @@ Go callers keep reading `cfg.Agents`, `cfg.Governor.Gateways` and so on through
| `project.label_driven_supersede_park_actors` | `[]` (off) | Automation logins (for example a lifecycle bot running as `github-actions[bot]`) whose park labels a later trusted acceptance supersedes on label-driven repos: Hive removes the label, says so in the release comment, and releases the issue ([#13605](https://github.com/hivecommons/hive/issues/13605)). Park labels added by people, by unlisted bots, or by a listed bot after the acceptance still block; `hold` is never superseded. Per-repo override: `project.repo_policies[].label_driven_supersede_park_actors`. |
| `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); **not yet enforced**. | Staged per-repo schema for `enabled`, `paths`, `kinds` (`action-sha`, `image-digest`, `version-pin`) and `trusted_authors`. Enabled entries require all three lists. Provides syntax-classification building blocks only: no merge route grants an exception or clears a hold. 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. |
Expand Down
90 changes: 90 additions & 0 deletions src/pkg/config/automerge_pin_only.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
package config

import (
"fmt"
"strings"

"github.com/hivecommons/hive/pkg/intent"
)

// PinOnlyException is staged policy, not authorization to merge. The eventual
// admission gates must supply authenticated identity, exact-head diff and review
// evidence before consulting the purely syntactic classifier.
type PinOnlyException struct {
Enabled bool `yaml:"enabled" json:"enabled"`
Paths []string `yaml:"paths" json:"paths"`
Kinds []string `yaml:"kinds" json:"kinds"`
TrustedAuthors []string `yaml:"trusted_authors" json:"trusted_authors"`
}

func (p PinOnlyException) validate() error {
for _, kind := range p.Kinds {
switch kind {
case "action-sha", "image-digest", "version-pin":
default:
return fmt.Errorf("unknown kind %q", kind)
}
}
if !p.Enabled {
return nil
}
for name, values := range map[string][]string{"paths": p.Paths, "kinds": p.Kinds, "trusted_authors": p.TrustedAuthors} {
if len(values) == 0 {
return fmt.Errorf("enabled policy requires nonempty %s", name)
}
for _, value := range values {
if strings.TrimSpace(value) == "" {
return fmt.Errorf("%s contains an empty value", name)
}
}
}
return nil
}

// Spec returns classifier input only; it deliberately contains no merge grant.
func (p PinOnlyException) Spec() intent.PinOnlySpec {
return intent.PinOnlySpec{Paths: append([]string(nil), p.Paths...), Kinds: append([]string(nil), p.Kinds...)}
}

// ValidateHumanMergePinOnly rejects ambiguous repository keys and invalid policy.
// Paths are checked against actual human-merge matches by the classifier, rather
// than attempting to infer containment between arbitrary glob languages.
func (a AutoMergeConfig) ValidateHumanMergePinOnly() error {
seen := make(map[string]bool)
for repo, policy := range a.HumanMergePinOnly {
key := strings.ToLower(strings.TrimSpace(repo))
parts := strings.Split(key, "/")
if len(parts) != 2 || parts[0] == "" || parts[1] == "" || strings.ContainsAny(key, " \t\n\r*") || seen[key] {
return fmt.Errorf("auto_merge.human_merge_pin_only: invalid or duplicate repository %q", repo)
}
seen[key] = true
if err := policy.validate(); err != nil {
return fmt.Errorf("auto_merge.human_merge_pin_only[%s]: %w", repo, err)
}
}
return nil
}

// HumanMergePinOnlyFor returns a defensive copy of an enabled, valid policy.
// Ambiguous case-insensitive keys fail closed even before config validation.
func (a AutoMergeConfig) HumanMergePinOnlyFor(repo string) (PinOnlyException, bool) {
var result PinOnlyException
found := false
for key, policy := range a.HumanMergePinOnly {
if !strings.EqualFold(strings.TrimSpace(key), strings.TrimSpace(repo)) {
continue
}
if found {
return PinOnlyException{}, false
}
found = true
result = policy
}
if !found || !result.Enabled || result.validate() != nil {
return PinOnlyException{}, false
}
result.Paths = append([]string(nil), result.Paths...)
result.Kinds = append([]string(nil), result.Kinds...)
result.TrustedAuthors = append([]string(nil), result.TrustedAuthors...)
return result, true
}
88 changes: 88 additions & 0 deletions src/pkg/config/automerge_pin_only_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
package config

import (
"testing"

"gopkg.in/yaml.v3"
)

func TestHumanMergePinOnlyConfig(t *testing.T) {
var cfg Config
if err := yaml.Unmarshal([]byte(`auto_merge:
human_merge_pin_only:
Owner/Repo:
enabled: true
paths: [".github/workflows/*.yml"]
kinds: [action-sha]
trusted_authors: [maintainer]
`), &cfg); err != nil {
t.Fatal(err)
}
if err := cfg.AutoMerge.ValidateHumanMergePinOnly(); err != nil {
t.Fatal(err)
}
policy, ok := cfg.AutoMerge.HumanMergePinOnlyFor(" owner/REPO ")
if !ok || len(policy.Spec().Paths) != 1 || policy.TrustedAuthors[0] != "maintainer" {
t.Fatalf("policy = %+v, %v", policy, ok)
}
policy.Paths[0] = "*"
policy.Kinds[0] = "anything"
policy.TrustedAuthors[0] = "attacker"
again, _ := cfg.AutoMerge.HumanMergePinOnlyFor("owner/repo")
if again.Paths[0] == "*" || again.Kinds[0] != "action-sha" || again.TrustedAuthors[0] != "maintainer" {
t.Fatal("accessor leaked config slices")
}
if _, ok := cfg.AutoMerge.HumanMergePinOnlyFor("other/repo"); ok {
t.Fatal("unknown repo enabled")
}
if _, ok := (AutoMergeConfig{}).HumanMergePinOnlyFor("owner/repo"); ok {
t.Fatal("absent config enabled")
}
}

func TestHumanMergePinOnlyInvalidConfig(t *testing.T) {
valid := func() PinOnlyException {
return PinOnlyException{Enabled: true, Paths: []string{"Containerfile"}, Kinds: []string{"image-digest"}, TrustedAuthors: []string{"maintainer"}}
}
for _, tc := range []struct {
name string
change func(*PinOnlyException)
valid bool
}{
{"valid", func(_ *PinOnlyException) {}, true},
{"disabled", func(p *PinOnlyException) { *p = PinOnlyException{} }, true},
{"no paths", func(p *PinOnlyException) { p.Paths = nil }, false},
{"no kinds", func(p *PinOnlyException) { p.Kinds = nil }, false},
{"no authors", func(p *PinOnlyException) { p.TrustedAuthors = nil }, false},
{"blank author", func(p *PinOnlyException) { p.TrustedAuthors = []string{" "} }, false},
{"blank path", func(p *PinOnlyException) { p.Paths = []string{""} }, false},
{"unknown kind", func(p *PinOnlyException) { p.Kinds = []string{"sha-shaped-text"} }, false},
{"disabled unknown kind", func(p *PinOnlyException) { p.Enabled = false; p.Kinds = []string{"anything"} }, false},
} {
t.Run(tc.name, func(t *testing.T) {
p := valid()
tc.change(&p)
a := AutoMergeConfig{HumanMergePinOnly: map[string]PinOnlyException{"o/r": p}}
if err := a.ValidateHumanMergePinOnly(); (err == nil) != tc.valid {
t.Fatalf("validation = %v", err)
}
_, ok := a.HumanMergePinOnlyFor("O/R")
if ok != (tc.valid && p.Enabled) {
t.Fatalf("accessor enabled = %v", ok)
}
})
}
for _, key := range []string{"", "owner", "o/", "/r", "o/r/extra", "o /r", "*/r"} {
a := AutoMergeConfig{HumanMergePinOnly: map[string]PinOnlyException{key: valid()}}
if err := a.ValidateHumanMergePinOnly(); err == nil {
t.Errorf("accepted invalid key %q", key)
}
}
a := AutoMergeConfig{HumanMergePinOnly: map[string]PinOnlyException{"o/r": valid(), "O/R": valid()}}
if err := a.ValidateHumanMergePinOnly(); err == nil {
t.Fatal("accepted duplicate key")
}
if _, ok := a.HumanMergePinOnlyFor("o/r"); ok {
t.Fatal("ambiguous policy enabled")
}
}
4 changes: 4 additions & 0 deletions src/pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -8336,6 +8336,10 @@ type AutoMergeConfig struct {
// means no such paths. This key only declares the paths; enforcement
// lives in the merge sweeps.
HumanMergePaths map[string][]string `yaml:"human_merge_paths,omitempty" json:"human_merge_paths,omitempty"`

// HumanMergePinOnly stages opt-in pin-only policy. Admission wiring must
// independently prove trusted identity, exact-head evidence and upstream review.
HumanMergePinOnly map[string]PinOnlyException `yaml:"human_merge_pin_only,omitempty" json:"human_merge_pin_only,omitempty"`
// HumanMergeTitlePrefixes lists title prefixes (matched after trimming
// the title) that mark a PR as one the owner merges by hand; no lane and
// no merge train merges it (hivecommons/hive#15442). Unset means the
Expand Down
3 changes: 3 additions & 0 deletions src/pkg/config/validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,9 @@ func (c *Config) ValidateWithOptions(opts ValidateOptions) error {
if err := c.validateSpektacularRecheckDiscovery(); err != nil {
return err
}
if err := c.AutoMerge.ValidateHumanMergePinOnly(); err != nil {
return err
}
if err := c.AutoMerge.TrustedAuthors.Validate(); err != nil {
return err
}
Expand Down
4 changes: 2 additions & 2 deletions src/pkg/github/automerge/automerge_intent_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,7 @@ func TestListChangedFilesPagesThroughFilesAPI(t *testing.T) {
switch r.URL.Query().Get("page") {
case "":
w.Header().Set("Link", `<`+base+`/repos/acme/widget/pulls/7/files?page=2>; rel="next"`)
json.NewEncoder(w).Encode([]map[string]any{{"filename": testIntentSourceFile, "status": "modified", "additions": 1, "deletions": 2}})
json.NewEncoder(w).Encode([]map[string]any{{"filename": testIntentSourceFile, "status": "modified", "additions": 1, "deletions": 2, "patch": "@@ -1,2 +1 @@\n-old\n-old2\n+new"}})
case "2":
json.NewEncoder(w).Encode([]map[string]any{{"filename": testIntentDocsFile, "status": "added", "additions": 3, "deletions": 0}})
default:
Expand All @@ -329,7 +329,7 @@ func TestListChangedFilesPagesThroughFilesAPI(t *testing.T) {
t.Fatalf("ListChangedFiles() error = %v, want nil for a complete two-page list", err)
}
want := []intent.ChangedFile{
{Filename: testIntentSourceFile, Status: "modified", Additions: 1, Deletions: 2},
{Filename: testIntentSourceFile, Status: "modified", Additions: 1, Deletions: 2, Patch: "@@ -1,2 +1 @@\n-old\n-old2\n+new"},
{Filename: testIntentDocsFile, Status: "added", Additions: 3, Deletions: 0},
}
if !reflect.DeepEqual(files, want) {
Expand Down
1 change: 1 addition & 0 deletions src/pkg/github/human_merge_paths.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ func ListPRChangedFiles(ctx context.Context, client *gh.Client, owner, repo stri
Status: f.GetStatus(),
Additions: f.GetAdditions(),
Deletions: f.GetDeletions(),
Patch: f.GetPatch(),
})
}
if resp == nil || resp.NextPage == 0 {
Expand Down
50 changes: 50 additions & 0 deletions src/pkg/github/pin_only_files_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package github

import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"

gh "github.com/google/go-github/v72/github"
"github.com/hivecommons/hive/pkg/intent"
)

func TestPinOnlyChangedFileEvidence(t *testing.T) {
patch := "@@ -1 +1 @@\n-FROM image@sha256:" + strings.Repeat("a", 64) + "\n+FROM image@sha256:" + strings.Repeat("b", 64)
for _, present := range []bool{true, false} {
t.Run(map[bool]string{true: "patch present", false: "patch omitted"}[present], func(t *testing.T) {
api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/repos/o/r/pulls/1/files" {
http.NotFound(w, r)
return
}
file := map[string]any{"filename": "Containerfile", "status": "modified", "additions": 1, "deletions": 1}
if present {
file["patch"] = patch
}
_ = json.NewEncoder(w).Encode([]map[string]any{file})
}))
defer api.Close()
client := gh.NewClient(api.Client())
client.BaseURL, _ = url.Parse(api.URL + "/")
pr := &gh.PullRequest{Number: gh.Ptr(1), ChangedFiles: gh.Ptr(1)}
files, err := ListPRChangedFiles(context.Background(), client, "o", "r", pr)
if err != nil {
t.Fatal(err)
}
ok, why := intent.ClassifyPinOnly(files, []string{"Containerfile"}, intent.PinOnlySpec{Paths: []string{"Containerfile"}, Kinds: []string{"image-digest"}})
if ok != present {
t.Fatalf("classification = %v, %s", ok, why)
}
pr.ChangedFiles = gh.Ptr(2)
if _, err := ListPRChangedFiles(context.Background(), client, "o", "r", pr); !errors.Is(err, ErrIncompletePRFileList) {
t.Fatalf("incomplete list: %v", err)
}
})
}
}
10 changes: 8 additions & 2 deletions src/pkg/intent/alignment.go
Original file line number Diff line number Diff line change
Expand Up @@ -274,15 +274,21 @@ func boundedFiles(files []ChangedFile) ([]DiffFileSummary, int) {
}
out := make([]DiffFileSummary, 0, limit)
for _, f := range files[:limit] {
out = append(out, DiffFileSummary(f))
out = append(out, DiffFileSummary{
Filename: f.Filename, Status: f.Status,
Additions: f.Additions, Deletions: f.Deletions,
})
}
return out, len(files) - limit
}

func allFiles(files []ChangedFile) []DiffFileSummary {
out := make([]DiffFileSummary, 0, len(files))
for _, f := range files {
out = append(out, DiffFileSummary(f))
out = append(out, DiffFileSummary{
Filename: f.Filename, Status: f.Status,
Additions: f.Additions, Deletions: f.Deletions,
})
}
return out
}
Expand Down
Loading
Loading