diff --git a/changelog.d/added-delegate-plan-what-hive-saw.md b/changelog.d/added-delegate-plan-what-hive-saw.md
new file mode 100644
index 0000000000..df8e8638fb
--- /dev/null
+++ b/changelog.d/added-delegate-plan-what-hive-saw.md
@@ -0,0 +1 @@
+- *Let hive decide* now shows what the decision rests on. Under **Details**, the preview lists **What hive saw**: every fact the decision rules read (author, whether the contributor is connected, CI, conflicts, sign-off, review, Sentinel and the rest), each marked as fine, holding the item back, or steering the decision. Then come the rule that decided, with its whole reason, and each option that was ruled out, with the fact that ruled it out. The visible part of the dialog is unchanged.
diff --git a/src/docs/api-reference/packs-and-acmm.md b/src/docs/api-reference/packs-and-acmm.md
index c1714c7f5b..3b2a9c07a5 100644
--- a/src/docs/api-reference/packs-and-acmm.md
+++ b/src/docs/api-reference/packs-and-acmm.md
@@ -19,7 +19,7 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f
| `POST` | `/api/repos/{owner}/{repo}/items/{number}/hold` | Owner or repo write/maintain/admin | Add or remove a dashboard hold chip for an issue or PR. Body `{"held": true}` adds the hive's exact-match canonical `hive-pause/` label; `{"held": false}` removes exactly the labels causing the hold (`hive-pause/` and/or generic hold labels) and never removes `hive/` provenance. Every toggle writes an audit-log entry; the #8851 upgrade migration writes `/data/hive-hold-migration-.json` with audit-backed, provenance-only, and ambiguous legacy `hive/` classifications. | `pkg/dashboard/api.go:364`, `pkg/dashboard/api_repo_hold.go` |
| `POST` | `/api/repos/{owner}/{repo}/items/{number}/decision` | Owner or repo write/maintain/admin, signed-in GitHub user | Record an operator decision from the activity monitor's row menu / selection bar. Body `{"decision": "approve"|"direction"|"close-superseded"|"close-wontfix"|"adopt"|"reroute"|"re-author"|"merge-now"|"queue-merge", "comment": "…", "type": "issue"|"pr", "superseded_by": "#458", "force": true, "to": ""|"any"}` (`force` only with `adopt`, `to` only with `reroute`; an unknown `decision` is a 400). On an issue parked at 045, `approve`/`direction` act exactly as a maintainer's `/hive approve` / `/hive decision ` comment would (labels, `approved-direction`, stage-engine Unparked fact, reply comment naming the operator). On a PR parked at 085 (`type: "pr"`), `approve` posts the `/lgtm` and `/approve` commands as two comments attributed to the operator, records the approval against the head as the human answer to a `requires_human` / decision-requested verdict (the lanes and the stage engine honour it like a trusted merger's Approve review), lifts `needs-human`, clears the sentinel label and acknowledges the bundle's sentinel findings for that head, re-derives the stage and drops the tracker cache — the response adds `released` (`approval-recorded`, `needs-human`, `sentinel-label`, `sentinel-acknowledged`) and `stage`; the merge gate decides from there (no review as the operator, no merge) — and `direction` records the text as a human change request against the head — the `/hive decision` fix lane — on a hive-authored PR, and on a contributor's clanker PR (`author/clanker` / hive attribution markers) where the text is posted to the contributor's hive and the PR moves to `stage/072-returned-to-contributor` (`status: "direction-returned-to-contributor"`); a person's PR, which no hive can carry direction to, answers 409. The close variants post a comment naming the operator (and the superseding PR when `superseded_by` is given) and close the item as not planned. `adopt` and `re-author` require `type: "pr"` and queue adoption via the `adoption/supersede` label (409 unless `governor.labels.stage.adoption` is enabled). `adopt` with `"force": true` is *Adopt now* ([#15038](https://github.com/hivecommons/hive/issues/15038)): it bypasses the author's presence, the grace window and `maintainer_policy`, marks the stage record and nudges the automerge sweep so the adoption engine supersedes the head at once (responds `status: "already-adopted"` when nothing is left to do; 400 on the hive's own PR). `reroute` (`type: "pr"`, `"to": ""|"any"`) hands the PR's follow-up work to another online clanker through the contributor fix queue, posts a `` note and arms a pickup timer that falls back to Adopt now after `governor.reroute.pickup_timeout`; answers `status: "rerouted"`, 409 when no clanker is online or adoption is disabled. On a PR at 090, `queue-merge` (*Approve and let hive merge*, the lead action) records an approval attributed to the operator and applies the automerge label, returning `status: "queued-for-merge"` (on the hive's own PR, which the App cannot review, the queue note is a comment and the operator's approval is recorded as `approve` records it — `released` lists `approval-recorded`, `admitted`); hive's merge sweep merges on its next tick once CI is green and the head has soaked, and that recorded operator approval is the one thing that lets the sweep merge an untrusted-author PR (the merge comment names the operator). `merge-now` (*Merge now as maintainer*, secondary) posts an attributed comment and merges immediately through the hive's GitHub App, returning `status: "merged"`. Both require `type: "pr"` and a verified owner or `merger` role in addition to the route's repo permission check; both refuse closed/merged PRs and the operator's own PR. `merge-now` on a PR whose `mergeable_state` is `dirty`/`behind` instead answers `202` with `status: "rebase-queued"` (approval recorded, rebase kicked, merge follows via the follow-through once the hive's own rebase is green; a head pushed by anyone else fails the follow-through closed; `head-not-pushable` refusal on a fork without maintainer edits). `approve` on such a PR adds `rebase: {attempt, max, exhausted, head, text}` for the rebase episode it opened. Every decision writes an audit-log entry (`repo_item_decision_*`, e.g. `repo_item_decision_adopt_now`, `repo_item_decision_reroute`). | `pkg/dashboard/api.go:365`, `pkg/dashboard/api_repo_item_decision.go` |
| `POST` / `GET` | `/api/repos/{owner}/{repo}/items/{number}/decide-delegated` | Same as `…/hold` (owner or repo write), signed-in GitHub user; `decisions.delegate.enabled` (403 when off) | *Let hive decide*: enqueue a delegated-decision job in which the hive decides the parked item itself as the owner's delegate under `pkg/delegatedecision.PolicyText` and records it as a human decision (`/hive decision` comment with the `` marker, park labels off, `triage/accepted`, queue approval on a PR head). Body `{"type": "issue"|"pr", "reason", "caption", "sentinel_reason"}`. `POST` answers 202 with the job (`{id, status: "running"|"done"|"failed", decision: {verdict, rule, text, rationale, actions, keeps_park, ladder?: {decision, reason, ruled_out[]}}, notes, error}`; `ladder` is set on contributor-PR decisions and names the rung that decided — `already-fixed` → `mergeable-as-is` → `rebase-then-merge` → `return-to-contributor` → `contributor-offline` — and why each rung above it did not apply); 409 with the running job while one is in flight; `GET` reads it. Rails: never merges, refuses items wearing `hold`, never grants secrets/permissions (`needs-owner` + `hold` instead), recommends only on hive policy/governance questions (keeps 085). Audited as `repo_item_decision_delegated[_failed]`. See [dashboard-sections.md](../dashboard-sections/activity-monitor.md#let-hive-decide). | `pkg/dashboard/api.go:329`, `pkg/dashboard/api_repo_item_decide_delegated.go` |
-| `POST` | `/api/repos/{owner}/{repo}/items/{number}/decide-delegated/plan` | Same as `…/decide-delegated` | Preview for *Let hive decide*: runs the same owner-delegate policy with **no side effects** (nothing written, no job) and answers `{would, rule, acting, title, summary, why, consequences[], ladder, mergeable_as_is, alternatives[], writes: false, prior, notes}` — `summary` is one verb-first sentence with no "Hive would:" prefix (*Send #15332 back to its author with one instruction: make CI green, nothing else.*), `why` one short line (*CI is red.*), `consequences` at most two items, `ladder` the rung that decided with its `ruled_out` list, and `mergeable_as_is` whether an as-is merge is honest (the queue-merge and merge-now alternatives are dropped when it is not). The dialog shows **Cancel** / **Let hive do that**, plus **Approve and let hive merge** (or **Merge now as maintainer** when the hive would approve anyway) only when `mergeable_as_is`; only then does the SPA post `…/decide-delegated` with `chosen` naming the button. See [dashboard-sections.md](../dashboard-sections/activity-monitor.md#let-hive-decide). | `pkg/dashboard/api.go:369`, `pkg/dashboard/api_repo_item_decide_delegated_plan.go` |
+| `POST` | `/api/repos/{owner}/{repo}/items/{number}/decide-delegated/plan` | Same as `…/decide-delegated` | Preview for *Let hive decide*: runs the same owner-delegate policy with **no side effects** (nothing written, no job) and answers `{would, rule, acting, title, summary, why, consequences[], ladder, mergeable_as_is, alternatives[], writes: false, prior, notes, saw[], rule_plain, rationale, why_not[]}` — `summary` is one verb-first sentence with no "Hive would:" prefix (*Send #15332 back to its author with one instruction: make CI green, nothing else.*), `why` one short line (*CI is red.*), `consequences` at most two items, `ladder` the rung that decided with its `ruled_out` list, `saw` every fact the rules read as `{label, value, state}` (`state` is `ok`, `blocks` or `info`), `rule_plain` and `rationale` the deciding rule in plain words and its whole reason (`rationale` omitted when it only repeats `why`), `why_not` the ruled-out rungs as `{option, because}`, and `mergeable_as_is` whether an as-is merge is honest (the queue-merge and merge-now alternatives are dropped when it is not). The dialog shows **Cancel** / **Let hive do that**, plus **Approve and let hive merge** (or **Merge now as maintainer** when the hive would approve anyway) only when `mergeable_as_is`; only then does the SPA post `…/decide-delegated` with `chosen` naming the button. See [dashboard-sections.md](../dashboard-sections/activity-monitor.md#let-hive-decide). | `pkg/dashboard/api.go:369`, `pkg/dashboard/api_repo_item_decide_delegated_plan.go` |
| `POST` | `/api/repos/{owner}/{repo}/items/{number}/blocker/recheck` | Same as `…/hold` (owner or repo write), signed-in GitHub user | *Re-check permissions* on an issue parked on a capability blocker (#15099): probes the GitHub App installation's permissions; when a non-workflows permission is granted, clears its ledger entries and un-parks the item; workflows blockers require a separate hand-off (`{result: {outcome: "released", …}}`), otherwise `{result: {outcome: "no-effect", reason: "blocker", options: [...]}}`; 404 when the item has no blocker, 409 when the blocker is not a capability gap | `pkg/dashboard/api.go:370` |
| `POST` | `/api/repos/{owner}/{repo}/items/{number}/blocker/handoff` | Same as `…/hold`, signed-in GitHub user | With a workflows blocker, verified App permission and capable lane, records the decision, clears the park and routes the issue to that lane; rejects held or ineligible issues | `pkg/dashboard/api.go:371` |
| `POST` | `/api/repos/{owner}/{repo}/items/{number}/blocker/close-partial` | Same as `…/hold` (owner or repo write), signed-in GitHub user | Option (c) on a capability blocker (#15099): labels the issue `hive/partially-addressed`, posts the operator's `{"comment"}` naming what remains and closes it; the ledger entry is cleared | `pkg/dashboard/api.go:372` |
diff --git a/src/docs/dashboard-sections/activity-monitor.md b/src/docs/dashboard-sections/activity-monitor.md
index 65fc4a959d..ab810d0ca4 100644
--- a/src/docs/dashboard-sections/activity-monitor.md
+++ b/src/docs/dashboard-sections/activity-monitor.md
@@ -752,11 +752,11 @@ The toast and the decision trail lead with the outcome in one line — *Adopted
**Fast previews.** Revealing a row's decision options — opening its decision popover or ⋯ menu, or hovering or focusing its *Let hive decide* button — prefetches the plan, and the click reuses that answer. The server keeps each plan for 45 s (at most 256 entries) keyed by repo, number, type, PR head and the request, so the prefetch and the click share one GitHub round trip; a new head or a recorded decision drops it. The plan response carries `Server-Timing: decide_plan;desc="hit|miss";dur=…` and the server logs one debug line with the plan's duration ([#15773](https://github.com/hivecommons/hive/issues/15773)).
-**Preview before acting.** *Let hive decide* no longer acts on the click. The button turns busy and reads **Asking the hive…** (the row caption says the same) while it first calls `POST …/decide-delegated/plan`, a dry run with no side effects that answers `{would, title, summary, why, consequences[], ladder, mergeable_as_is, alternatives[]}`, and shows one decision — built to be read in three seconds (operator feedback on hive's own spoke: the first version was "a wall of text" with a doubled *Hive would: Hive would:*, the PR named twice, three type sizes and a merge button on a head it had just called not mergeable):
+**Preview before acting.** *Let hive decide* no longer acts on the click. The button turns busy and reads **Asking the hive…** (the row caption says the same) while it first calls `POST …/decide-delegated/plan`, a dry run with no side effects that answers `{would, title, summary, why, consequences[], ladder, mergeable_as_is, alternatives[], saw[], rule_plain, rationale, why_not[]}`, and shows one decision — built to be read in three seconds (operator feedback on hive's own spoke: the first version was "a wall of text" with a doubled *Hive would: Hive would:*, the PR named twice, three type sizes and a merge button on a head it had just called not mergeable):
- **Title** *Let hive decide*, then one subject line — `hivecommons/hive#15332 · ci: run crux's Go file-size ratchet…` — with a compact **⚠ Sentinel** chip when the sentinel flagged the head (the full finding is in Details).
- **Eyebrow** *Hive would* → **one verb-first sentence**: *Send #15332 back to its author with one instruction: make CI green, nothing else.* → one muted **Why** line (≤ 12 words: *CI is red.*) → **Then**, at most two short items (*Hive posts that instruction on #15332. · The author pushes a fix; the row updates when it lands.*).
-- **Details** (collapsed): the sentinel finding, *Why not the others* — the ladder rungs ruled out above the one that decided (`ladder.ruled_out`) — and the one-line rails (*never merges, never touches held items, never grants secrets; the sentinel label stays with a person*).
+- **Details** (collapsed): the sentinel finding; **What hive saw** (`saw`), every fact the decision rules read — author, whether the contributor is connected, CI, conflicts, sign-off, review, Sentinel, and whatever else steered it — each marked ✓ (fine), ✗ (holds it back) or • (steers the decision), then the **Rule** that decided and its whole reason; *Why not the others* — each option the ladder ruled out above the one that decided, with the fact that ruled it out (*Approve as it is — conflicting, CI not green*; `why_not`, from `ladder.ruled_out`); and the one-line rails (*never merges, never touches held items, never grants secrets; the sentinel label stays with a person*).
- **Buttons**, right-aligned: **Cancel** · **Let hive do that**. A merge button appears only when the plan says `mergeable_as_is` — the ladder's *mergeable-as-is* rung, or (no ladder) a green, conflict-free, signed-off head — and is greyed with the reason when the operator lacks merge rights; the plan drops both merge alternatives otherwise, so the dialog cannot contradict itself. The button is **Approve and let hive merge** (`decide:queue-merge`); when the hive would approve anyway, that is the primary button under another name, so the one merge alternative left is **Merge now as maintainer**.
The same renderer serves issue decisions and every PR verdict (adopt, approve, close as duplicate/superseded, send back, recommend only). The visible text never uses hive's vocabulary (*park*, *audit marker*, *stage*, *ladder*, */hive decision*) and is ≤ 60 words for the #15332 case, which the node harness enforces. Nothing is written until the operator picks, and the badge tooltip and the trail record which button was pressed (the request's `chosen`).
diff --git a/src/pkg/dashboard/api_repo_item_decide_delegated_plan.go b/src/pkg/dashboard/api_repo_item_decide_delegated_plan.go
index 5277a0fa27..f5d57ffe52 100644
--- a/src/pkg/dashboard/api_repo_item_decide_delegated_plan.go
+++ b/src/pkg/dashboard/api_repo_item_decide_delegated_plan.go
@@ -69,6 +69,14 @@ type delegatedDecisionPlan struct {
// then says so and the primary button re-runs it.
Prior *time.Time `json:"prior,omitempty"`
Notes []string `json:"notes,omitempty"`
+ // Saw is every fact the decision rules read, for the dialog's "What
+ // hive saw"; RulePlain and Rationale are the rule that decided and its
+ // whole reason; WhyNot is the ladder's ruled-out options with the fact
+ // that ruled each out. All four sit under Details.
+ Saw []delegatedecision.Fact `json:"saw,omitempty"`
+ RulePlain string `json:"rule_plain,omitempty"`
+ Rationale string `json:"rationale,omitempty"`
+ WhyNot []delegatedecision.WhyNot `json:"why_not,omitempty"`
}
// delegatedPlanAlternativeLabel is the preview's merge button: the
@@ -230,7 +238,7 @@ func (s *Server) planDelegatedDecision(ctx context.Context, repoFull string, num
if err != nil {
return nil, err
}
- plan := &delegatedDecisionPlan{Repo: repoFull, Number: number, Type: itemType, Title: strings.TrimSpace(in.Title)}
+ plan := &delegatedDecisionPlan{Repo: repoFull, Number: number, Type: itemType, Title: strings.TrimSpace(in.Title), Saw: in.Facts()}
if in.Kind == delegatedecision.KindIssue {
if b := s.delegatedBlocker(ctx, repoFull, number, s.delegatedCommentTexts(ctx, repoFull, number)); b != nil && blocker.Kind(b.Kind) == blocker.CapabilityWorkflowsPermission {
held := len(holdLabels(in.Labels, s.delegateHiveID())) > 0
@@ -274,7 +282,8 @@ func (s *Server) planDelegatedDecision(ctx context.Context, repoFull string, num
}
plan.Summary, plan.Consequences = delegatedPlanWording(in, d)
plan.Why = delegatedPlanWhy(in, d)
- plan.Ladder = d.Ladder
+ plan.RulePlain, plan.Rationale = delegatedPlanRule(in, d, plan.Why)
+ plan.Ladder, plan.WhyNot = d.Ladder, d.Ladder.WhyNot()
plan.MergeableAsIs = delegatedPlanMergeableAsIs(in, d)
if plan.Alternatives == nil {
plan.Alternatives = delegatedPlanAlternatives(in, d, mergerRole)
diff --git a/src/pkg/dashboard/api_repo_item_decide_delegated_plan_rule.go b/src/pkg/dashboard/api_repo_item_decide_delegated_plan_rule.go
new file mode 100644
index 0000000000..a8c042404e
--- /dev/null
+++ b/src/pkg/dashboard/api_repo_item_decide_delegated_plan_rule.go
@@ -0,0 +1,22 @@
+package dashboard
+
+import (
+ "strings"
+
+ "github.com/hivecommons/hive/pkg/delegatedecision"
+)
+
+// delegatedPlanRule is the rule that decided, in plain words, and its whole
+// reason with issue references stripped; the reason is left out when it
+// says no more than the dialog's one-line Why.
+func delegatedPlanRule(in delegatedecision.Input, d delegatedecision.Decision, why string) (rule, rationale string) {
+ if d.Rule != "" {
+ rule = delegatedecision.PlainOn(d.Rule, in.Kind)
+ }
+ rationale = strings.TrimSpace(delegatedPlanIssueRef.ReplaceAllString(strings.TrimSpace(d.Rationale), ""))
+ rationale = strings.Join(strings.Fields(rationale), " ")
+ if strings.EqualFold(strings.TrimSuffix(rationale, "."), strings.TrimSuffix(strings.TrimSpace(why), ".")) {
+ rationale = ""
+ }
+ return rule, rationale
+}
diff --git a/src/pkg/dashboard/api_repo_item_decide_delegated_plan_saw_test.go b/src/pkg/dashboard/api_repo_item_decide_delegated_plan_saw_test.go
new file mode 100644
index 0000000000..03ffff550f
--- /dev/null
+++ b/src/pkg/dashboard/api_repo_item_decide_delegated_plan_saw_test.go
@@ -0,0 +1,78 @@
+package dashboard
+
+import (
+ "encoding/json"
+ "net/http"
+ "strings"
+ "testing"
+
+ "github.com/hivecommons/hive/pkg/delegatedecision"
+)
+
+// The preview carries what the rules read ("What hive saw"), the rule that
+// decided with its whole reason, and each ruled-out option with the fact
+// that ruled it out, so the owner can check the decision, not just its
+// one-line reason.
+func TestDelegatedDecisionPlanShowsWhatHiveSaw(t *testing.T) {
+ mock := &repoItemDecisionMock{prForeign: true, prLabels: []string{"stage/085-needs-decision", "needs-human"}}
+ srv := newDelegatedServer(t, mock)
+ srv.deps.Config.Governor.Labels.Stage.Adoption.Enabled = boolPtr(true)
+ body := `{"type":"pr","reason":"adoption-stalled:contributor-offline","caption":"adoption stalled"}`
+ w := postDelegatedPlan(t, srv, 8, "writer", body, map[string]string{"X-Hive-Role": "merger"})
+ if w.Code != http.StatusOK {
+ t.Fatalf("code=%d body=%s", w.Code, w.Body.String())
+ }
+ var plan delegatedDecisionPlan
+ if err := json.Unmarshal(w.Body.Bytes(), &plan); err != nil {
+ t.Fatal(err)
+ }
+ saw := map[string]delegatedecision.Fact{}
+ for _, f := range plan.Saw {
+ saw[f.Label] = f
+ }
+ for _, label := range []string{"Author", "Contributor", "CI", "Conflicts", "Sign-off", "Review", "Sentinel"} {
+ if _, ok := saw[label]; !ok {
+ t.Errorf("What hive saw has no %q line: %+v", label, plan.Saw)
+ }
+ }
+ if f := saw["Contributor"]; !strings.Contains(f.Value, "since the nudge") {
+ t.Errorf("Contributor = %+v, want the offline fact the adopt decision rests on", f)
+ }
+ if plan.RulePlain == "" || plan.RulePlain == plan.Rule {
+ t.Errorf("rule_plain = %q for rule %q, want plain words", plan.RulePlain, plan.Rule)
+ }
+ if strings.Contains(plan.Rationale, "hivecommons/hive#") {
+ t.Errorf("rationale keeps issue references: %q", plan.Rationale)
+ }
+ if plan.Ladder == nil || len(plan.WhyNot) != len(plan.Ladder.RuledOut) {
+ t.Fatalf("why_not = %+v for ladder %+v", plan.WhyNot, plan.Ladder)
+ }
+ found := false
+ for _, wn := range plan.WhyNot {
+ if wn.Option == "Approve as it is" {
+ found = wn.Because != ""
+ }
+ }
+ if !found {
+ t.Errorf("why_not does not say why approving as it is was ruled out: %+v", plan.WhyNot)
+ }
+ var raw map[string]json.RawMessage
+ _ = json.Unmarshal(w.Body.Bytes(), &raw)
+ for _, key := range []string{"saw", "rule_plain", "why_not"} {
+ if _, ok := raw[key]; !ok {
+ t.Errorf("plan JSON has no %q", key)
+ }
+ }
+}
+
+func TestDelegatedPlanRuleDropsARationaleTheWhyAlreadySays(t *testing.T) {
+ in := delegatedecision.Input{Kind: delegatedecision.KindPR}
+ d := delegatedecision.Decision{Rule: delegatedecision.RuleMergeableAsIs, Rationale: "a mergeable, green head needs no adoption; the merge queue takes it (hivecommons/hive#15289)"}
+ rule, rationale := delegatedPlanRule(in, d, "Mergeable and green.")
+ if rule == "" || rationale != "a mergeable, green head needs no adoption; the merge queue takes it" {
+ t.Fatalf("rule %q rationale %q", rule, rationale)
+ }
+ if _, r := delegatedPlanRule(in, delegatedecision.Decision{Rationale: "CI is red."}, "CI is red."); r != "" {
+ t.Fatalf("a rationale equal to the why is repeated: %q", r)
+ }
+}
diff --git a/src/pkg/dashboard/stage_tracker_delegate_plan_saw_test.go b/src/pkg/dashboard/stage_tracker_delegate_plan_saw_test.go
new file mode 100644
index 0000000000..9d2fb1a33b
--- /dev/null
+++ b/src/pkg/dashboard/stage_tracker_delegate_plan_saw_test.go
@@ -0,0 +1,68 @@
+package dashboard
+
+import (
+ "strings"
+ "testing"
+)
+
+// The "Let hive decide" preview keeps its visible budget (one sentence, one
+// why, two "then" items) and puts what the rules read under Details: "What
+// hive saw" with each fact marked by its effect, the rule that decided and
+// its whole reason, and each ruled-out option with the fact that ruled it
+// out (owner: "more information in that pop up dialog, specifically why
+// hive would do what it wants to do").
+func TestStageTrackerDelegatePlanDetailsShowWhatHiveSaw(t *testing.T) {
+ html := indexHTML(t)
+ for _, want := range []string{`.ham-plan-saw {`, `.ham-plan-fact[data-state="blocks"] .ham-plan-fact-mark {`, `.ham-plan-sr {`} {
+ if !strings.Contains(html, want) {
+ t.Errorf("index.html missing %q", want)
+ }
+ }
+ runStageTrackerRowActionsScript(t, stageTrackerRowActionsPreamble(t, html)+stageTrackerConfirmOptOutJS(t, html)+`
+const visibleOf = html => stageTrackerDelegatePlanVisibleText(html);
+const detailsOf = html => (html.match(//) || [''])[0];
+const base = { ref: 'o/r#15219', number: 15219, type: 'pr', title: 'fix the thing', would: 'adopt-supersede', rule: 'contributor-offline',
+ summary: 'Re-open #15219 as hive\'s own PR with the same commits and merge that; close #15219 as superseded.', why: 'Their clanker is offline.',
+ consequences: ['Hive opens its copy of #15219, lets it soak, and merges it.', '#15219 is closed as superseded; the author keeps the credit.'],
+ ladder: { decision: 'contributor-offline', reason: 'offline', ruled_out: ['already-fixed: no merged PR has closed this PR\'s issue', 'mergeable-as-is: conflicting, CI not green'] },
+ mergeable_as_is: false, alternatives: [] };
+const withSaw = Object.assign({}, base, {
+ saw: [
+ { label: 'Author', value: '@Karibhou, not trusted', state: 'info' },
+ { label: 'CI', value: 'not green', state: 'blocks' },
+ { label: 'Sign-off', value: 'signed off', state: 'ok' },
+ { label: 'Question for a person', value: '
', state: 'weird' },
+ ],
+ rule_plain: 'the contributor is offline; adopted in supersede mode',
+ rationale: 'the author\'s clanker hasn\'t been connected since the nudge; adoption in supersede mode keeps the work moving',
+ why_not: [{ option: 'Close as already fixed', because: 'no merged PR has closed this PR\'s issue' }, { option: 'Approve as it is', because: 'conflicting, CI not green' }],
+});
+
+// The visible part is exactly what it was without the new fields.
+const before = stageTrackerDelegatePlanHtml(stageTrackerDelegatePlanView([base], ''));
+const after = stageTrackerDelegatePlanHtml(stageTrackerDelegatePlanView([withSaw], ''));
+assert.strictEqual(visibleOf(after), visibleOf(before), 'the visible budget is unchanged');
+assert.ok(!visibleOf(after).includes('What hive saw'), 'What hive saw is under Details');
+
+const details = detailsOf(after);
+assert.ok(details.includes('What hive saw
'), details);
+assert.ok(details.includes('✗ CI not green (holds it back)'), details);
+assert.ok(details.includes('data-state="ok">✓ Sign-off signed off (fine)'), details);
+assert.ok(details.includes('data-state="info">• Author @Karibhou, not trusted'), details);
+// An unknown state renders as info, and every value is escaped.
+assert.ok(details.includes('data-state="info">• Question for a person <img src=x onerror=alert(1)>'), details);
+assert.ok(!after.includes('
Rule the contributor is offline; adopted in supersede mode
'), details);
+assert.ok(details.includes('the author's clanker') || details.includes('
the author's clanker') || details.includes("
the author's clanker"), details);
+// Ruled-out options read as choices with their reason, not rung slugs.
+assert.ok(details.includes('
Approve as it is — conflicting, CI not green') && !details.includes('mergeable-as-is:'), details);
+assert.ok(details.indexOf('What hive saw') < details.indexOf('Why not the others') && details.indexOf('Why not the others') < details.indexOf('Rails:'), 'order: what hive saw, why not the others, rails');
+
+// A plan from an older server (no why_not) keeps the raw ruled-out lines.
+assert.ok(detailsOf(before).includes('mergeable-as-is: conflicting, CI not green') && !detailsOf(before).includes('What hive saw'), detailsOf(before));
+
+// A batch labels each item's facts with its reference.
+const batch = stageTrackerDelegatePlanHtml(stageTrackerDelegatePlanView([withSaw, Object.assign({}, withSaw, { ref: 'o/r#9', number: 9 })], ''));
+assert.ok(detailsOf(batch).includes('What hive saw · o/r#15219') && detailsOf(batch).includes('What hive saw · o/r#9'), detailsOf(batch));
+`)
+}
diff --git a/src/pkg/dashboard/static-src/css/tracker.css b/src/pkg/dashboard/static-src/css/tracker.css
index e44bef15fe..31cf846141 100644
--- a/src/pkg/dashboard/static-src/css/tracker.css
+++ b/src/pkg/dashboard/static-src/css/tracker.css
@@ -552,6 +552,16 @@
.ham-plan-details .ham-plan-label { margin-top: var(--sp-4); }
.ham-plan-finding { color: var(--status-error); white-space: pre-line; }
.ham-plan-ruled-out { padding-left: 1.4em; }
+ /* What hive saw: one fact per line, marked by its effect on the item. */
+ .ham-plan-saw { list-style: none; margin: var(--sp-1) 0 0; padding: 0; }
+ .ham-plan-fact + .ham-plan-fact { margin-top: var(--sp-1); }
+ .ham-plan-fact-mark { display: inline-block; width: 1.2em; text-align: center; font-weight: var(--fw-semibold); }
+ .ham-plan-fact[data-state="ok"] .ham-plan-fact-mark { color: var(--status-ok); }
+ .ham-plan-fact[data-state="blocks"] .ham-plan-fact-mark { color: var(--status-error); }
+ .ham-plan-fact-label { color: var(--text); font-weight: var(--fw-semibold); margin-right: var(--sp-2); }
+ .ham-plan-rule .ham-plan-label { margin-right: var(--sp-2); }
+ .ham-plan-sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
+ .ham-plan-rationale { color: var(--muted); }
.ham-plan-rails { font-size: var(--fs-xs); color: var(--text-faint); }
/* The preview opens as a skeleton while the plan is gathered
(hivecommons/hive 15773): placeholder lines breathe gently, and stand
diff --git a/src/pkg/dashboard/static-src/js/tracker-actions.js b/src/pkg/dashboard/static-src/js/tracker-actions.js
index 6f87c8840a..80088bbc04 100644
--- a/src/pkg/dashboard/static-src/js/tracker-actions.js
+++ b/src/pkg/dashboard/static-src/js/tracker-actions.js
@@ -1639,8 +1639,11 @@
}
// Pure: one view model for every decision the preview can show — a
// PR or an issue; direction, adopt, close, approve, recommend-only.
- // { title, subject, finding, decisions: [{ ref, sentence, why, next[] }],
+ // { title, subject, finding, decisions: [{ ref, sentence, why, next[], saw[], rule, rationale }],
// ruledOut[], rails, mergeable, mergeWhy, mergeAction, mergeLabel, danger }
+ // saw is the plan's "What hive saw" facts ({label, value, state}); rule
+ // and rationale are the rule that decided and its whole reason. All three
+ // sit under Details, so the visible budget is unchanged.
function stageTrackerDelegatePlanView(plans, sentinel) {
plans = plans || [];
// One item: "repo#N · title"; a batch names each item on its own
@@ -1655,8 +1658,16 @@
sentence: stageTrackerPlanSentence(pl),
why: pl.why ? String(pl.why).trim() : '',
next: (pl.consequences || []).slice(0, STAGE_TRACKER_PLAN_NEXT_MAX).map(String),
+ saw: (pl.saw || []).filter(f => f && f.label).map(f => ({ label: String(f.label), value: String(f.value || ''), state: f.state === 'ok' || f.state === 'blocks' ? f.state : 'info' })),
+ rule: pl.rule_plain ? String(pl.rule_plain).trim() : '',
+ rationale: pl.rationale ? String(pl.rationale).trim() : '',
}));
- const ruledOut = [].concat(...plans.map(pl => (pl.ladder && pl.ladder.ruled_out) || []));
+ // Each ruled-out option with the fact that ruled it out ("Approve as
+ // it is — CI not green"); the ladder's raw "rung: reason" when the
+ // plan predates why_not.
+ const ruledOut = [].concat(...plans.map(pl => (pl.why_not && pl.why_not.length)
+ ? pl.why_not.map(w => w.because ? w.option + ' — ' + w.because : w.option)
+ : ((pl.ladder && pl.ladder.ruled_out) || [])));
const mergeable = stageTrackerDelegatePlanMergeable(plans);
return {
title: STAGE_TRACKER_PLAN_TITLE,
@@ -1688,8 +1699,23 @@
+ (d.next.length ? 'Then
' + d.next.map(n => '- ' + esc(n) + '
').join('') + '
' : '')
+ '';
}).join('');
+ // What hive saw: every fact the rules read, marked ✓ (does not hold it
+ // back), ✗ (holds it back) or • (steers the decision); then the rule
+ // that decided and its whole reason.
+ const marks = { ok: ['✓', 'fine'], blocks: ['✗', 'holds it back'], info: ['•', ''] };
+ const saw = view.decisions.map(d => {
+ if (!d.saw.length && !d.rule && !d.rationale) return '';
+ const multi = view.decisions.length > 1;
+ return ''
+ + '
What hive saw' + (multi ? ' · ' + esc(d.ref) : '') + '
'
+ + (d.saw.length ? '
' + d.saw.map(f => '- ' + marks[f.state][0] + ' ' + esc(f.label) + ' ' + esc(f.value) + (marks[f.state][1] ? ' (' + marks[f.state][1] + ')' : '') + '
').join('') + '
' : '')
+ + (d.rule ? '
Rule ' + esc(d.rule) + '
' : '')
+ + (d.rationale ? '
' + esc(d.rationale) + '
' : '')
+ + '
';
+ }).filter(Boolean);
const details = []
.concat(view.finding ? ['' + esc(view.finding) + '
'] : [])
+ .concat(saw)
.concat(view.ruledOut.length ? ['Why not the others
' + view.ruledOut.map(r => '- ' + esc(r) + '
').join('') + '
'] : [])
.concat(['' + esc(view.rails) + '
']);
return '' + esc(view.title) + '
'
diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html
index a84ad8b426..0ffb032b27 100644
--- a/src/pkg/dashboard/static/index.html
+++ b/src/pkg/dashboard/static/index.html
@@ -1894,6 +1894,16 @@
.ham-plan-details .ham-plan-label { margin-top: var(--sp-4); }
.ham-plan-finding { color: var(--status-error); white-space: pre-line; }
.ham-plan-ruled-out { padding-left: 1.4em; }
+ /* What hive saw: one fact per line, marked by its effect on the item. */
+ .ham-plan-saw { list-style: none; margin: var(--sp-1) 0 0; padding: 0; }
+ .ham-plan-fact + .ham-plan-fact { margin-top: var(--sp-1); }
+ .ham-plan-fact-mark { display: inline-block; width: 1.2em; text-align: center; font-weight: var(--fw-semibold); }
+ .ham-plan-fact[data-state="ok"] .ham-plan-fact-mark { color: var(--status-ok); }
+ .ham-plan-fact[data-state="blocks"] .ham-plan-fact-mark { color: var(--status-error); }
+ .ham-plan-fact-label { color: var(--text); font-weight: var(--fw-semibold); margin-right: var(--sp-2); }
+ .ham-plan-rule .ham-plan-label { margin-right: var(--sp-2); }
+ .ham-plan-sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
+ .ham-plan-rationale { color: var(--muted); }
.ham-plan-rails { font-size: var(--fs-xs); color: var(--text-faint); }
/* The preview opens as a skeleton while the plan is gathered
(hivecommons/hive 15773): placeholder lines breathe gently, and stand
@@ -24461,8 +24471,11 @@ All labels
}
// Pure: one view model for every decision the preview can show — a
// PR or an issue; direction, adopt, close, approve, recommend-only.
- // { title, subject, finding, decisions: [{ ref, sentence, why, next[] }],
+ // { title, subject, finding, decisions: [{ ref, sentence, why, next[], saw[], rule, rationale }],
// ruledOut[], rails, mergeable, mergeWhy, mergeAction, mergeLabel, danger }
+ // saw is the plan's "What hive saw" facts ({label, value, state}); rule
+ // and rationale are the rule that decided and its whole reason. All three
+ // sit under Details, so the visible budget is unchanged.
function stageTrackerDelegatePlanView(plans, sentinel) {
plans = plans || [];
// One item: "repo#N · title"; a batch names each item on its own
@@ -24477,8 +24490,16 @@ All labels
sentence: stageTrackerPlanSentence(pl),
why: pl.why ? String(pl.why).trim() : '',
next: (pl.consequences || []).slice(0, STAGE_TRACKER_PLAN_NEXT_MAX).map(String),
+ saw: (pl.saw || []).filter(f => f && f.label).map(f => ({ label: String(f.label), value: String(f.value || ''), state: f.state === 'ok' || f.state === 'blocks' ? f.state : 'info' })),
+ rule: pl.rule_plain ? String(pl.rule_plain).trim() : '',
+ rationale: pl.rationale ? String(pl.rationale).trim() : '',
}));
- const ruledOut = [].concat(...plans.map(pl => (pl.ladder && pl.ladder.ruled_out) || []));
+ // Each ruled-out option with the fact that ruled it out ("Approve as
+ // it is — CI not green"); the ladder's raw "rung: reason" when the
+ // plan predates why_not.
+ const ruledOut = [].concat(...plans.map(pl => (pl.why_not && pl.why_not.length)
+ ? pl.why_not.map(w => w.because ? w.option + ' — ' + w.because : w.option)
+ : ((pl.ladder && pl.ladder.ruled_out) || [])));
const mergeable = stageTrackerDelegatePlanMergeable(plans);
return {
title: STAGE_TRACKER_PLAN_TITLE,
@@ -24510,8 +24531,23 @@ All labels
+ (d.next.length ? 'Then
' + d.next.map(n => '- ' + esc(n) + '
').join('') + '
' : '')
+ '';
}).join('');
+ // What hive saw: every fact the rules read, marked ✓ (does not hold it
+ // back), ✗ (holds it back) or • (steers the decision); then the rule
+ // that decided and its whole reason.
+ const marks = { ok: ['✓', 'fine'], blocks: ['✗', 'holds it back'], info: ['•', ''] };
+ const saw = view.decisions.map(d => {
+ if (!d.saw.length && !d.rule && !d.rationale) return '';
+ const multi = view.decisions.length > 1;
+ return ''
+ + '
What hive saw' + (multi ? ' · ' + esc(d.ref) : '') + '
'
+ + (d.saw.length ? '
' + d.saw.map(f => '- ' + marks[f.state][0] + ' ' + esc(f.label) + ' ' + esc(f.value) + (marks[f.state][1] ? ' (' + marks[f.state][1] + ')' : '') + '
').join('') + '
' : '')
+ + (d.rule ? '
Rule ' + esc(d.rule) + '
' : '')
+ + (d.rationale ? '
' + esc(d.rationale) + '
' : '')
+ + '
';
+ }).filter(Boolean);
const details = []
.concat(view.finding ? ['' + esc(view.finding) + '
'] : [])
+ .concat(saw)
.concat(view.ruledOut.length ? ['Why not the others
' + view.ruledOut.map(r => '- ' + esc(r) + '
').join('') + '
'] : [])
.concat(['' + esc(view.rails) + '
']);
return '' + esc(view.title) + '
'
diff --git a/src/pkg/delegatedecision/facts.go b/src/pkg/delegatedecision/facts.go
new file mode 100644
index 0000000000..c1bb14be2d
--- /dev/null
+++ b/src/pkg/delegatedecision/facts.go
@@ -0,0 +1,223 @@
+package delegatedecision
+
+import (
+ "strconv"
+ "strings"
+)
+
+// Fact is one thing the delegate read about an item, in plain words. The
+// "Let hive decide" preview lists them under "What hive saw" so the owner
+// can check the decision against its inputs instead of taking the one-line
+// reason on trust.
+type Fact struct {
+ Label string `json:"label"`
+ Value string `json:"value"`
+ // State is FactOK when the fact does not hold the item back,
+ // FactBlocks when it does, and FactInfo when it only steers which
+ // decision is made.
+ State string `json:"state"`
+}
+
+// Fact states.
+const (
+ FactOK = "ok"
+ FactBlocks = "blocks"
+ FactInfo = "info"
+)
+
+// Facts lists what the decision rules read from in, in the order an owner
+// checks them: who wrote it, whether the head can merge, what review and
+// Sentinel said, then whatever else steered the decision. Only facts the
+// rules use are listed, and a fact that does not apply to the item's kind
+// is left out.
+func (in Input) Facts() []Fact {
+ var out []Fact
+ add := func(label, value, state string) { out = append(out, Fact{Label: label, Value: value, State: state}) }
+ pr := in.Kind == KindPR
+
+ author := "unknown"
+ if a := strings.TrimSpace(in.Author); a != "" {
+ author = "@" + a
+ }
+ switch {
+ case in.HiveAuthored:
+ add("Author", "the hive", FactInfo)
+ case in.OwnerAuthor:
+ add("Author", author+", an owner of this hive", FactInfo)
+ case in.TrustedAuthor:
+ add("Author", author+", trusted (write access)", FactInfo)
+ default:
+ add("Author", author+", not trusted", FactInfo)
+ }
+ if pr && !in.HiveAuthored && !in.PersonAuthored() {
+ who := in.AuthorWord()
+ switch {
+ case in.ReworkPickedUp:
+ add("Contributor", who+" has picked the rework up", FactInfo)
+ case in.ContributorOnline:
+ add("Contributor", who+" is connected", FactInfo)
+ default:
+ add("Contributor", in.OfflineWording(), FactInfo)
+ }
+ }
+
+ if pr {
+ switch {
+ case in.CIGreen:
+ add("CI", "green", FactOK)
+ case in.CIPending:
+ add("CI", "still running, nothing failed", FactInfo)
+ default:
+ add("CI", "not green", FactBlocks)
+ }
+ if in.Conflicting {
+ add("Conflicts", "conflicts with the base branch", FactBlocks)
+ } else {
+ add("Conflicts", "none", FactOK)
+ }
+ if in.DCOMissing {
+ add("Sign-off", "DCO sign-off missing", FactBlocks)
+ } else {
+ add("Sign-off", "signed off", FactOK)
+ }
+ switch {
+ case in.ChangeRequest() != "":
+ add("Review", in.ChangeRequest()+" still stand", FactBlocks)
+ case in.HeadNeedsPerson():
+ add("Review", "the hive's review asks a person to decide", FactBlocks)
+ case strings.TrimSpace(in.HeadReviewVerdict) != "":
+ add("Review", "the hive's review on this head: "+strings.ReplaceAll(strings.TrimSpace(in.HeadReviewVerdict), "_", " "), FactOK)
+ default:
+ add("Review", "no review verdict on this head", FactInfo)
+ }
+ if f := strings.TrimSpace(in.ReviewerFinding); f != "" {
+ if in.SecurityFinding {
+ f += " (security review)"
+ }
+ add("Review finding", f, FactBlocks)
+ }
+ }
+
+ if in.SentinelAlert {
+ reason := strings.TrimSpace(in.SentinelReason)
+ if reason == "" {
+ reason = "flagged security-relevant changes"
+ }
+ add("Sentinel", reason, FactBlocks)
+ } else {
+ add("Sentinel", "no alert", FactOK)
+ }
+
+ if pr {
+ var shape []string
+ if in.Small {
+ shape = append(shape, "small (size XS or S)")
+ }
+ if in.LowRiskPaths {
+ shape = append(shape, "only CI config, workflow, docs, text or read-only RBAC files")
+ }
+ if in.DiffEmpty {
+ shape = append(shape, "empty against the base branch")
+ }
+ if len(shape) > 0 {
+ add("Change", strings.Join(shape, "; "), FactInfo)
+ }
+ if in.WorkflowPath {
+ if in.WorkflowsPushable {
+ add("Workflow files", "edits .github/workflows; the hive can push them here", FactInfo)
+ } else {
+ add("Workflow files", "edits .github/workflows; the hive cannot push them here", FactBlocks)
+ }
+ }
+ if c := in.SupersededBy; c != nil && c.PR > 0 {
+ add("Already landed", SupersededText(*c), FactInfo)
+ }
+ }
+
+ if in.DuplicateOf > 0 {
+ add("Duplicate", "duplicates #"+strconv.Itoa(in.DuplicateOf), FactInfo)
+ }
+ if len(in.Overlaps) > 0 {
+ add("Overlaps", refList(in.Overlaps), FactInfo)
+ }
+ var others []int
+ for _, c := range in.Competing {
+ if !c.Current && c.Number != in.Number {
+ others = append(others, c.Number)
+ }
+ }
+ if len(others) > 0 {
+ add("Other PRs for the same work", refList(others), FactInfo)
+ }
+ if in.TrainDuplicateOf > 0 {
+ add("Merge queue", "held as a duplicate of #"+strconv.Itoa(in.TrainDuplicateOf), FactBlocks)
+ }
+ if in.ClaimConflictWith > 0 {
+ add("Merge queue", "#"+strconv.Itoa(in.ClaimConflictWith)+" claims the same issue", FactBlocks)
+ }
+
+ if pr {
+ switch {
+ case strings.TrimSpace(in.AdoptedPushRefused) != "":
+ add("Adoption", "the hive cannot push this branch: "+strings.TrimSpace(in.AdoptedPushRefused), FactBlocks)
+ case in.AdoptedByHive:
+ add("Adoption", "adopted by the hive; its fixer owns the branch", FactInfo)
+ case in.AdoptionStalled:
+ add("Adoption", "adoption stalled on a lane blocker", FactBlocks)
+ case in.AdoptionGraceElapsed:
+ add("Adoption", "the offline grace has run out", FactInfo)
+ }
+ if in.ReporterTrustHold {
+ add("Reporter trust", "the reporter-trust gate holds this fix", FactBlocks)
+ }
+ }
+ if in.RepoPaused {
+ add("Repository", "paused by the operator; the hive only recommends", FactInfo)
+ }
+ if q := strings.TrimSpace(in.Question); q != "" {
+ add("Question for a person", q, FactInfo)
+ }
+ return out
+}
+
+func refList(ns []int) string {
+ refs := make([]string, len(ns))
+ for i, n := range ns {
+ refs[i] = "#" + strconv.Itoa(n)
+ }
+ return strings.Join(refs, ", ")
+}
+
+// WhyNot is one option the ladder ruled out and the fact that ruled it out.
+type WhyNot struct {
+ Option string `json:"option"`
+ Because string `json:"because"`
+}
+
+// rungOptions names each ladder rung as the option an owner would have
+// picked by hand.
+var rungOptions = map[string]string{
+ RuleAlreadyFixed: "Close as already fixed",
+ RuleMergeableAsIs: "Approve as it is",
+ RuleRebaseThenMerge: "Rebase, then merge",
+ RuleReturnToContributor: "Send it back to the contributor",
+ RuleContributorOffline: "Adopt it",
+}
+
+// WhyNot turns RuledOut ("rung: reason") into the options it ruled out, in
+// the owner's words. Nil for a nil ladder.
+func (l *Ladder) WhyNot() []WhyNot {
+ if l == nil {
+ return nil
+ }
+ out := make([]WhyNot, 0, len(l.RuledOut))
+ for _, r := range l.RuledOut {
+ rung, because, _ := strings.Cut(r, ": ")
+ option, ok := rungOptions[rung]
+ if !ok {
+ option = Plain(rung)
+ }
+ out = append(out, WhyNot{Option: option, Because: strings.TrimSpace(because)})
+ }
+ return out
+}
diff --git a/src/pkg/delegatedecision/facts_test.go b/src/pkg/delegatedecision/facts_test.go
new file mode 100644
index 0000000000..cfb16892f1
--- /dev/null
+++ b/src/pkg/delegatedecision/facts_test.go
@@ -0,0 +1,129 @@
+package delegatedecision
+
+import (
+ "strings"
+ "testing"
+)
+
+func factMap(fs []Fact) map[string]Fact {
+ m := map[string]Fact{}
+ for _, f := range fs {
+ m[f.Label] = f
+ }
+ return m
+}
+
+func TestFactsGreenContributorPR(t *testing.T) {
+ in := Input{Kind: KindPR, Number: 8, Author: "k", TrustedAuthor: true, CIGreen: true, ContributorOnline: true, AuthorTooling: AuthorToolingClanker, Small: true, HeadReviewVerdict: "approve"}
+ m := factMap(in.Facts())
+ want := map[string]Fact{
+ "Author": {"Author", "@k, trusted (write access)", FactInfo},
+ "Contributor": {"Contributor", "the author's clanker is connected", FactInfo},
+ "CI": {"CI", "green", FactOK},
+ "Conflicts": {"Conflicts", "none", FactOK},
+ "Sign-off": {"Sign-off", "signed off", FactOK},
+ "Review": {"Review", "the hive's review on this head: approve", FactOK},
+ "Sentinel": {"Sentinel", "no alert", FactOK},
+ "Change": {"Change", "small (size XS or S)", FactInfo},
+ }
+ for label, f := range want {
+ if m[label] != f {
+ t.Errorf("%s = %+v, want %+v", label, m[label], f)
+ }
+ }
+ for _, f := range in.Facts() {
+ if f.State == FactBlocks {
+ t.Errorf("a green, signed-off, conflict-free head lists a blocker: %+v", f)
+ }
+ }
+}
+
+func TestFactsBlockedPRNamesEveryBlocker(t *testing.T) {
+ in := Input{Kind: KindPR, Number: 15219, Author: "Karibhou", AuthorTooling: AuthorToolingClanker,
+ Conflicting: true, DCOMissing: true, SentinelAlert: true, SentinelReason: "changes 1 sensitive path(s)",
+ ChangesRequestedBy: []string{"maint"}, WorkflowPath: true, Question: "Should this land before the release?",
+ Competing: []CompetingPR{{Number: 15219, Current: true}, {Number: 15240}}}
+ m := factMap(in.Facts())
+ blocks := map[string]string{
+ "CI": "not green",
+ "Conflicts": "conflicts with the base branch",
+ "Sign-off": "DCO sign-off missing",
+ "Review": "the changes @maint requested on GitHub still stand",
+ "Sentinel": "changes 1 sensitive path(s)",
+ "Workflow files": "edits .github/workflows; the hive cannot push them here",
+ }
+ for label, value := range blocks {
+ if f := m[label]; f.Value != value || f.State != FactBlocks {
+ t.Errorf("%s = %+v, want %q holding it back", label, f, value)
+ }
+ }
+ if f := m["Contributor"]; f.Value != "the author's clanker hasn't been connected since the nudge" {
+ t.Errorf("Contributor = %+v", f)
+ }
+ if f := m["Author"]; f.Value != "@Karibhou, not trusted" {
+ t.Errorf("Author = %+v", f)
+ }
+ if f := m["Other PRs for the same work"]; f.Value != "#15240" {
+ t.Errorf("competing = %+v, want only the other PR", f)
+ }
+ if f := m["Question for a person"]; f.Value != in.Question {
+ t.Errorf("question = %+v", f)
+ }
+}
+
+func TestFactsPendingCIIsNotABlocker(t *testing.T) {
+ m := factMap(Input{Kind: KindPR, CIPending: true}.Facts())
+ if f := m["CI"]; f.State != FactInfo || !strings.Contains(f.Value, "still running") {
+ t.Fatalf("CI = %+v, want still running, not a blocker", f)
+ }
+}
+
+func TestFactsIssueListsNoHeadFacts(t *testing.T) {
+ in := Input{Kind: KindIssue, Number: 42, Author: "reporter", DuplicateOf: 7, Overlaps: []int{9, 11}, RepoPaused: true}
+ m := factMap(in.Facts())
+ for _, label := range []string{"CI", "Conflicts", "Sign-off", "Review", "Contributor", "Change"} {
+ if _, ok := m[label]; ok {
+ t.Errorf("an issue lists the PR fact %q", label)
+ }
+ }
+ if m["Duplicate"].Value != "duplicates #7" || m["Overlaps"].Value != "#9, #11" || m["Repository"].State != FactInfo {
+ t.Fatalf("issue facts = %+v", in.Facts())
+ }
+}
+
+func TestFactsHiveAndPersonPRsHaveNoContributorLine(t *testing.T) {
+ for _, in := range []Input{{Kind: KindPR, HiveAuthored: true}, {Kind: KindPR, HumanAuthor: true, Author: "dev"}} {
+ if _, ok := factMap(in.Facts())["Contributor"]; ok {
+ t.Errorf("%+v lists a contributor reachability line", in)
+ }
+ }
+}
+
+func TestLadderWhyNotNamesTheOptions(t *testing.T) {
+ in := Input{Kind: KindPR, Number: 15219, Author: "k", AuthorTooling: AuthorToolingClanker, Conflicting: true}
+ d, ok := decideLadder(in, "#15219")
+ if !ok || d.Ladder == nil {
+ t.Fatalf("ladder did not decide: %+v", d)
+ }
+ got := d.Ladder.WhyNot()
+ if len(got) != len(d.Ladder.RuledOut) {
+ t.Fatalf("WhyNot = %+v for %v", got, d.Ladder.RuledOut)
+ }
+ byOption := map[string]string{}
+ for _, w := range got {
+ byOption[w.Option] = w.Because
+ }
+ if byOption["Close as already fixed"] != "no merged PR has closed this PR's issue" {
+ t.Errorf("already-fixed = %q", byOption["Close as already fixed"])
+ }
+ if b := byOption["Approve as it is"]; !strings.Contains(b, "conflicting") || !strings.Contains(b, "CI not green") {
+ t.Errorf("mergeable-as-is = %q, want the blockers", b)
+ }
+ if (*Ladder)(nil).WhyNot() != nil {
+ t.Error("a nil ladder has no why-not")
+ }
+ unknown := (&Ladder{RuledOut: []string{"some-new-rung: because"}}).WhyNot()
+ if unknown[0].Option != "some new rung" || unknown[0].Because != "because" {
+ t.Errorf("unknown rung = %+v", unknown)
+ }
+}