From 175fe6b25e42a0ff530f6489b710892e0e43e5db Mon Sep 17 00:00:00 2001 From: thatguywob Date: Thu, 5 Nov 2026 00:43:40 +0000 Subject: [PATCH 1/3] =?UTF-8?q?=E2=9C=A8=20feat(settings):=20expose=20merg?= =?UTF-8?q?e-train=20controls=20in=20Auto-merge?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Expose nested merge-train controls with owner-only partial API updates and persistence-aware explicit-zero stall warnings. Hive-Run: hivecommons/hive#16677 Hive-Plan: merge-train-settings Hive-Spec: hivecommons/hive#16677#proposed Signed-off-by: thatguywob Co-authored-by: clubanderson <407614+clubanderson@users.noreply.github.com> --- .../added-16677-merge-train-settings.md | 1 + src/docs/dashboard-copy-inventory.md | 13 ++ src/docs/operator-reference/README.md | 6 +- src/pkg/config/config.go | 33 +++- src/pkg/config/merge_train_settings_test.go | 59 ++++++ src/pkg/dashboard/api.go | 2 + src/pkg/dashboard/api_config_automerge.go | 25 ++- src/pkg/dashboard/api_governor.go | 1 + src/pkg/dashboard/api_governor_merge_train.go | 42 +++++ src/pkg/dashboard/audit.go | 1 + .../dashboard/merge_train_settings_test.go | 176 ++++++++++++++++++ .../dashboard/settings_parity_allowlist.txt | 2 - .../static-src/js/config-features.js | 68 ++++--- .../dashboard/static-src/js/config-helpers.js | 10 + .../dashboard/static-src/js/config-state.js | 1 + .../static-src/js/linear-repos-save.js | 6 + src/pkg/dashboard/static/index.html | 85 ++++++--- 17 files changed, 463 insertions(+), 68 deletions(-) create mode 100644 changelog.d/added-16677-merge-train-settings.md create mode 100644 src/pkg/config/merge_train_settings_test.go create mode 100644 src/pkg/dashboard/api_governor_merge_train.go create mode 100644 src/pkg/dashboard/merge_train_settings_test.go diff --git a/changelog.d/added-16677-merge-train-settings.md b/changelog.d/added-16677-merge-train-settings.md new file mode 100644 index 0000000000..9166f81fd3 --- /dev/null +++ b/changelog.d/added-16677-merge-train-settings.md @@ -0,0 +1 @@ +- Expose conflict-aware merge train, rebase-attempt and stall-warning controls under Settings → Auto-merge → Merge train, including disabling stall warnings with zero seconds ([#16677](https://github.com/hivecommons/hive/issues/16677)). diff --git a/src/docs/dashboard-copy-inventory.md b/src/docs/dashboard-copy-inventory.md index b80df3e804..c37c0538c1 100644 --- a/src/docs/dashboard-copy-inventory.md +++ b/src/docs/dashboard-copy-inventory.md @@ -73,6 +73,19 @@ The new hover, verbatim (title line omitted): | `stageTrackerSelectionTriage` (`tracker-actions.js`) | selection bar lead button / bulk ⋯ menu entry, summary toast | — (no bulk Accept triage; one row at a time) | *Accept triage (4 selected)* / *Accept triage (2 of 4)* with the hint *skips the 2 not waiting on triage*; one toast *Accepted 4 issues* | `TestStageTrackerBulkAcceptTriage` | | Settings → Features → Auto-merge → "Merge only on current base" help (`renderGovFeatures`, `config-features.js`) and the Repos-tab override row / repo-card `current-base` chip ([#15335](https://github.com/hivecommons/hive/issues/15335)) | settingHelpMark popover, checkbox label, chip hover | — (new) | 56 (help), 5 (row label), 1 (chip) | `TestCurrentBaseSettingsMarkupNodeGuard` | + +## Merge train settings (hivecommons/hive#16677) + +These controls appear in **Settings → Auto-merge → Merge train**, immediately above Native GitHub merge queue (`renderGovFeatures`, `config-features.js`). Each label includes its YAML hint and a help popover. + +| Label | YAML key | Help text | +|---|---|---| +| Conflict-aware merge train | `auto_merge.merge_train.enabled` | Default on. Runs one front per overlap group so PRs changing the same files merge in order. False restores independent per-PR evaluation. | +| Rebase attempts per front | `auto_merge.merge_train.max_rebase_attempts` | How many rebase-resolve requests one PR may make behind one front before it parks at stage/085 for a human decision. Default 2; 0 uses that default. | +| Stall warning after | `governor.merge_train_stall_warn_s` | Seconds without progress before the Activity Monitor chip reads "Merge queue · stalled". Default 3600 seconds; 0 disables the warning. | + +`TestMergeTrainSettingsMarkup` holds the labels, help popovers, YAML hints and placement; `TestMergeTrainSettingsPatchRoundTrip` holds the saved values and audit actions. + ## Totals | | Before | After | diff --git a/src/docs/operator-reference/README.md b/src/docs/operator-reference/README.md index 2757cd42a3..74a5c7d1b1 100644 --- a/src/docs/operator-reference/README.md +++ b/src/docs/operator-reference/README.md @@ -272,7 +272,7 @@ Go callers keep reading `cfg.Agents`, `cfg.Governor.Gateways` and so on through | `review.reviewers.autoscale.*` | `enabled: false`; when on: `min: 1`, `max: 4` (≤ the replicas cap 5), `target_backlog_per_reviewer: 2`, `scale_up_cycles: 2`, `scale_down_cycles: 5`, `cooldown: 5m`, `cpu_per_reviewer: 1.0`, `mem_per_reviewer_mb: 2048`, `agent` unset (first `role: reviewer` agent, else `reviewer_agents[0]`); owner-only. | Sizes the reviewer lane to its backlog ([#14685](https://github.com/hivecommons/hive/issues/14685)): adds a `reviewer-N` replica after `scale_up_cycles` cycles with more PRs waiting for a free reviewer than `target_backlog_per_reviewer` per reviewer (or a wait older than the review-pending stage dwell), drains the top replica after `scale_down_cycles` idle cycles and retires it only when its turn ends. Scale-ups are refused by named guards (`at-max`, `cooldown`, `saturated` kicks, `provider-budget`, `provider-headroom`, `max-parallel-reviews`, cgroup `cpu` / `memory`). Decisions log as `reviewer autoscale: 2→3 reason=…`; state is in `/api/status.reviewerAutoscale`. See [review-swarm.md](../review-swarm.md#reviewer-autoscale-reviewreviewersautoscale). | | `review.contributor_prs.base_sync` | Off by default; owner-only. | Lets PR follow-up use GitHub's update-branch API on hive-authored lane PRs whose head is in a contributor fork, whose `mergeable_state` is `behind`/`dirty`, and whose author enabled "allow edits by maintainers". `behind` PRs get a GitHub-authored merge commit; `dirty`/422 falls back to the `hive-base-moved` repair note and kick. This requires an agent/proxy mode with `ISSUES_PRS_MERGE` because `PUT /pulls/{n}/update-branch` is merge-scoped. It does not rewrite history and does not add a human/bot-authored DCO commit; the repository's "Sign-off survives the squash" check examines the PR's own commits, not GitHub's update-branch merge commit. | | `governor.advisory.post_retry_backoff_s` | `3600` seconds. `HIVE_ADVISORY_POST_RETRY_BACKOFF_S` overrides the default when the key is unset; a negative value disables the pause. | How long the advisory digest write is paused after GitHub refuses it with `403 Resource not accessible by integration`. That refusal is structural (foreign-authored comment, repo dropped from the installation, or repo transferred to another owner), so per-cycle retries only burn API quota. The failed edit first falls back to creating a fresh App-authored comment; if the create is refused too, the error is recorded for the hub health row — naming the new `owner/repo` when the repository has moved — and attempts pause for this window. See [advisory.md](../advisory.md#when-the-write-is-refused). | -| `governor.merge_train_stall_warn_s` | `3600` seconds; `0` disables | How long the head of a merge train may sit in one stage before the Activity Monitor reads the train **stalled** — the queued chip turns to "Merge queue · stalled — waiting on #15253 (waiting for CI) · 3h", the Merge queue popover marks the train, and the activity log records one `merge train stalled` line per train per hour naming the head, its state and how long. A soaking head is on its clock, not stalled, until that clock itself overruns the window ([#15395](https://github.com/hivecommons/hive/issues/15395)). | +| `governor.merge_train_stall_warn_s` | `3600` seconds; `0` disables | **Settings → Auto-merge → Merge train → Stall warning after.** How long the head of a merge train may sit in one stage before the Activity Monitor reads the train **stalled** — the queued chip turns to "Merge queue · stalled — waiting on #15253 (waiting for CI) · 3h", the Merge queue popover marks the train, and the activity log records one `merge train stalled` line per train per hour naming the head, its state and how long. A soaking head is on its clock, not stalled, until that clock itself overruns the window ([#15395](https://github.com/hivecommons/hive/issues/15395)). | | `governor.trajectory.enabled` | Defaults to enabled. | The lane no-ops until a reviewer endpoint and model resolve from `governor.trajectory` or `governor.litellm`. | | `governor.kick_limits.max_issues` / `max_prs` | `100` / `50` | Caps on every issue list and every PR list (actionable, stale drafts, merge-eligible, CI-failing) rendered into a kick prompt; a cut list ends with an explicit "… and N more" line. An absent key or a negative value means the default; an explicit `0` opts out of the cap entirely (`KickListUnlimited` — every item is listed), and anything above `500` is pinned to `500`. Editable without touching this file under **Settings → Repos → Kick prompt list caps**. Truncation drops the *newest, lowest-priority* items: issues are listed oldest first, and PRs in review-priority order (fixes, then refactors/docs, then tests, oldest first within each class), so lowering a cap never hides the most urgent work. Raise `max_prs` only if your agents actually work more than 50 PRs per turn; the tail of a long list costs tokens and delivery time on every kick without changing behaviour (#7368). | | `project.agents_md_max_bytes` | `8192`; values under `2048` are raised to `2048`. | Caps the repo `AGENTS.md` block prepended to a kick. Whole sections (split at `#`/`##` headings; each resolved skill is its own unit) are kept or dropped, never clipped mid-rule; when any are dropped the kick carries a one-line `⚠️ AGENTS.md exceeded N bytes; … — read AGENTS.md …` warning naming them and the scheduler logs it. See [agents-md.md](../agents-md.md#size-cap-whole-sections-visible-warning). | @@ -464,8 +464,8 @@ advanced into the merge path. | `auto_merge.require_current_base_default` | `false` | Hive-wide default of the current-base gate for repos in neither `require_current_base` nor `skip_current_base` (Settings → Features → Auto-merge → "Merge only on current base"). **Off** by default: the merge train already update-branches overlapping siblings, so the gate is being soaked per repo (hive's own hive first, via `require_current_base`) before any hive turns it on everywhere. When `true`, a behind head the App cannot update merges as it was tested, with one WARN per PR (`automerge current-base gate: … merging as tested`), so fork-heavy repos are not parked wholesale. | | `auto_merge.skip_current_base` | unset | Repo list (`owner/repo`) with an explicit **off** override for the current-base gate (Settings → Repos → "Merge only on current base" unchecked): a green head there merges even if the base has moved, whatever `require_current_base_default` says. An explicit `require_current_base` entry wins over this list. | | `auto_merge.merge_forward_trusted_human` | unset (off) | Repo list (`owner/repo`) where a `role/trusted` + `author/human` PR on a same-repo branch that GitHub reports as conflicting (`dirty`) gets the base merged into its head as one App-authored, signed-off merge commit via the GitHub merges API (no human commit is rewritten), then merges once CI is green on the new head. A real conflict pushes nothing and posts one `` note naming the files both sides changed. Fork heads are never written. Attempted once per head (#13636). | -| `auto_merge.merge_train.enabled` | `true` | Conflict-aware merge train in every automerge lane (hive, trusted-author, contributor) ([#15117](https://github.com/hivecommons/hive/issues/15117)). Each sweep groups the open approved / mergeable-pending PRs of one repo+base by overlapping changed files (`GET /pulls/{n}/files`, cached per head SHA) and lets ONE front per group merge — ordered readiness first: a head the lane last saw at the merge gate (green, approved, soaking or waiting on a sweep) leads, one it has not evaluated since its push comes next, one still at CI / Review trails, then clean-mergeable before behind, then oldest; recomputed every pass, so a member that turns green moves up and one that turns red moves back — while the others wait at stage/080 with lane reason `merge-train:queued-behind#:/:…` (tracker pill "In merge queue · 3 of 4 · ~4m", never a human stage, never `needs-rebase` as a human flag). The moment the front merges, every sibling whose branch is merely `behind` gets `PUT /pulls/{n}/update-branch`; a `dirty` one is handed to the fixer's rebase-resolve episode (`requested_by: merge-train`, the shared two-attempt guard of [#15104](https://github.com/hivecommons/hive/pull/15104); the fixer router still requires a head the hive can push to, so a fork without maintainer edits stays on the plain `conflicting` path for a person). A head the lane last saw blocked on its own (red required check, terminal hold, permanent merge refusal) never fronts, and a group whose best member is blocked imposes no ordering (fail-open) — nobody waits behind a PR that is not moving. One INFO line `merge train` per order change, not per cycle. The queue carries one PR per issue: when two open PRs declare the same `Fixes #N`, the sweep keeps one (green first, then the earlier-opened) and holds the other with lane reason `merge-train:duplicate-of#:/0:0/0:` (tracker pill "Duplicate of #15402 · needs a pick"; *Let hive decide* supersedes, [#15395](https://github.com/hivecommons/hive/issues/15395)). That pick sees one lane; when the two claimants sit in different lanes (the hive's own PR and a trusted human's PR for one issue) every lane holds its candidate with lane reason `merge-train:claim-conflict#:/0:0/0:` and the log line `same-issue claim conflict undecided: #A vs #B`, so neither is admitted until a decision is recorded on one head or the other PR closes — the PR parks at 085, the chevron reads "held · duplicate of #B · needs decision", and the row's options name the concrete PRs; the hive recommends and never picks ([#15810](https://github.com/hivecommons/hive/issues/15810)). `false` restores independent per-PR evaluation. A PR GitHub reports conflicting on its own, or one at stage/072 returned-to-contributor (label or stage record), is never a member nor counted in the train's size and draws no train idle comment; a conflicting PR rides only while the train itself is repairing it (its rebase requested behind a merged front, loop guard not spent) ([#15395](https://github.com/hivecommons/hive/issues/15395)). | -| `auto_merge.merge_train.max_rebase_attempts` | `2` | Loop guard: how many rebase-resolve requests the train makes for one PR behind one front. Past it the PR moves to stage/085 with the pill "Needs human decision · rebase failed twice" and the decision option "Rebase, then merge as maintainer". | +| `auto_merge.merge_train.enabled` | `true` | **Settings → Auto-merge → Merge train → Conflict-aware merge train.** Conflict-aware merge train in every automerge lane (hive, trusted-author, contributor) ([#15117](https://github.com/hivecommons/hive/issues/15117)). Each sweep groups the open approved / mergeable-pending PRs of one repo+base by overlapping changed files (`GET /pulls/{n}/files`, cached per head SHA) and lets ONE front per group merge — ordered readiness first: a head the lane last saw at the merge gate (green, approved, soaking or waiting on a sweep) leads, one it has not evaluated since its push comes next, one still at CI / Review trails, then clean-mergeable before behind, then oldest; recomputed every pass, so a member that turns green moves up and one that turns red moves back — while the others wait at stage/080 with lane reason `merge-train:queued-behind#:/:…` (tracker pill "In merge queue · 3 of 4 · ~4m", never a human stage, never `needs-rebase` as a human flag). The moment the front merges, every sibling whose branch is merely `behind` gets `PUT /pulls/{n}/update-branch`; a `dirty` one is handed to the fixer's rebase-resolve episode (`requested_by: merge-train`, the shared two-attempt guard of [#15104](https://github.com/hivecommons/hive/pull/15104); the fixer router still requires a head the hive can push to, so a fork without maintainer edits stays on the plain `conflicting` path for a person). A head the lane last saw blocked on its own (red required check, terminal hold, permanent merge refusal) never fronts, and a group whose best member is blocked imposes no ordering (fail-open) — nobody waits behind a PR that is not moving. One INFO line `merge train` per order change, not per cycle. The queue carries one PR per issue: when two open PRs declare the same `Fixes #N`, the sweep keeps one (green first, then the earlier-opened) and holds the other with lane reason `merge-train:duplicate-of#:/0:0/0:` (tracker pill "Duplicate of #15402 · needs a pick"; *Let hive decide* supersedes, [#15395](https://github.com/hivecommons/hive/issues/15395)). That pick sees one lane; when the two claimants sit in different lanes (the hive's own PR and a trusted human's PR for one issue) every lane holds its candidate with lane reason `merge-train:claim-conflict#:/0:0/0:` and the log line `same-issue claim conflict undecided: #A vs #B`, so neither is admitted until a decision is recorded on one head or the other PR closes — the PR parks at 085, the chevron reads "held · duplicate of #B · needs decision", and the row's options name the concrete PRs; the hive recommends and never picks ([#15810](https://github.com/hivecommons/hive/issues/15810)). `false` restores independent per-PR evaluation. A PR GitHub reports conflicting on its own, or one at stage/072 returned-to-contributor (label or stage record), is never a member nor counted in the train's size and draws no train idle comment; a conflicting PR rides only while the train itself is repairing it (its rebase requested behind a merged front, loop guard not spent) ([#15395](https://github.com/hivecommons/hive/issues/15395)). | +| `auto_merge.merge_train.max_rebase_attempts` | `2`; `0` uses the default | **Settings → Auto-merge → Merge train → Rebase attempts per front.** Loop guard: how many rebase-resolve requests the train makes for one PR behind one front. Past it the PR moves to stage/085 with the pill "Needs human decision · rebase failed twice" and the decision option "Rebase, then merge as maintainer". | | `auto_merge.native_merge_queue.enabled` | `false` | Opt-in: once the lane's gates pass, enqueue the PR into GitHub's native merge queue (App auth only) instead of merging directly, and withdraw only Hive's own entries when the PR loses eligibility ([#15198](https://github.com/hivecommons/hive/issues/15198)). Off keeps the pre-queue behaviour everywhere, including the `merge-queue-required` park. See [native-merge-queue.md](../native-merge-queue.md). | | `auto_merge.native_merge_queue.repos` | unset (every watched repo once enabled) | `owner/repo` allow-list for the hand-off, matched case-insensitively. | | `auto_merge.native_merge_queue.skip_current_base_gate` | `false` | Explicitly lets a queue-enabled base bypass the `auto_merge.require_current_base` gate and the `behind` update-branch, because the merge group re-tests the merged result and a pushed head drops the PR from the queue. Off keeps both gates in force on queue bases. | diff --git a/src/pkg/config/config.go b/src/pkg/config/config.go index 401f97b80d..c3cbb1ec0c 100644 --- a/src/pkg/config/config.go +++ b/src/pkg/config/config.go @@ -295,6 +295,11 @@ func (c *Config) UnmarshalYAML(value *yaml.Node) error { c.AgentsGitHubAPIHourlyCap = cap c.AgentsGitHubAPIHourlyCapSet = capSet c.AgentsSessionRecycle = recycle + if governor := mappingValueNode(&node, "governor"); governor != nil { + if stall := mappingValueNode(governor, "merge_train_stall_warn_s"); stall != nil && stall.Tag != "!!null" { + c.Governor.mergeTrainStallWarnSet = true + } + } return nil } @@ -1597,11 +1602,12 @@ type GovernorConfig struct { // MergeTrainStallWarnS is how long, in seconds, a merge train's head // may sit without progressing before the Activity Monitor marks the // train stalled on the queued rows' chips and the dashboard writes one - // activity-log warning per hour (default DefaultMergeTrainStallWarnS, - // hivecommons/hive#15395). - MergeTrainStallWarnS int `yaml:"merge_train_stall_warn_s,omitempty"` - ConserveIntervalMultiplier int `yaml:"conserve_interval_multiplier,omitempty"` - OptionalSweepEveryNCycles int `yaml:"optional_sweep_every_n_cycles,omitempty"` + // activity-log warning per hour (default DefaultMergeTrainStallWarnS; + // explicit zero disables warnings; hivecommons/hive#15395). + MergeTrainStallWarnS int `yaml:"merge_train_stall_warn_s,omitempty"` + mergeTrainStallWarnSet bool `yaml:"-" json:"-"` + ConserveIntervalMultiplier int `yaml:"conserve_interval_multiplier,omitempty"` + OptionalSweepEveryNCycles int `yaml:"optional_sweep_every_n_cycles,omitempty"` // ExplainMode is the hive-wide default explain mode for agents that leave // their own explain_mode unset. "" means "no hive default configured", in // which case ExplainModeEnvVar is consulted and then off — see @@ -5272,10 +5278,16 @@ func (c *Config) CIFailureKickCooldown() time.Duration { return DefaultCIFailureKickCooldownS * time.Second } +// SetMergeTrainStallWarnS records an explicit value, including zero to disable warnings. +func (c *Config) SetMergeTrainStallWarnS(seconds int) { + c.Governor.MergeTrainStallWarnS = seconds + c.Governor.mergeTrainStallWarnSet = true +} + // MergeTrainStallWarn is the effective governor.merge_train_stall_warn_s as -// a duration (default one hour). +// a duration (default one hour; explicit zero disables warnings). func (c *Config) MergeTrainStallWarn() time.Duration { - if c != nil && c.Governor.MergeTrainStallWarnS > 0 { + if c != nil && (c.Governor.mergeTrainStallWarnSet || c.Governor.MergeTrainStallWarnS > 0) { return time.Duration(c.Governor.MergeTrainStallWarnS) * time.Second } return DefaultMergeTrainStallWarnS * time.Second @@ -7169,6 +7181,13 @@ func (c Config) MarshalYAML() (interface{}, error) { if root == nil { return out, nil } + if c.Governor.mergeTrainStallWarnSet && c.Governor.MergeTrainStallWarnS == 0 { + if governor := mappingValueNode(root, "governor"); governor != nil { + governor.Content = append(governor.Content, + &yaml.Node{Kind: yaml.ScalarNode, Value: "merge_train_stall_warn_s"}, + &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!int", Value: "0"}) + } + } agents := mappingValueNode(root, "agents") if agents == nil { root.Content = append(root.Content, &yaml.Node{Kind: yaml.ScalarNode, Value: "agents"}, &yaml.Node{Kind: yaml.MappingNode}) diff --git a/src/pkg/config/merge_train_settings_test.go b/src/pkg/config/merge_train_settings_test.go new file mode 100644 index 0000000000..b781886244 --- /dev/null +++ b/src/pkg/config/merge_train_settings_test.go @@ -0,0 +1,59 @@ +package config + +import ( + "strings" + "testing" + "time" + + "gopkg.in/yaml.v3" +) + +func TestMergeTrainStallWarningYAMLRoundTrip(t *testing.T) { + for _, tc := range []struct { + name, yaml string + want time.Duration + explicitZero bool + }{ + {"absent", "governor: {}", time.Hour, false}, + {"null", "governor: {merge_train_stall_warn_s: null}", time.Hour, false}, + {"disabled", "governor: {merge_train_stall_warn_s: 0}", 0, true}, + {"custom", "governor: {merge_train_stall_warn_s: 120}", 2 * time.Minute, false}, + } { + t.Run(tc.name, func(t *testing.T) { + var cfg Config + if err := yaml.Unmarshal([]byte(tc.yaml), &cfg); err != nil { + t.Fatal(err) + } + if got := cfg.MergeTrainStallWarn(); got != tc.want { + t.Fatalf("threshold=%s want %s", got, tc.want) + } + data, err := yaml.Marshal(cfg) + if err != nil { + t.Fatal(err) + } + if tc.explicitZero && !strings.Contains(string(data), "merge_train_stall_warn_s: 0") { + t.Fatal("explicit zero was dropped on save") + } + var restored Config + if err := yaml.Unmarshal(data, &restored); err != nil { + t.Fatal(err) + } + if got := restored.MergeTrainStallWarn(); got != tc.want { + t.Fatalf("restored threshold=%s want %s", got, tc.want) + } + }) + } + cfg := &Config{} + cfg.SetMergeTrainStallWarnS(0) + data, err := yaml.Marshal(cfg) + if err != nil { + t.Fatal(err) + } + var restored Config + if err := yaml.Unmarshal(data, &restored); err != nil { + t.Fatal(err) + } + if restored.MergeTrainStallWarn() != 0 { + t.Fatal("dashboard disable did not survive persistence") + } +} diff --git a/src/pkg/dashboard/api.go b/src/pkg/dashboard/api.go index cf24f69def..7a1ce6f845 100644 --- a/src/pkg/dashboard/api.go +++ b/src/pkg/dashboard/api.go @@ -208,6 +208,7 @@ func (s *Server) RegisterAPI(deps *Dependencies) { s.mux.HandleFunc("GET /api/config/stat-sources", s.handleStatSources) s.mux.HandleFunc("GET /api/config/governor", s.handleGovernorConfigGet) + s.mux.HandleFunc("PATCH /api/config/governor", s.handleGovernorMergeTrainPatch) s.mux.HandleFunc("GET /api/config/dashboard", s.handleDashboardSettingsGet) s.mux.HandleFunc("PUT /api/config/dashboard", s.handleDashboardSettingsPut) s.mux.HandleFunc("PUT /api/config/governor/sensing", s.handleGovernorSensing) @@ -249,6 +250,7 @@ func (s *Server) RegisterAPI(deps *Dependencies) { // lives on the governor Features tab — see api_config_automerge.go. s.mux.HandleFunc("GET /api/config/auto-merge", s.handleAutoMergeGet) s.mux.HandleFunc("PUT /api/config/auto-merge", s.handleAutoMergePut) + s.mux.HandleFunc("PATCH /api/config/auto-merge", s.handleAutoMergePut) // convergence is a top-level Config field (not GovernorConfig); its UI // lives on the governor Features tab — see api_config_convergence.go // (#4263 off/shadow/enforce rollout). The soak endpoint is the diff --git a/src/pkg/dashboard/api_config_automerge.go b/src/pkg/dashboard/api_config_automerge.go index d810f551d2..8665e5e5c5 100644 --- a/src/pkg/dashboard/api_config_automerge.go +++ b/src/pkg/dashboard/api_config_automerge.go @@ -143,6 +143,10 @@ func (s *Server) handleAutoMergePut(w http.ResponseWriter, r *http.Request) { return } var body struct { + MergeTrain *struct { + Enabled *bool `json:"enabled"` + MaxRebaseAttempts *int `json:"max_rebase_attempts"` + } `json:"merge_train"` NativeMergeQueue *nativeQueueSettingsPatch `json:"native_merge_queue"` SelfAuthored *bool `json:"self_authored"` MaxMerges *int `json:"max_merges"` @@ -186,6 +190,10 @@ func (s *Server) handleAutoMergePut(w http.ResponseWriter, r *http.Request) { } // --- validate before mutating anything --- + if body.MergeTrain != nil && body.MergeTrain.MaxRebaseAttempts != nil && *body.MergeTrain.MaxRebaseAttempts < 0 { + jsonError(w, "merge_train.max_rebase_attempts must be at least 0 (0 uses the default of 2)", http.StatusBadRequest) + return + } nativeQueue, err := updateNativeQueueSettings(s.deps.Config.AutoMerge.NativeMergeQueue, body.NativeMergeQueue) if err != nil { jsonError(w, err.Error(), http.StatusBadRequest) @@ -270,6 +278,15 @@ func (s *Server) handleAutoMergePut(w http.ResponseWriter, r *http.Request) { // --- apply --- cfg := s.deps.Config previousAutoMerge := cfg.AutoMerge + if body.MergeTrain != nil { + if body.MergeTrain.Enabled != nil { + v := *body.MergeTrain.Enabled + cfg.AutoMerge.MergeTrain.Enabled = &v + } + if body.MergeTrain.MaxRebaseAttempts != nil { + cfg.AutoMerge.MergeTrain.MaxRebaseAttempts = *body.MergeTrain.MaxRebaseAttempts + } + } if body.NativeMergeQueue != nil { cfg.AutoMerge.NativeMergeQueue = nativeQueue } @@ -369,10 +386,10 @@ 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 { + if body.NativeMergeQueue != nil || body.MergeTrain != nil { cfg.AutoMerge = previousAutoMerge syncAutoMergePolicyToGitHubClient(cfg, s.deps.GHClient) - jsonError(w, "failed to persist native queue settings", http.StatusInternalServerError) + jsonError(w, "failed to persist auto-merge settings", http.StatusInternalServerError) return } } @@ -440,6 +457,10 @@ func autoMergeSectionResponse(cfg *config.Config) map[string]interface{} { "require_current_base_default": am.CurrentBaseDefaultEnabled(), "require_current_base": emptyIfNilStrings(am.RequireCurrentBase), "skip_current_base": emptyIfNilStrings(am.SkipCurrentBase), + "merge_train": map[string]interface{}{ + "enabled": am.MergeTrain.IsEnabled(), + "max_rebase_attempts": am.MergeTrain.EffectiveMaxRebaseAttempts(), + }, "native_merge_queue": map[string]interface{}{ "enabled": am.NativeMergeQueue.Enabled, "repos": emptyIfNilStrings(am.NativeMergeQueue.Repos), diff --git a/src/pkg/dashboard/api_governor.go b/src/pkg/dashboard/api_governor.go index 8a832b7952..1b15f345d2 100644 --- a/src/pkg/dashboard/api_governor.go +++ b/src/pkg/dashboard/api_governor.go @@ -226,6 +226,7 @@ func (s *Server) handleGovernorConfigGet(w http.ResponseWriter, r *http.Request) "ttlSeconds": cfg.Governor.Sensing.TTLSeconds, "pullbackSeconds": cfg.Governor.Sensing.PullbackSeconds, }, + "merge_train_stall_warn_s": int(cfg.MergeTrainStallWarn() / time.Second), "logging": loggingSectionResponse(cfg), "dashboard": dashboardSettingsResponse(cfg), "backends": backendsPolicyResponse(cfg), diff --git a/src/pkg/dashboard/api_governor_merge_train.go b/src/pkg/dashboard/api_governor_merge_train.go new file mode 100644 index 0000000000..7bdee25d7b --- /dev/null +++ b/src/pkg/dashboard/api_governor_merge_train.go @@ -0,0 +1,42 @@ +package dashboard + +import ( + "net/http" + "time" +) + +// handleGovernorMergeTrainPatch edits the stall warning without changing other governor settings. +func (s *Server) handleGovernorMergeTrainPatch(w http.ResponseWriter, r *http.Request) { + if !requireOwnerRole(w, r) { + return + } + if s.deps == nil || s.deps.Config == nil { + jsonError(w, "config unavailable", http.StatusServiceUnavailable) + return + } + var body struct { + StallWarnS *int `json:"merge_train_stall_warn_s"` + } + if err := decodeBody(r, &body); err != nil { + jsonError(w, "invalid body", http.StatusBadRequest) + return + } + if body.StallWarnS != nil && (*body.StallWarnS < 0 || int64(*body.StallWarnS) > int64((1<<63-1)/time.Second)) { + jsonError(w, "merge_train_stall_warn_s must be non-negative seconds within the supported duration range", http.StatusBadRequest) + return + } + cfg := s.deps.Config + previous := cfg.Governor + if body.StallWarnS != nil { + cfg.SetMergeTrainStallWarnS(*body.StallWarnS) + } + if err := s.saveConfig(); err != nil { + cfg.Governor = previous + s.logger.Error("failed to persist merge-train stall warning", "error", err) + jsonError(w, "failed to persist governor settings", http.StatusInternalServerError) + return + } + s.auditFromRequest(r, "config_governor", auditDetail("section", "governor"), "") + s.refreshAndPersist() + jsonResponse(w, map[string]interface{}{"merge_train_stall_warn_s": int(cfg.MergeTrainStallWarn() / time.Second)}) +} diff --git a/src/pkg/dashboard/audit.go b/src/pkg/dashboard/audit.go index dbaec8961e..af149dfa61 100644 --- a/src/pkg/dashboard/audit.go +++ b/src/pkg/dashboard/audit.go @@ -73,6 +73,7 @@ var auditSensitiveActions = map[string]bool{ "config_convergence": true, "config_escalation": true, "config_github": true, + "config_governor": true, "config_governor_advisory": true, "config_governor_attribution": true, "config_governor_backup_key": true, diff --git a/src/pkg/dashboard/merge_train_settings_test.go b/src/pkg/dashboard/merge_train_settings_test.go new file mode 100644 index 0000000000..b08beb758a --- /dev/null +++ b/src/pkg/dashboard/merge_train_settings_test.go @@ -0,0 +1,176 @@ +package dashboard + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "reflect" + "strconv" + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/config" +) + +func patchMergeTrainSettings(s *Server, path, body string) *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodPatch, path, strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + markOwnerRequest(req) + rec := httptest.NewRecorder() + s.mux.ServeHTTP(rec, req) + return rec +} + +func TestMergeTrainSettingsPatchRoundTrip(t *testing.T) { + s := covApiServer(t) + assertTrain := func(enabled bool, attempts int) { + t.Helper() + rec := doOwnerGet(s, "/api/config/auto-merge") + var body struct { + Train struct { + Enabled bool `json:"enabled"` + Attempts int `json:"max_rebase_attempts"` + } `json:"merge_train"` + Bots []map[string]any `json:"bot_authors"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatal(err) + } + if rec.Code != http.StatusOK || body.Train.Enabled != enabled || body.Train.Attempts != attempts || len(body.Bots) == 0 { + t.Fatalf("auto-merge response: %d %s", rec.Code, rec.Body.String()) + } + } + assertTrain(true, 2) + for _, body := range []string{`{"merge_train":{"enabled":false,"max_rebase_attempts":4}}`, `{"merge_train":{"max_rebase_attempts":0}}`, `{"merge_train":{"enabled":true}}`} { + if rec := patchMergeTrainSettings(s, "/api/config/auto-merge", body); rec.Code != http.StatusOK { + t.Fatalf("PATCH: %d %s", rec.Code, rec.Body.String()) + } + switch body { + case `{"merge_train":{"enabled":false,"max_rebase_attempts":4}}`: + assertTrain(false, 4) + case `{"merge_train":{"max_rebase_attempts":0}}`: + assertTrain(false, 2) + default: + assertTrain(true, 2) + } + } + // The existing partial PUT writer accepts the same nested payload. + if rec := doPut(s, "/api/config/auto-merge", map[string]any{"merge_train": map[string]any{"max_rebase_attempts": 3}}); rec.Code != http.StatusOK { + t.Fatal(rec.Body.String()) + } + assertTrain(true, 3) + for _, seconds := range []int{7200, 0, 3600} { + raw, _ := json.Marshal(map[string]int{"merge_train_stall_warn_s": seconds}) + rec := patchMergeTrainSettings(s, "/api/config/governor", string(raw)) + if rec.Code != http.StatusOK { + t.Fatalf("governor PATCH: %d %s", rec.Code, rec.Body.String()) + } + var body map[string]int + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatal(err) + } + if got := body["merge_train_stall_warn_s"]; got != seconds { + t.Fatalf("echo=%d want %d", got, seconds) + } + rec = doOwnerGet(s, "/api/config/governor") + var governor map[string]json.RawMessage + if err := json.Unmarshal(rec.Body.Bytes(), &governor); err != nil { + t.Fatal(err) + } + if string(governor["merge_train_stall_warn_s"]) != strconv.Itoa(seconds) { + t.Fatalf("governor GET: %s", rec.Body.String()) + } + if s.deps.Config.MergeTrainStallWarn() != time.Duration(seconds)*time.Second { + t.Fatal("stall threshold not applied") + } + } + for _, action := range []string{"config_auto_merge", "config_governor"} { + found := false + for _, entry := range s.audit.Recent(50) { + if entry.Action == action { + if !auditEntryIsSensitive(entry) { + t.Errorf("%s audit must be marked sensitive", action) + } + found = true + } + } + if !found { + t.Errorf("missing %s audit", action) + } + } +} + +func TestMergeTrainSettingsPatchRejectsInvalidWithoutMutation(t *testing.T) { + for _, tc := range []struct{ path, body string }{ + {"auto-merge", `{"merge_train":{"enabled":false,"max_rebase_attempts":-1}}`}, + {"auto-merge", `{"merge_train":{"max_rebase_attempts":"two"}}`}, + {"auto-merge", `{"merge_train":"invalid"}`}, + {"governor", `{"merge_train_stall_warn_s":"soon"}`}, + {"governor", `{"merge_train_stall_warn_s":-1}`}, + {"governor", `{"merge_train_stall_warn_s":1.5}`}, + {"governor", `{"merge_train_stall_warn_s":9223372036854775807}`}, + {"governor", `"invalid"`}, + } { + t.Run(tc.path+tc.body, func(t *testing.T) { + s := covApiServer(t) + beforeAM, beforeGov := s.deps.Config.AutoMerge, s.deps.Config.Governor + rec := patchMergeTrainSettings(s, "/api/config/"+tc.path, tc.body) + if rec.Code != http.StatusBadRequest { + t.Fatalf("got %d: %s", rec.Code, rec.Body.String()) + } + if !reflect.DeepEqual(beforeAM, s.deps.Config.AutoMerge) || !reflect.DeepEqual(beforeGov, s.deps.Config.Governor) { + t.Fatal("invalid PATCH mutated settings") + } + }) + } +} + +func TestMergeTrainSettingsOwnerOnlyAndPersistenceFailure(t *testing.T) { + for _, tc := range []struct{ path, body string }{ + {"auto-merge", `{"merge_train":{"enabled":false,"max_rebase_attempts":3}}`}, + {"governor", `{"merge_train_stall_warn_s":0}`}, + } { + t.Run(tc.path, func(t *testing.T) { + s := covApiServer(t) + beforeAM, beforeGov := s.deps.Config.AutoMerge, s.deps.Config.Governor + req := httptest.NewRequest(http.MethodPatch, "/api/config/"+tc.path, strings.NewReader(tc.body)) + req.Header.Set("X-Hive-Role", config.RoleReadWrite) + rec := httptest.NewRecorder() + s.mux.ServeHTTP(rec, req) + if rec.Code != http.StatusForbidden { + t.Fatalf("non-owner: %d", rec.Code) + } + s.deps.Config.SourcePath = "unwritten-merge-train-settings.yaml" + s.deps.Config.Project.Org = "" // Save guard fails before writing files. + rec = patchMergeTrainSettings(s, "/api/config/"+tc.path, tc.body) + if rec.Code != http.StatusInternalServerError { + t.Fatalf("save failure: %d %s", rec.Code, rec.Body.String()) + } + if !reflect.DeepEqual(beforeAM, s.deps.Config.AutoMerge) || !reflect.DeepEqual(beforeGov, s.deps.Config.Governor) { + t.Fatal("refused update changed live settings") + } + }) + } +} + +func TestMergeTrainSettingsMarkup(t *testing.T) { + body := extractJSFunction(t, indexHTML(t), "renderGovFeatures") + for _, key := range []string{"auto_merge.merge_train.enabled", "auto_merge.merge_train.max_rebase_attempts", "governor.merge_train_stall_warn_s"} { + if !strings.Contains(body, "yamlHint('"+key+"')") { + t.Errorf("missing yamlHint for %s", key) + } + } + for _, label := range []string{"Conflict-aware merge train", "Rebase attempts per front", "Stall warning after"} { + if !strings.Contains(body, "'"+label+"', `") { + t.Errorf("missing settingHelpMark for %s", label) + } + } + train, native, review := strings.Index(body, ">Merge train"), strings.Index(body, "