diff --git a/changelog.d/fixed-decision-unpark-stage.md b/changelog.d/fixed-decision-unpark-stage.md new file mode 100644 index 0000000000..f27c20f9cc --- /dev/null +++ b/changelog.d/fixed-decision-unpark-stage.md @@ -0,0 +1 @@ +- A trusted merger's `/hive decision` on a hive-authored PR parked at `stage/085-needs-decision` now moves the PR: the whole comment (not just its first line) is recorded as the instruction and quoted verbatim in the fix kick, a decision on the current head supersedes the swarm's decision-requested verdict so the PR derives `stage/070-fixing` in the same pass as the acknowledgement, a bare `/hive decision approve` is recorded as an approval that releases requires_human instead of kicking a fix that says "approve", and an acknowledged decision whose record did not survive a restart is rebuilt from the comment thread ([#14679](https://github.com/hivecommons/hive/issues/14679)). diff --git a/src/docs/maintainer-commands.md b/src/docs/maintainer-commands.md index e699977528..aa05348fe6 100644 --- a/src/docs/maintainer-commands.md +++ b/src/docs/maintainer-commands.md @@ -74,6 +74,17 @@ delivered ahead of the governor's own kick to the same agent in that eval cycle, so it does not time out behind routine queue work; a kick that still cannot be sent is logged as `review swarm kick not delivered` with the PR and audited as `review_kick_undelivered`, and the planner re-plans it next cycle. +The whole comment after `/hive decision` is the instruction — numbered points +on the lines below the command are kept and quoted verbatim — and the +decision on the current head outranks the swarm's decision-requested verdict +on that head, so the stage moves in the same pass as the acknowledgement +rather than waiting on a re-review. A bare `/hive decision approve` (nothing +beyond the approval word) is recorded as your answer to the swarm's question +instead: no fix is kicked, requires_human is released for that head and the +PR follows the normal merge path. An acknowledged decision whose record did +not survive a pod restart is rebuilt from the comment thread; a decision +answered for an older head is left alone +([#14679](https://github.com/hivecommons/hive/issues/14679)). The 085 entry comment names both actions. The commenter must hold `write` or better on the repo *and* be in the hive's trusted-merger set (the bar a human approval already meets). `/hive decision` on a PR the hive did **not** open, or `/hive diff --git a/src/pkg/github/automerge/automerge_human_changes_requested.go b/src/pkg/github/automerge/automerge_human_changes_requested.go index 7c471d3ea6..ecc61d8ac8 100644 --- a/src/pkg/github/automerge/automerge_human_changes_requested.go +++ b/src/pkg/github/automerge/automerge_human_changes_requested.go @@ -78,15 +78,24 @@ func (c *Engine) latestTrustedHumanChangesRequested(ctx context.Context, owner, // request already standing in the store for this head — a `/hive decision` // the un-park sweep recorded (pr_unpark_decision.go) — counts the same way, // so the text path reaches 070 through the lane reason like a review does. +// A bare `/hive decision approve` recorded there is not a change request +// (hivecommons/hive#14679). Either way the requester is noted on the stage +// detail so the reviewer's decision-requested verdict on this head stops +// deriving 085. func (c *Engine) humanChangesRequestedForHead(ctx context.Context, owner, repo string, number int, head string) bool { rv, ok := c.latestTrustedHumanChangesRequested(ctx, owner, repo, number, head) if !ok { if c.humanChangeRequests == nil || strings.TrimSpace(head) == "" { return false } - _, standing := c.humanChangeRequests.For(owner+"/"+repo, number, strings.TrimSpace(head)) - return standing + standing, found := c.humanChangeRequests.For(owner+"/"+repo, number, strings.TrimSpace(head)) + if !found || standing.IsApproval() { + return false + } + c.noteStageHumanChangeRequest(owner, repo, number, head, standing.Actor) + return true } + c.noteStageHumanChangeRequest(owner, repo, number, head, hgithub.SafeGetLogin(rv.GetUser())) if c.humanChangeRequests == nil { return true } diff --git a/src/pkg/github/automerge/automerge_human_changes_requested_test.go b/src/pkg/github/automerge/automerge_human_changes_requested_test.go index ea6b5a8a60..bd410cb065 100644 --- a/src/pkg/github/automerge/automerge_human_changes_requested_test.go +++ b/src/pkg/github/automerge/automerge_human_changes_requested_test.go @@ -175,3 +175,56 @@ func TestTrySweepSelfAuthoredPRHonoursRecordedDecision(t *testing.T) { }) } } + +// hivecommons/hive#14679: a recorded `/hive decision` on the current head +// is noted on the stage detail as the standing human change requester, so +// the stage derives fixing over the swarm's decision-requested verdict on +// that head; a bare approval recorded there is not a change request and +// does not hold the lane. +func TestTrySweepSelfAuthoredPRRecordedDecisionNotesStageAndApprovalReleases(t *testing.T) { + for _, tt := range []struct { + name string + kind string + wantReason string + wantRequester string + }{ + {name: "instruction holds the lane and notes the requester", kind: review.HumanChangeRequestKindChanges, wantReason: autoMergeReasonHumanChangesRequested, wantRequester: "bob"}, + {name: "bare approval releases the lane", kind: review.HumanChangeRequestKindApprove}, + } { + t.Run(tt.name, func(t *testing.T) { + api := newSelfSweepGuardAPI(t, selfSweepFixture{mergeApplied: true}) + defer api.Close() + c := newAutoMergeSweepClient(api.URL) + c.stageTracker = NewStageTracker() + c.stageLabelPolicy = func() StageLabelPolicy { return StageLabelPolicy{Enabled: true} } + store := review.NewHumanChangeRequests("") + c.humanChangeRequests = store + if err := store.Record(review.HumanChangeRequest{Repo: "acme/widget", Number: 7, HeadSHA: "sha7", Source: review.HumanChangeRequestSourceDecision, SourceID: 99, Actor: "bob", Body: "approve", Kind: tt.kind}); err != nil { + t.Fatal(err) + } + event, reason, err := c.trySweepSelfAuthoredPR(context.Background(), "acme/widget", "acme", "widget", 7, true) + if err != nil { + t.Fatal(err) + } + if reason != tt.wantReason { + t.Fatalf("reason = %q, want %q", reason, tt.wantReason) + } + c.stageTracker.mu.Lock() + detail := c.stageTracker.details[stageKey("acme", "widget", 7)] + c.stageTracker.mu.Unlock() + if detail.HumanChangeRequester != tt.wantRequester || (tt.wantRequester != "" && detail.HumanChangeRequestHead != "sha7") { + t.Fatalf("stage detail = %+v, want requester %q on sha7", detail, tt.wantRequester) + } + if tt.wantReason == "" && event.MergeSHA != "merge7" { + t.Fatalf("event = %+v, want the merge to proceed over a bare approval", event) + } + if tt.wantReason != "" { + o := stageObservation{Lane: stageLaneSelf, Reason: reason, HeadSHA: "sha7", Detail: detail} + o.Detail.Verdict, o.Detail.VerdictKnown = ContributorLaneVerdict{Configured: true, Verdict: "requires_human", DecisionRequested: true}, true + if v := classifyStage(o); v.Stage != stagelabels.Fixing || v.Reason != autoMergeReasonHumanChangesRequested { + t.Fatalf("stage with the decision-requested verdict = %+v, want 070 on the recorded decision", v) + } + } + }) + } +} diff --git a/src/pkg/github/automerge/automerge_review_gate.go b/src/pkg/github/automerge/automerge_review_gate.go index 9791f6803e..26b6c70ae4 100644 --- a/src/pkg/github/automerge/automerge_review_gate.go +++ b/src/pkg/github/automerge/automerge_review_gate.go @@ -355,5 +355,26 @@ func (c *Engine) trustedHumanApprovalForRequiresHuman(ctx context.Context, owner if !verdictNeedsHuman(stageDetail{Verdict: verdict, VerdictKnown: true}) { return "", false } - return c.latestTrustedHumanApproval(ctx, owner, repo, number, head) + if login, ok := c.latestTrustedHumanApproval(ctx, owner, repo, number, head); ok { + return login, true + } + return c.recordedHumanApprovalForHead(owner, repo, number, head) +} + +// recordedHumanApprovalForHead is a bare `/hive decision approve` the un-park +// sweep recorded against head (pr_unpark_decision.go): the owner answered the +// swarm's question with "yes" in a comment rather than a GitHub review. It +// releases requires_human the way an APPROVED review on the head does +// (hivecommons/hive#14679). +func (c *Engine) recordedHumanApprovalForHead(owner, repo string, number int, head string) (string, bool) { + if c == nil || c.humanChangeRequests == nil || strings.TrimSpace(head) == "" { + return "", false + } + req, ok := c.humanChangeRequests.For(owner+"/"+repo, number, strings.TrimSpace(head)) + if !ok || !req.IsApproval() || strings.TrimSpace(req.Actor) == "" { + return "", false + } + login := strings.ToLower(strings.TrimSpace(req.Actor)) + c.noteStageTrustedHumanApproval(owner, repo, number, head, login) + return login, true } diff --git a/src/pkg/github/automerge/automerge_stage_labels.go b/src/pkg/github/automerge/automerge_stage_labels.go index 7c2d87ee8f..499ba84b66 100644 --- a/src/pkg/github/automerge/automerge_stage_labels.go +++ b/src/pkg/github/automerge/automerge_stage_labels.go @@ -285,6 +285,9 @@ func (t *StageTracker) drain() [][]stageObservation { if detail.HumanApprover != "" && detail.HumanApprovalHead != "" && detail.HumanApprovalHead == o.HeadSHA { o.Detail.HumanApprover, o.Detail.HumanApprovalHead = detail.HumanApprover, detail.HumanApprovalHead } + if detail.HumanChangeRequester != "" && detail.HumanChangeRequestHead != "" && detail.HumanChangeRequestHead == o.HeadSHA { + o.Detail.HumanChangeRequester, o.Detail.HumanChangeRequestHead = detail.HumanChangeRequester, detail.HumanChangeRequestHead + } if detail.Role != stagelabels.RoleNone { o.Detail.Role = detail.Role } @@ -445,6 +448,20 @@ func (c *Engine) noteStageTrustedHumanApproval(owner, repo string, number int, h }) } +// noteStageHumanChangeRequest records that a trusted human's change request +// (review or `/hive decision `) stands against the exact head. Stage +// derivation reads it as "the person answered": the requires_human / +// decision-requested verdict on that head no longer parks the PR at 085 +// (hivecommons/hive#14679). +func (c *Engine) noteStageHumanChangeRequest(owner, repo string, number int, head, login string) { + if !c.stagePolicy().Enabled || strings.TrimSpace(login) == "" || strings.TrimSpace(head) == "" { + return + } + c.stageTrackerOrShared().note(stageKey(owner, repo, number), func(d *stageDetail) { + d.HumanChangeRequester, d.HumanChangeRequestHead = strings.TrimSpace(login), strings.TrimSpace(head) + }) +} + // noteStageRole records the author's admission tier as the lane computed // it. Lanes disagree by design (the contributor lane reports "untrusted" // for a maintainer with no registry profile), so tiers merge by precedence diff --git a/src/pkg/github/issue_unpark_command.go b/src/pkg/github/issue_unpark_command.go index 20bffb0ce2..f133ea02fd 100644 --- a/src/pkg/github/issue_unpark_command.go +++ b/src/pkg/github/issue_unpark_command.go @@ -92,6 +92,30 @@ var fixedCommandTokens = []string{"/fixed", "/close"} type unparkCommand struct { Kind unparkCommandKind Decision string + // Text is the whole decision as the person wrote it: the rest of the + // command line plus every line after it, trimmed. Decision stays the + // first line so the reply's `Decision:` round-trip is unchanged; the PR + // path hands Text to the author agent verbatim (hivecommons/hive#14679). + Text string +} + +// BareApproval reports whether a `/hive decision` carries nothing beyond an +// approval word — the owner answered "yes" without an instruction to act on. +func (c unparkCommand) BareApproval() bool { + switch strings.ToLower(strings.TrimSpace(c.Text)) { + case "approve", "approved", "approve.", "approved.", "lgtm", "yes": + return true + } + return false +} + +// DecisionText is what the author agent should follow: the full comment +// body after the command when it has one, else the first-line decision. +func (c unparkCommand) DecisionText() string { + if t := strings.TrimSpace(c.Text); t != "" { + return t + } + return strings.TrimSpace(c.Decision) } // IssueUnparkEvent records one issue this sweep un-parked, for the audit log. @@ -149,11 +173,14 @@ type IssueUnparkSweepOptions struct { // PullRequestDecisionEvent records one `/hive decision` on a hive-authored // PR the sweep routed to the fix lane (hivecommons/hive#13041). type PullRequestDecisionEvent struct { - Repo string - Number int - HeadSHA string - Actor string - Decision string + Repo string + Number int + HeadSHA string + Actor string + Decision string + // Mode is "changes_requested" (the decision carries an instruction) + // or "approve" (a bare `/hive decision approve`). + Mode string CommentURL string } @@ -933,11 +960,36 @@ func parseUnparkCommand(body string) (unparkCommand, bool) { if decision == "" { return unparkCommand{}, false } - return unparkCommand{Kind: unparkCommandDecision, Decision: decision}, true + return unparkCommand{Kind: unparkCommandDecision, Decision: decision, Text: decisionText(body, decision)}, true } return unparkCommand{}, false } +// decisionText joins the first-line decision with every line that follows +// the command line, so numbered instructions under `/hive decision approve` +// reach the author agent instead of being dropped (hivecommons/hive#14679). +func decisionText(body, firstLine string) string { + lines := strings.Split(body, "\n") + rest := make([]string, 0, len(lines)) + seen := false + for _, line := range lines { + line = strings.TrimRight(strings.TrimSuffix(line, "\r"), " \t") + if !seen { + if strings.TrimSpace(line) == "" { + continue + } + seen = true + continue + } + rest = append(rest, line) + } + tail := strings.TrimSpace(strings.Join(rest, "\n")) + if tail == "" { + return firstLine + } + return strings.TrimSpace(firstLine + "\n\n" + tail) +} + // firstNonEmptyLine returns the comment's first line that has content, // trimmed of surrounding whitespace. func firstNonEmptyLine(body string) string { diff --git a/src/pkg/github/issue_unpark_command_test.go b/src/pkg/github/issue_unpark_command_test.go index 6bb7a0e583..d8b5e4ce1d 100644 --- a/src/pkg/github/issue_unpark_command_test.go +++ b/src/pkg/github/issue_unpark_command_test.go @@ -1241,3 +1241,32 @@ func TestSweepClosedIssueStageLabelsCap(t *testing.T) { t.Fatalf("nil client err = %v, want ErrNoGitHubClient", err) } } + +// hivecommons/hive#14679 (seen on #14628): the owner's `/hive decision +// approve` followed by numbered instructions must reach the author agent +// whole, and a bare approve must read as an approval, not an instruction. +func TestParseUnparkCommandKeepsDecisionTextAfterFirstLine(t *testing.T) { + body := "/hive decision approve\r\n\r\nPlease do the following before merging:\r\n\r\n1. Change `Closes #14605` to `Refs #14605`.\n2. Keep #14605 open.\n3. Merge on green.\n" + cmd, ok := parseUnparkCommand(body) + if !ok || cmd.Kind != unparkCommandDecision || cmd.Decision != "approve" { + t.Fatalf("parseUnparkCommand = %+v, %v", cmd, ok) + } + if cmd.BareApproval() { + t.Fatalf("approve with instructions read as a bare approval: %q", cmd.Text) + } + for _, want := range []string{"approve\n\n", "1. Change `Closes #14605` to `Refs #14605`.", "2. Keep #14605 open.", "3. Merge on green."} { + if !strings.Contains(cmd.DecisionText(), want) { + t.Fatalf("decision text missing %q:\n%s", want, cmd.DecisionText()) + } + } + for _, bare := range []string{"/hive decision approve", "/hive decision Approved\n", "/hive decision approve.\n\n"} { + cmd, ok := parseUnparkCommand(bare) + if !ok || !cmd.BareApproval() || cmd.DecisionText() == "" { + t.Fatalf("parseUnparkCommand(%q) = %+v, %v; want a bare approval", bare, cmd, ok) + } + } + single, _ := parseUnparkCommand("/hive decision keep 10 stable tags") + if single.DecisionText() != "keep 10 stable tags" || single.BareApproval() { + t.Fatalf("single-line decision = %+v", single) + } +} diff --git a/src/pkg/github/pr_decision_operator.go b/src/pkg/github/pr_decision_operator.go index 3b8596f188..ee53c7bfd9 100644 --- a/src/pkg/github/pr_decision_operator.go +++ b/src/pkg/github/pr_decision_operator.go @@ -212,6 +212,7 @@ func (c *Client) RecordOperatorPullRequestDecision(ctx context.Context, repo str if head == "" { return PullRequestDecisionEvent{}, ErrPullRequestHeadUnknown } + mode := prDecisionModeFor(unparkCommand{Kind: unparkCommandDecision, Decision: decision, Text: decision}) req := review.HumanChangeRequest{ Repo: owner + "/" + name, Number: number, @@ -220,19 +221,19 @@ func (c *Client) RecordOperatorPullRequestDecision(ctx context.Context, repo str SourceID: operatorDecisionMarkerID, Actor: actor, Body: decision, + Kind: mode.kind(), } // Record before replying: a reply without a record would promise a fix // nothing is queued to make. if err := store.Record(req); err != nil { return PullRequestDecisionEvent{}, fmt.Errorf("recording dashboard decision on %s/%s#%d: %w", owner, name, number, err) } - body := renderPRDecisionRecordedReply(actor, head) + "\n\n_Recorded from the hive dashboard._" + stage := c.applyPRDecisionStage(ctx, owner, name, number, head, actor, mode, selfAuthored) + body := renderPRDecisionReply(actor, head, mode) + "\n\n_Recorded from the hive dashboard._" if err := c.postUnparkReply(ctx, owner, name, number, operatorDecisionMarkerID, body); err != nil { return PullRequestDecisionEvent{}, err } - event := PullRequestDecisionEvent{Repo: owner + "/" + name, Number: number, HeadSHA: head, Actor: actor, Decision: decision} - if c.logger != nil { - c.logger.Info("pull request direction recorded by dashboard decision", "repo", event.Repo, "pr", number, "actor", actor, "head", head) - } + event := PullRequestDecisionEvent{Repo: owner + "/" + name, Number: number, HeadSHA: head, Actor: actor, Decision: decision, Mode: string(mode)} + c.logPRDecision(event.Repo, number, head, actor, mode, stage, false) return event, nil } diff --git a/src/pkg/github/pr_decision_operator_test.go b/src/pkg/github/pr_decision_operator_test.go index 7b68348767..4fa0bbf2f1 100644 --- a/src/pkg/github/pr_decision_operator_test.go +++ b/src/pkg/github/pr_decision_operator_test.go @@ -77,6 +77,28 @@ func TestRecordOperatorPullRequestDecisionRecordsChangeRequestAndReplies(t *test if !strings.Contains(posted, unparkReplyMarkerPrefix+"0 -->") { t.Fatalf("reply must carry the shared unpark marker with a non-command id, got %q", posted) } + if event.Mode != string(prDecisionChangesRequested) || got.IsApproval() { + t.Fatalf("event mode = %q, kind = %q; want changes_requested", event.Mode, got.Kind) + } + if facts := prDecisionFacts(t, c); len(facts) != 1 || !facts[0].Instruction || facts[0].Head != liveDecisionHead { + t.Fatalf("stage facts = %+v, want one PRDecided with the instruction", facts) + } + + // A bare "approve" from the dashboard is an approval, not a fix request. + c2, rec2 := newUnparkPRClient(t, []unparkWireIssue{hiveParkedPR()}, nil) + event2, err := c2.RecordOperatorPullRequestDecision(context.Background(), "org/repo", liveDecisionPR, "maintainer", "approve", store) + if err != nil { + t.Fatalf("approve: %v", err) + } + if event2.Mode != string(prDecisionApprove) || review.HumanChangeRequestFor(store, "org/repo", liveDecisionPR, liveDecisionHead) != nil || review.HumanApprovalFor(store, "org/repo", liveDecisionPR, liveDecisionHead) == nil { + t.Fatalf("approve event = %+v, store = %+v", event2, store) + } + if posted := strings.Join(rec2.posted[liveDecisionPR], "\n"); !strings.Contains(posted, "Approval recorded by @maintainer") { + t.Fatalf("expected the approval reply, got %q", posted) + } + if facts := prDecisionFacts(t, c2); len(facts) != 1 || facts[0].Instruction { + t.Fatalf("stage facts = %+v, want one PRDecided without an instruction", facts) + } } func TestRecordOperatorPullRequestDecisionRefusesForeignEmptyAndUnstored(t *testing.T) { diff --git a/src/pkg/github/pr_unpark_decision.go b/src/pkg/github/pr_unpark_decision.go index 58ae8b2026..81b55ba931 100644 --- a/src/pkg/github/pr_unpark_decision.go +++ b/src/pkg/github/pr_unpark_decision.go @@ -10,6 +10,8 @@ import ( gh "github.com/google/go-github/v72/github" "github.com/hivecommons/hive/pkg/authorkind" "github.com/hivecommons/hive/pkg/review" + "github.com/hivecommons/hive/pkg/stageengine" + "github.com/hivecommons/hive/pkg/stagelabels" ) // tryUnparkPullRequest answers the newest eligible `/hive …` command on a PR @@ -41,7 +43,7 @@ func (c *Client) tryUnparkPullRequest(ctx context.Context, displayRepo, owner, r return false, err } if candidate == nil || command.Kind == unparkCommandNone { - return false, nil + return c.reconcileAnsweredPRDecision(ctx, displayRepo, owner, repo, number, comments, opts) } actor := safeGetLogin(candidate.GetUser()) if opts.TrustedMerger == nil || !opts.TrustedMerger(actor) { @@ -67,6 +69,7 @@ func (c *Client) tryUnparkPullRequest(ctx context.Context, displayRepo, owner, r reply := "" switch { case command.Kind == unparkCommandDecision && selfAuthored && head != "": + mode := prDecisionModeFor(command) req := review.HumanChangeRequest{ Repo: owner + "/" + repo, Number: number, @@ -74,8 +77,9 @@ func (c *Client) tryUnparkPullRequest(ctx context.Context, displayRepo, owner, r Source: review.HumanChangeRequestSourceDecision, SourceID: candidate.GetID(), Actor: actor, - Body: command.Decision, + Body: command.DecisionText(), URL: candidate.GetHTMLURL(), + Kind: mode.kind(), } if opts.HumanChangeRequests == nil { return false, fmt.Errorf("no human change request store; `/hive decision` on %s/%s#%d by @%s cannot be routed", owner, repo, number, actor) @@ -85,12 +89,14 @@ func (c *Client) tryUnparkPullRequest(ctx context.Context, displayRepo, owner, r if err := opts.HumanChangeRequests.Record(req); err != nil { return false, fmt.Errorf("recording `/hive decision` on %s/%s#%d: %w", owner, repo, number, err) } - event := PullRequestDecisionEvent{Repo: displayRepo, Number: number, HeadSHA: head, Actor: actor, Decision: command.Decision, CommentURL: candidate.GetHTMLURL()} + event := PullRequestDecisionEvent{Repo: displayRepo, Number: number, HeadSHA: head, Actor: actor, Decision: req.Body, Mode: string(mode), CommentURL: candidate.GetHTMLURL()} result.PRDecisions = append(result.PRDecisions, event) if opts.PRAudit != nil { opts.PRAudit(event) } - reply = renderPRDecisionRecordedReply(actor, head) + stage := c.applyPRDecisionStage(ctx, owner, repo, number, head, actor, mode, selfAuthored) + c.logPRDecision(displayRepo, number, head, actor, mode, stage, false) + reply = renderPRDecisionReply(actor, head, mode) case command.Kind == unparkCommandDecision && selfAuthored: reply = renderPRDecisionNoHeadReply() case command.Kind == unparkCommandDecision: @@ -109,6 +115,254 @@ func (c *Client) tryUnparkPullRequest(ctx context.Context, displayRepo, owner, r return true, nil } +// prDecisionMode is what a `/hive decision` on a PR asks for. +type prDecisionMode string + +const ( + // prDecisionChangesRequested: the decision carries an instruction; the + // PR goes to fixing and the author agent follows it verbatim. + prDecisionChangesRequested prDecisionMode = "changes_requested" + // prDecisionApprove: a bare `/hive decision approve`; the owner answered + // the swarm's question with "yes" and the merge path takes over. + prDecisionApprove prDecisionMode = "approve" +) + +func (m prDecisionMode) kind() string { + if m == prDecisionApprove { + return review.HumanChangeRequestKindApprove + } + return review.HumanChangeRequestKindChanges +} + +func prDecisionModeFor(cmd unparkCommand) prDecisionMode { + if cmd.BareApproval() { + return prDecisionApprove + } + return prDecisionChangesRequested +} + +// prDecisionHeadMarker tags the reply with the exact head the decision was +// recorded for, so a restart that lost the store can rebuild the record +// from the comment thread alone (reconcileAnsweredPRDecision). +const prDecisionHeadMarker = "", prDecisionHeadMarker, strings.TrimSpace(head), mode) +} + +// parsePRDecisionHeadMarker reads the head and mode a recorded-decision reply +// was posted for. Replies from before the marker existed carry only the +// 7-character head in prose ("head `3b4a2b5`"); those are matched by prefix +// against the live head, with the mode read from the prose. +func parsePRDecisionHeadMarker(reply, liveHead string) (prDecisionMode, bool) { + liveHead = strings.TrimSpace(liveHead) + if liveHead == "" { + return "", false + } + if idx := strings.Index(reply, prDecisionHeadMarker); idx >= 0 { + rest := reply[idx+len(prDecisionHeadMarker):] + if end := strings.Index(rest, "-->"); end >= 0 { + rest = rest[:end] + } + fields := strings.Fields(rest) + if len(fields) < 1 || !strings.EqualFold(fields[0], liveHead) { + return "", false + } + for _, f := range fields[1:] { + if strings.HasPrefix(f, "mode=") { + if m := prDecisionMode(strings.TrimPrefix(f, "mode=")); m == prDecisionApprove { + return prDecisionApprove, true + } + } + } + return prDecisionChangesRequested, true + } + if !strings.Contains(reply, "Decision recorded by @") && !strings.Contains(reply, "Approval recorded by @") { + return "", false + } + short := liveHead + if len(short) > 7 { + short = short[:7] + } + if !strings.Contains(reply, "head `"+short+"`") { + return "", false + } + if strings.Contains(reply, "Approval recorded by @") { + return prDecisionApprove, true + } + return prDecisionChangesRequested, true +} + +// reconcileAnsweredPRDecision is the restart path (hivecommons/hive#14679). +// The reply marker says the newest `/hive decision` on this PR was already +// acknowledged, so it is never answered twice — but the acknowledgement is +// only the promise; the record that moves the PR and kicks the fix lives in +// the change-request store. If that record is missing for the live head +// (lost data dir, a crash between record and persist, an older build that +// recorded a different head) the decision is re-recorded from the thread, +// silently, and the stage re-applied. A decision answered for an older head +// is left alone: the author already pushed past it. +func (c *Client) reconcileAnsweredPRDecision(ctx context.Context, displayRepo, owner, repo string, number int, comments []*gh.IssueComment, opts IssueUnparkSweepOptions) (bool, error) { + if opts.HumanChangeRequests == nil || opts.TrustedMerger == nil { + return false, nil + } + replies := c.unparkRepliesByCommentID(comments) + var decision *gh.IssueComment + var cmd unparkCommand + for i := len(comments) - 1; i >= 0; i-- { + cm := comments[i] + if cm == nil || replies[cm.GetID()] == nil || !c.isHumanAuthor(cm.GetUser()) { + continue + } + parsed, ok := parseUnparkCommand(cm.GetBody()) + if !ok { + continue + } + if parsed.Kind != unparkCommandDecision { + if isUnparkWatermarkCommand(cm.GetBody()) { + return false, nil + } + continue + } + if !opts.TrustedMerger(safeGetLogin(cm.GetUser())) { + continue + } + decision, cmd = cm, parsed + break + } + if decision == nil { + return false, nil + } + // Already recorded with the text as it reads now: nothing to repair. A + // record whose body differs (an older build kept only the first line, + // hivecommons/hive#14628) is re-recorded below so the planner and the + // lane see the instruction the person actually gave. + if store, ok := opts.HumanChangeRequests.(interface { + Lookup(repo string, number int, source string, sourceID int64) (review.HumanChangeRequest, bool) + }); ok { + if existing, found := store.Lookup(owner+"/"+repo, number, review.HumanChangeRequestSourceDecision, decision.GetID()); found && existing.Body == cmd.DecisionText() { + return false, nil + } + } + pr, resp, err := c.client.PullRequests.Get(ctx, owner, repo, number) + if err != nil { + if resp != nil && resp.StatusCode == http.StatusNotFound { + return false, nil + } + return false, fmt.Errorf("fetching pull request %s/%s#%d: %w", owner, repo, number, err) + } + if strings.EqualFold(pr.GetState(), "closed") || pr.GetHead() == nil { + return false, nil + } + head := strings.TrimSpace(pr.GetHead().GetSHA()) + if head == "" { + return false, nil + } + mode, ok := parsePRDecisionHeadMarker(replies[decision.GetID()].GetBody(), head) + if !ok { + return false, nil + } + if existing, found := opts.HumanChangeRequests.For(owner+"/"+repo, number, head); found && existing.Source == review.HumanChangeRequestSourceDecision && existing.SourceID == decision.GetID() && existing.Body == cmd.DecisionText() && existing.Kind == mode.kind() { + return false, nil + } + selfAuthored := c.isHiveAccount(pr.GetUser()) || labelPresent(issueLabelNames(pr.Labels), authorkind.Hive.Label()) + if !selfAuthored { + return false, nil + } + actor := safeGetLogin(decision.GetUser()) + req := review.HumanChangeRequest{ + Repo: owner + "/" + repo, + Number: number, + HeadSHA: head, + Source: review.HumanChangeRequestSourceDecision, + SourceID: decision.GetID(), + Actor: actor, + Body: cmd.DecisionText(), + URL: decision.GetHTMLURL(), + Kind: mode.kind(), + RecordedAt: replies[decision.GetID()].GetCreatedAt().Time, + } + if err := opts.HumanChangeRequests.Record(req); err != nil { + return false, fmt.Errorf("re-recording `/hive decision` on %s/%s#%d: %w", owner, repo, number, err) + } + stage := c.applyPRDecisionStage(ctx, owner, repo, number, head, actor, mode, selfAuthored) + c.logPRDecision(displayRepo, number, head, actor, mode, stage, true) + return true, nil +} + +// unparkRepliesByCommentID maps each answered command's comment ID to the +// hive's reply that answered it. +func (c *Client) unparkRepliesByCommentID(comments []*gh.IssueComment) map[int64]*gh.IssueComment { + out := map[int64]*gh.IssueComment{} + for _, cm := range comments { + if cm == nil || !c.markerAuthorTrusted(cm.GetUser()) { + continue + } + body := cm.GetBody() + idx := strings.Index(body, unparkReplyMarkerPrefix) + if idx < 0 { + continue + } + rest := body[idx+len(unparkReplyMarkerPrefix):] + end := strings.Index(rest, " ") + if end < 0 { + continue + } + var id int64 + if _, err := fmt.Sscanf(rest[:end], "%d", &id); err == nil && id > 0 { + out[id] = cm + } + } + return out +} + +// applyPRDecisionStage submits the decision to the stage engine so the park +// lifts now rather than on the next sweep. A failed write is not fatal: the +// record stands in the store, and the lanes derive the same stage from it +// on their next pass. It returns the stage written, or "" when none was. +func (c *Client) applyPRDecisionStage(ctx context.Context, owner, repo string, number int, head, actor string, mode prDecisionMode, selfAuthored bool) string { + sink := c.StageFacts() + if sink == nil { + return "" + } + tr, err := sink.PRDecided(ctx, c.PRStageRef(owner+"/"+repo, number), stageengine.PRDecisionFact{ + Head: head, + By: actor, + Instruction: mode == prDecisionChangesRequested, + SelfAuthored: selfAuthored, + }) + if err != nil { + if c.logger != nil { + c.logger.Warn("decision: stage write deferred to next sweep", "repo", owner+"/"+repo, "pr", number, "head", head, "error", err) + } + return "" + } + if tr.To == stagelabels.None { + return "" + } + return tr.To.Label() +} + +func (c *Client) logPRDecision(displayRepo string, number int, head, actor string, mode prDecisionMode, stage string, reconciled bool) { + if c.logger == nil { + return + } + stageText := stage + if stageText == "" { + stageText = "next-sweep" + } + c.logger.Info(fmt.Sprintf("decision: unpark pr=%d head=%s mode=%s by=%s → stage=%s", number, prShortHead(head), mode, actor, stageText), + "repo", displayRepo, "pr", number, "head", head, "mode", string(mode), "by", actor, "stage", stage, "reconciled", reconciled) +} + +func prShortHead(head string) string { + head = strings.TrimSpace(head) + if len(head) > 7 { + return head[:7] + } + return head +} + func prHeadRef(head string) string { head = strings.TrimSpace(head) if head == "" { @@ -120,9 +374,21 @@ func prHeadRef(head string) string { return "head `" + head + "`" } +func renderPRDecisionReply(actor, head string, mode prDecisionMode) string { + if mode == prDecisionApprove { + return renderPRDecisionApprovedReply(actor, head) + } + return renderPRDecisionRecordedReply(actor, head) +} + func renderPRDecisionRecordedReply(actor, head string) string { - return fmt.Sprintf("Decision recorded by @%s for %s. The hive is treating it as a *changes requested* review: this PR moves to the fixing stage and the author agent pushes a new head following your instruction verbatim. The review swarm then re-reviews that head; if it approves, the PR comes back for your merge approval.", - actor, prHeadRef(head)) + return fmt.Sprintf("%s\nDecision recorded by @%s for %s. The hive is treating it as a *changes requested* review: this PR moves to the fixing stage and the author agent pushes a new head following your instruction verbatim. The review swarm then re-reviews that head; if it approves, the PR comes back for your merge approval.", + prDecisionHeadMarkerLine(head, prDecisionChangesRequested), actor, prHeadRef(head)) +} + +func renderPRDecisionApprovedReply(actor, head string) string { + return fmt.Sprintf("%s\nApproval recorded by @%s for %s. The hive is treating it as your answer to the review swarm's question: nothing is sent back to the author, and the PR follows the merge path on the next pass (merged when the merge gates pass, or handed to you at the ready-for-merge stage where a person has to press the button).", + prDecisionHeadMarkerLine(head, prDecisionApprove), actor, prHeadRef(head)) } func renderPRDecisionNoHeadReply() string { diff --git a/src/pkg/github/pr_unpark_decision_test.go b/src/pkg/github/pr_unpark_decision_test.go index d17a254e75..5298608d4d 100644 --- a/src/pkg/github/pr_unpark_decision_test.go +++ b/src/pkg/github/pr_unpark_decision_test.go @@ -6,6 +6,8 @@ import ( "testing" "github.com/hivecommons/hive/pkg/review" + "github.com/hivecommons/hive/pkg/stageengine" + "github.com/hivecommons/hive/pkg/stageengine/stageenginetest" ) // Reproduces hivecommons/hive#12968, the live case behind #13041: a @@ -52,9 +54,26 @@ func newUnparkPRClient(t *testing.T, issues []unparkWireIssue, permissions map[s server, rec := newUnparkServer(t, "org", "repo", issues, permissions) c := newTestClient(t, server, "org", []string{"repo"}) c.SetAppBotLogin("hive[bot]") + c.SetStageFactSink(&stageenginetest.Recorder{}) return c, rec } +// prDecisionFacts returns the PRDecided facts the client submitted. +func prDecisionFacts(t *testing.T, c *Client) []stageengine.PRDecisionFact { + t.Helper() + rec, ok := c.StageFacts().(*stageenginetest.Recorder) + if !ok { + t.Fatalf("stage sink is %T, want the test recorder", c.StageFacts()) + } + var out []stageengine.PRDecisionFact + for _, f := range rec.All() { + if f.Method == "PRDecided" && f.Decision != nil { + out = append(out, *f.Decision) + } + } + return out +} + func TestSweepIssueUnparkCommandsDecisionOnHivePRRoutesFixKick(t *testing.T) { issues := []unparkWireIssue{hiveParkedPR(humanComment(4242, "clubanderson", "/hive decision "+liveDecisionText))} c, rec := newUnparkPRClient(t, issues, map[string]string{"clubanderson": "admin"}) @@ -93,7 +112,12 @@ func TestSweepIssueUnparkCommandsDecisionOnHivePRRoutesFixKick(t *testing.T) { } } if len(rec.added[liveDecisionPR]) != 0 || len(rec.removed[liveDecisionPR]) != 0 { - t.Fatalf("labels touched on a PR: added %v removed %v", rec.added[liveDecisionPR], rec.removed[liveDecisionPR]) + t.Fatalf("labels touched on a PR outside the stage engine: added %v removed %v", rec.added[liveDecisionPR], rec.removed[liveDecisionPR]) + } + // The stage moves in the same breath as the reply, through the engine. + facts := prDecisionFacts(t, c) + if len(facts) != 1 || facts[0] != (stageengine.PRDecisionFact{Head: liveDecisionHead, By: "clubanderson", Instruction: true, SelfAuthored: true}) { + t.Fatalf("stage facts = %+v, want one PRDecided with the instruction", facts) } // The planner kicks the fix lane from the record, with the text verbatim. @@ -114,11 +138,190 @@ func TestSweepIssueUnparkCommandsDecisionOnHivePRRoutesFixKick(t *testing.T) { if err != nil { t.Fatalf("second sweep: %v", err) } - if len(result2.PRDecisions) != 0 || len(rec2.posted[liveDecisionPR]) != 0 || store.Len() != 1 { + if len(result2.PRDecisions) != 0 || len(rec2.posted[liveDecisionPR]) != 0 || store.Len() != 1 || len(prDecisionFacts(t, c2)) != 0 { t.Fatalf("second sweep repeated: %+v posted=%v store=%d", result2, rec2.posted[liveDecisionPR], store.Len()) } } +// hivecommons/hive#14679, the live case on #14628: `/hive decision approve` +// followed by numbered instructions is a change request carrying the whole +// text — recorded verbatim, stage 070 submitted, fix kick quoting every +// line — while a bare `/hive decision approve` is an approval: recorded as +// such, no fix kick, the lanes release requires_human from it. +func TestSweepIssueUnparkCommandsDecisionApproveModes(t *testing.T) { + const instructions = "/hive decision approve\n\nBefore merging:\n\n1. Change `Closes #14605` to `Refs #14605`.\n2. Keep #14605 open.\n3. Merge on green." + cases := []struct { + name string + body string + wantMode string + wantKind string + wantFixKick bool + wantReply []string + wantInstruct bool + }{ + { + name: "approve with instructions → changes_requested", body: instructions, + wantMode: "changes_requested", wantKind: review.HumanChangeRequestKindChanges, wantFixKick: true, wantInstruct: true, + wantReply: []string{"Decision recorded by @clubanderson", "changes requested", prDecisionHeadMarkerLine(liveDecisionHead, prDecisionChangesRequested)}, + }, + { + name: "bare approve → approve", body: "/hive decision approve", + wantMode: "approve", wantKind: review.HumanChangeRequestKindApprove, + wantReply: []string{"Approval recorded by @clubanderson", "merge path", prDecisionHeadMarkerLine(liveDecisionHead, prDecisionApprove)}, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + issues := []unparkWireIssue{hiveParkedPR(humanComment(4242, "clubanderson", tc.body))} + c, rec := newUnparkPRClient(t, issues, map[string]string{"clubanderson": "admin"}) + store := review.NewHumanChangeRequests("") + result, err := c.SweepIssueUnparkCommands(context.Background(), IssueUnparkSweepOptions{HumanChangeRequests: store, TrustedMerger: trustedMergerSet("clubanderson")}) + if err != nil { + t.Fatalf("sweep: %v", err) + } + if len(result.PRDecisions) != 1 || result.PRDecisions[0].Mode != tc.wantMode { + t.Fatalf("decisions = %+v, want one in mode %s", result.PRDecisions, tc.wantMode) + } + req, ok := store.For("org/repo", liveDecisionPR, liveDecisionHead) + if !ok || req.Kind != tc.wantKind || req.Actor != "clubanderson" { + t.Fatalf("recorded = %+v, %v", req, ok) + } + if tc.wantInstruct { + for _, want := range []string{"1. Change `Closes #14605` to `Refs #14605`.", "2. Keep #14605 open.", "3. Merge on green."} { + if !strings.Contains(req.Body, want) || !strings.Contains(result.PRDecisions[0].Decision, want) { + t.Fatalf("instruction %q lost: body=%q", want, req.Body) + } + } + } + if len(rec.posted[liveDecisionPR]) != 1 { + t.Fatalf("posted = %v", rec.posted[liveDecisionPR]) + } + for _, want := range tc.wantReply { + if !strings.Contains(rec.posted[liveDecisionPR][0], want) { + t.Fatalf("reply missing %q:\n%s", want, rec.posted[liveDecisionPR][0]) + } + } + facts := prDecisionFacts(t, c) + if len(facts) != 1 || facts[0].Instruction != tc.wantInstruct || facts[0].Head != liveDecisionHead || !facts[0].SelfAuthored { + t.Fatalf("stage facts = %+v", facts) + } + pr := review.PullRequest{Repo: "org/repo", Number: liveDecisionPR, Author: "hive[bot]", HeadSHA: liveDecisionHead, Labels: []string{PRNeedsDecisionStageLabel, "author/hive"}} + pr.HumanChangeRequest = review.HumanChangeRequestFor(store, pr.Repo, pr.Number, pr.HeadSHA) + plan := review.PlanDispatch([]review.PullRequest{pr}, review.Artifact{}, review.DispatchState{}, review.DispatchOptions{ + RequireApproval: true, FanOut: true, ProjectOrg: "org", + Agents: []review.AgentCapability{{Name: review.DefaultFixerAgent, Enabled: true, UsesKick: true, Role: "reviewer"}}, + }) + if got := len(plan.FixKicks) == 1; got != tc.wantFixKick { + t.Fatalf("fix kicks = %+v, want kick=%v", plan.FixKicks, tc.wantFixKick) + } + if tc.wantFixKick && !strings.Contains(plan.FixKicks[0].Message, "3. Merge on green.") { + t.Fatalf("fix kick does not quote the instructions:\n%s", plan.FixKicks[0].Message) + } + }) + } +} + +// hivecommons/hive#14679: the decision on #14628 was acknowledged by one pod +// and the stage never moved before the next pod came up. An answered +// decision (reply marker present) whose record is missing for the live +// head is rebuilt from the thread — no second reply, the same stage fact — +// and one answered for an older head is left alone. +func TestSweepIssueUnparkCommandsReconcilesAnsweredDecisionAfterRestart(t *testing.T) { + const body = "/hive decision approve\n\n1. Change `Closes #14605` to `Refs #14605`.\n2. Keep #14605 open." + replyFor := func(head string) unparkWireComment { + return unparkWireComment{ID: 9001, Body: unparkReplyMarkerPrefix + "4242 -->\n" + renderPRDecisionRecordedReply("clubanderson", head), User: wireUser{Login: "hive[bot]"}, CreatedAt: unparkNow(), UpdatedAt: unparkNow()} + } + t.Run("answered for the live head → re-recorded, no reply", func(t *testing.T) { + issues := []unparkWireIssue{hiveParkedPR(humanComment(4242, "clubanderson", body), replyFor(liveDecisionHead))} + c, rec := newUnparkPRClient(t, issues, map[string]string{"clubanderson": "admin"}) + store := review.NewHumanChangeRequests("") + result, err := c.SweepIssueUnparkCommands(context.Background(), IssueUnparkSweepOptions{HumanChangeRequests: store, TrustedMerger: trustedMergerSet("clubanderson")}) + if err != nil { + t.Fatalf("sweep: %v", err) + } + if len(rec.posted[liveDecisionPR]) != 0 || len(result.PRDecisions) != 0 { + t.Fatalf("reconciliation replied again: posted=%v decisions=%+v", rec.posted[liveDecisionPR], result.PRDecisions) + } + req, ok := store.For("org/repo", liveDecisionPR, liveDecisionHead) + if !ok || req.SourceID != 4242 || req.Kind != review.HumanChangeRequestKindChanges || !strings.Contains(req.Body, "2. Keep #14605 open.") { + t.Fatalf("re-recorded = %+v, %v", req, ok) + } + facts := prDecisionFacts(t, c) + if len(facts) != 1 || !facts[0].Instruction || facts[0].Head != liveDecisionHead { + t.Fatalf("stage facts = %+v", facts) + } + // Idempotent: the record now stands, so the next sweep is a no-op. + c2, rec2 := newUnparkPRClient(t, issues, map[string]string{"clubanderson": "admin"}) + if _, err := c2.SweepIssueUnparkCommands(context.Background(), IssueUnparkSweepOptions{HumanChangeRequests: store, TrustedMerger: trustedMergerSet("clubanderson")}); err != nil { + t.Fatal(err) + } + if len(rec2.posted[liveDecisionPR]) != 0 || len(prDecisionFacts(t, c2)) != 0 || store.Len() != 1 { + t.Fatalf("second reconciliation acted: posted=%v store=%d", rec2.posted[liveDecisionPR], store.Len()) + } + }) + t.Run("record kept only the first line → repaired with the whole text", func(t *testing.T) { + issues := []unparkWireIssue{hiveParkedPR(humanComment(4242, "clubanderson", body), replyFor(liveDecisionHead))} + c, rec := newUnparkPRClient(t, issues, map[string]string{"clubanderson": "admin"}) + store := review.NewHumanChangeRequests("") + if err := store.Record(review.HumanChangeRequest{Repo: "org/repo", Number: liveDecisionPR, HeadSHA: liveDecisionHead, Source: review.HumanChangeRequestSourceDecision, SourceID: 4242, Actor: "clubanderson", Body: "approve"}); err != nil { + t.Fatal(err) + } + if _, err := c.SweepIssueUnparkCommands(context.Background(), IssueUnparkSweepOptions{HumanChangeRequests: store, TrustedMerger: trustedMergerSet("clubanderson")}); err != nil { + t.Fatal(err) + } + req, ok := store.For("org/repo", liveDecisionPR, liveDecisionHead) + if !ok || store.Len() != 1 || !strings.Contains(req.Body, "1. Change `Closes #14605` to `Refs #14605`.") || len(rec.posted[liveDecisionPR]) != 0 { + t.Fatalf("repaired = %+v (len %d), posted=%v", req, store.Len(), rec.posted[liveDecisionPR]) + } + }) + t.Run("pre-marker reply matched by short head", func(t *testing.T) { + old := replyFor(liveDecisionHead) + old.Body = unparkReplyMarkerPrefix + "4242 -->\nDecision recorded by @clubanderson for head `" + liveDecisionHead[:7] + "`. The hive is treating it as a *changes requested* review." + issues := []unparkWireIssue{hiveParkedPR(humanComment(4242, "clubanderson", body), old)} + c, _ := newUnparkPRClient(t, issues, map[string]string{"clubanderson": "admin"}) + store := review.NewHumanChangeRequests("") + if _, err := c.SweepIssueUnparkCommands(context.Background(), IssueUnparkSweepOptions{HumanChangeRequests: store, TrustedMerger: trustedMergerSet("clubanderson")}); err != nil { + t.Fatal(err) + } + if _, ok := store.For("org/repo", liveDecisionPR, liveDecisionHead); !ok || len(prDecisionFacts(t, c)) != 1 { + t.Fatalf("pre-marker reply not reconciled: store=%d", store.Len()) + } + }) + t.Run("answered for an older head → ignored", func(t *testing.T) { + issues := []unparkWireIssue{hiveParkedPR(humanComment(4242, "clubanderson", body), replyFor("0ld0ld0ld0ld0ld0ld0ld0ld0ld0ld0ld0ld0ld0"))} + c, rec := newUnparkPRClient(t, issues, map[string]string{"clubanderson": "admin"}) + store := review.NewHumanChangeRequests("") + if _, err := c.SweepIssueUnparkCommands(context.Background(), IssueUnparkSweepOptions{HumanChangeRequests: store, TrustedMerger: trustedMergerSet("clubanderson")}); err != nil { + t.Fatal(err) + } + if store.Len() != 0 || len(rec.posted[liveDecisionPR]) != 0 || len(prDecisionFacts(t, c)) != 0 { + t.Fatalf("stale decision acted on: store=%d posted=%v", store.Len(), rec.posted[liveDecisionPR]) + } + }) +} + +func TestParsePRDecisionHeadMarker(t *testing.T) { + head := liveDecisionHead + cases := []struct { + reply string + wantMode prDecisionMode + wantOK bool + }{ + {renderPRDecisionRecordedReply("ann", head), prDecisionChangesRequested, true}, + {renderPRDecisionApprovedReply("ann", head), prDecisionApprove, true}, + {renderPRDecisionRecordedReply("ann", "0ld0ld0ld0ld0ld0ld0ld0ld0ld0ld0ld0ld0ld0"), "", false}, + {"Decision recorded by @ann for head `" + head[:7] + "`.", prDecisionChangesRequested, true}, + {"Decision recorded by @ann for head `0ld0ld0`.", "", false}, + {renderPRHelpReply(true, head), "", false}, + } + for _, tc := range cases { + mode, ok := parsePRDecisionHeadMarker(tc.reply, head) + if ok != tc.wantOK || mode != tc.wantMode { + t.Errorf("parsePRDecisionHeadMarker(%q) = %s, %v; want %s, %v", tc.reply, mode, ok, tc.wantMode, tc.wantOK) + } + } +} + func TestSweepIssueUnparkCommandsDecisionOnHumanPRExplainsReviews(t *testing.T) { issues := []unparkWireIssue{parkedPR(31, "alice", []string{PRNeedsDecisionStageLabel}, humanComment(50, "maintainer", "/hive decision ship it with the flag"))} c, rec := newUnparkPRClient(t, issues, map[string]string{"maintainer": "write"}) diff --git a/src/pkg/review/human_change_request.go b/src/pkg/review/human_change_request.go index facc9d17df..6cd27863bc 100644 --- a/src/pkg/review/human_change_request.go +++ b/src/pkg/review/human_change_request.go @@ -30,6 +30,19 @@ const ( HumanChangeRequestSourceDecision = "decision" ) +// Kinds of a HumanChangeRequest. +const ( + // HumanChangeRequestKindChanges (the zero value, "" in older files) is + // an instruction the author agent must act on. + HumanChangeRequestKindChanges = "" + // HumanChangeRequestKindApprove is a bare `/hive decision approve`: the + // owner answered the swarm's question with "yes" and gave nothing to + // change. It supersedes the requires_human verdict on Head so the lane + // stops reporting decision-requested, but it never kicks a fix + // (hivecommons/hive#14679). + HumanChangeRequestKindApprove = "approve" +) + // HumanChangeRequest is one maintainer instruction that sends a hive-authored // PR head back to its author agent: a CHANGES_REQUESTED review on the head, // or a `/hive decision ` comment while the PR waits at @@ -49,11 +62,19 @@ type HumanChangeRequest struct { Actor string `json:"actor"` // Body is the review body or decision text, verbatim. Body string `json:"body"` + // Kind is HumanChangeRequestKindChanges or ...Approve. + Kind string `json:"kind,omitempty"` // URL is the review's or comment's HTML URL, when known. URL string `json:"url,omitempty"` RecordedAt time.Time `json:"recorded_at"` } +// IsApproval reports whether the request is a bare approval rather than an +// instruction to change the head. +func (r HumanChangeRequest) IsApproval() bool { + return r.Kind == HumanChangeRequestKindApprove +} + // HumanChangeRequestStore records maintainer change requests and answers // which one, if any, stands against a PR head. Implementations are safe for // concurrent use: the automerge sweep records while the planner reads. @@ -186,6 +207,25 @@ func (s *HumanChangeRequests) For(repo string, number int, head string) (HumanCh return newest, found } +// Lookup returns the request recorded from source/sourceID against +// repo#number at any head: the cheap "already seen" test the un-park +// sweep's restart reconciliation runs before it spends a PR read. +func (s *HumanChangeRequests) Lookup(repo string, number int, source string, sourceID int64) (HumanChangeRequest, bool) { + if s == nil { + return HumanChangeRequest{}, false + } + repo = strings.TrimSpace(repo) + s.mu.Lock() + defer s.mu.Unlock() + s.load() + for _, item := range s.items { + if item.Number == number && strings.EqualFold(item.Repo, repo) && item.Source == source && item.SourceID == sourceID { + return item, true + } + } + return HumanChangeRequest{}, false +} + // Len is the number of recorded requests across all PRs and heads. func (s *HumanChangeRequests) Len() int { if s == nil { @@ -199,12 +239,27 @@ func (s *HumanChangeRequests) Len() int { // HumanChangeRequestFor resolves the request standing against pr's head // from store (nil-safe), for callers that build review.PullRequest values. +// A bare approval is not a change request: the planner must not kick a fix +// whose only instruction is "approve". func HumanChangeRequestFor(store HumanChangeRequestStore, repo string, number int, head string) *HumanChangeRequest { if store == nil { return nil } req, ok := store.For(repo, number, head) - if !ok { + if !ok || req.IsApproval() { + return nil + } + return &req +} + +// HumanApprovalFor returns the bare `/hive decision approve` standing +// against pr's head, if the newest recorded decision on that head is one. +func HumanApprovalFor(store HumanChangeRequestStore, repo string, number int, head string) *HumanChangeRequest { + if store == nil { + return nil + } + req, ok := store.For(repo, number, head) + if !ok || !req.IsApproval() { return nil } return &req diff --git a/src/pkg/review/human_change_request_test.go b/src/pkg/review/human_change_request_test.go index cddc9c6bae..306dea45f7 100644 --- a/src/pkg/review/human_change_request_test.go +++ b/src/pkg/review/human_change_request_test.go @@ -251,3 +251,46 @@ func TestPlanDispatchPendingFixExpires(t *testing.T) { }) } } + +// hivecommons/hive#14679: a bare `/hive decision approve` is recorded against +// the head so the lanes stop asking for a decision, but it is not a change +// request — the planner must not kick a fix whose instruction is "approve". +func TestHumanChangeRequestApprovalKindIsNotAFixRequest(t *testing.T) { + store := NewHumanChangeRequests(filepath.Join(t.TempDir(), HumanChangeRequestsFile)) + approve := liveCaseRequest() + approve.Body, approve.Kind = "approve", HumanChangeRequestKindApprove + approve.RecordedAt = time.Date(2026, 10, 27, 18, 35, 0, 0, time.UTC) + if err := store.Record(approve); err != nil { + t.Fatal(err) + } + if got := HumanChangeRequestFor(store, liveCaseRepo, liveCaseNumber, liveCaseHead); got != nil { + t.Fatalf("HumanChangeRequestFor returned an approval: %+v", got) + } + if got := HumanApprovalFor(store, liveCaseRepo, liveCaseNumber, liveCaseHead); got == nil || !got.IsApproval() || got.Actor != "clubanderson" { + t.Fatalf("HumanApprovalFor = %+v", got) + } + if got := HumanApprovalFor(store, liveCaseRepo, liveCaseNumber, "0ther"); got != nil { + t.Fatalf("approval leaked to another head: %+v", got) + } + pr := liveCasePR() + pr.HumanChangeRequest = HumanChangeRequestFor(store, pr.Repo, pr.Number, pr.HeadSHA) + plan := PlanDispatch([]PullRequest{pr}, Artifact{}, DispatchState{}, humanRequestOpts()) + if len(plan.FixKicks) != 0 { + t.Fatalf("a bare approval kicked a fix: %+v", plan.FixKicks) + } + + // A later instruction on the same head supersedes the approval, and the + // record survives a reload with its kind. + changes := liveCaseRequest() + changes.SourceID, changes.RecordedAt = 4343, approve.RecordedAt.Add(time.Minute) + if err := store.Record(changes); err != nil { + t.Fatal(err) + } + reloaded := NewHumanChangeRequests(store.path) + if got := HumanChangeRequestFor(reloaded, liveCaseRepo, liveCaseNumber, liveCaseHead); got == nil || got.SourceID != 4343 || !strings.Contains(got.Body, "gate it behind the flag") { + t.Fatalf("reloaded request = %+v", got) + } + if got := HumanApprovalFor(reloaded, liveCaseRepo, liveCaseNumber, liveCaseHead); got != nil { + t.Fatalf("superseded approval still standing: %+v", got) + } +} diff --git a/src/pkg/stageengine/derive_pr.go b/src/pkg/stageengine/derive_pr.go index e23af7fdf5..2c948b0097 100644 --- a/src/pkg/stageengine/derive_pr.go +++ b/src/pkg/stageengine/derive_pr.go @@ -100,6 +100,9 @@ func ReviewFactsFrom(d stageDetail, head string) ReviewFacts { if approver := strings.TrimSpace(d.HumanApprover); approver != "" && strings.TrimSpace(d.HumanApprovalHead) != "" && strings.TrimSpace(d.HumanApprovalHead) == strings.TrimSpace(head) { r.HumanApprover = approver } + if requester := strings.TrimSpace(d.HumanChangeRequester); requester != "" && strings.TrimSpace(d.HumanChangeRequestHead) != "" && strings.TrimSpace(d.HumanChangeRequestHead) == strings.TrimSpace(head) { + r.HumanChangeRequester = requester + } r.State = VerdictStateFrom(d) return r } @@ -153,6 +156,9 @@ func ObservationsFromPRFacts(f Facts) []stageObservation { if pr.Review.HumanApprover != "" && pr.HeadSHA != "" { detail.HumanApprover, detail.HumanApprovalHead = pr.Review.HumanApprover, pr.HeadSHA } + if pr.Review.HumanChangeRequester != "" && pr.HeadSHA != "" { + detail.HumanChangeRequester, detail.HumanChangeRequestHead = pr.Review.HumanChangeRequester, pr.HeadSHA + } if pr.DCOGate { detail.DCOGateHead = pr.HeadSHA } diff --git a/src/pkg/stageengine/derive_pr_classify.go b/src/pkg/stageengine/derive_pr_classify.go index 21dcfd0c43..c8ddae5b3d 100644 --- a/src/pkg/stageengine/derive_pr_classify.go +++ b/src/pkg/stageengine/derive_pr_classify.go @@ -175,6 +175,26 @@ func TrustedHumanApprovedRequiresHuman(d stageDetail, head string) bool { return VerdictNeedsHuman(d) && strings.TrimSpace(d.HumanApprover) != "" && strings.TrimSpace(d.HumanApprovalHead) != "" && strings.TrimSpace(d.HumanApprovalHead) == strings.TrimSpace(head) } +// TrustedHumanChangeRequested reports whether a trusted human's change +// request — a CHANGES_REQUESTED review or a `/hive decision ` given +// at 085 — stands against head. It answers the swarm's requires_human / +// decision-requested verdict on that head: the person has spoken, so the +// PR belongs in fixing with the instruction, not parked on the question +// it already answered (hivecommons/hive#14679, seen on #14628). +func TrustedHumanChangeRequested(d stageDetail, head string) bool { + return strings.TrimSpace(d.HumanChangeRequester) != "" && strings.TrimSpace(d.HumanChangeRequestHead) != "" && strings.TrimSpace(d.HumanChangeRequestHead) == strings.TrimSpace(head) +} + +// HumanChangeRequestStage is the fixing opinion a standing human change +// request on the head carries: owned rank, reason human-changes-requested, +// whatever the reviewer verdict on that head says. +func HumanChangeRequestStage(o stageObservation) (stageVerdict, bool) { + if !TrustedHumanChangeRequested(o.Detail, o.HeadSHA) { + return stageVerdict{}, false + } + return stageVerdict{Stage: FixingStage(o), Rank: stageRankOwned, Reason: autoMergeReasonHumanChangesRequested}, true +} + func WithHumanApprovalReason(v stageVerdict, reason string) stageVerdict { if reason != "" && v.Rank != stageRankNone && !v.Terminal && v.Reason == "" { v.Reason = reason @@ -304,6 +324,9 @@ func ClassifyStage(o stageObservation) stageVerdict { if HasLabelFold(o.Labels, "needs-rebase") { return stageVerdict{Stage: fixing, Rank: stageRankOwned} } + if v, ok := HumanChangeRequestStage(o); ok { + return v + } if v, ok := RequiresHumanStage(o, rank); ok { // The reviewer already asked for a person: a 090 candidate would // be dropped for the non-approve verdict and fall to 050, where @@ -330,6 +353,11 @@ func ClassifyStage(o stageObservation) stageVerdict { } return stageVerdict{Stage: stagelabels.NeedsDecision, Rank: stageRankOwned, Human: true} } + if v, ok := HumanChangeRequestStage(o); ok { + // The person answered the question on this head: fixing with the + // instruction, ahead of the decision-requested verdict below. + return v + } if o.Detail.VerdictKnown && o.Detail.Verdict.DecisionRequested { // A posted decision question outranks mergeability: no fixer is kicked // for a decision-requested head, and a conflict is moot if the answer @@ -430,7 +458,7 @@ func ReviewGateStage(reason string, fixing stagelabels.Stage) (stageVerdict, boo // is requires_human / needs-decision and that no trusted human has approved // since; rank is the strength the caller's reason carries. func RequiresHumanStage(o stageObservation, rank int) (stageVerdict, bool) { - if !VerdictNeedsHuman(o.Detail) || TrustedHumanApprovedRequiresHuman(o.Detail, o.HeadSHA) { + if !VerdictNeedsHuman(o.Detail) || TrustedHumanApprovedRequiresHuman(o.Detail, o.HeadSHA) || TrustedHumanChangeRequested(o.Detail, o.HeadSHA) { return stageVerdict{}, false } return stageVerdict{Stage: stagelabels.NeedsDecision, Rank: rank, Human: true, Reason: StageVerdictReason(o.Detail)}, true diff --git a/src/pkg/stageengine/derive_pr_human_decision_test.go b/src/pkg/stageengine/derive_pr_human_decision_test.go new file mode 100644 index 0000000000..ab0af98306 --- /dev/null +++ b/src/pkg/stageengine/derive_pr_human_decision_test.go @@ -0,0 +1,168 @@ +package stageengine + +import ( + "context" + "testing" + + "github.com/hivecommons/hive/pkg/stagelabels" +) + +// hivecommons/hive#14679 (seen on #14628): a trusted human's recorded +// decision on the head answers the swarm's decision-requested verdict on +// that head. With an instruction the PR is fixing; a bare approval reads as +// a human approval and releases requires_human; a decision recorded for an +// older head is ignored and the question stands. +func TestClassifyStageHumanDecisionSupersedesDecisionRequested(t *testing.T) { + asked := ContributorLaneVerdict{Configured: true, Verdict: "requires_human", DecisionRequested: true} + fixing := FixingStage(stageObservation{Lane: stageLaneSelf}) + cases := []struct { + name string + reason string + detail stageDetail + wantStage stagelabels.Stage + wantReason string + wantHuman bool + }{ + { + name: "instructions on the head → fixing, over the lane's human-changes-requested reason", + reason: autoMergeReasonHumanChangesRequested, + detail: stageDetail{VerdictKnown: true, Verdict: asked, HumanChangeRequester: "clubanderson", HumanChangeRequestHead: goldenHead}, + wantStage: fixing, + wantReason: autoMergeReasonHumanChangesRequested, + }, + { + name: "instructions on the head → fixing, whatever else the lane reported", + reason: "ci-pending", + detail: stageDetail{VerdictKnown: true, Verdict: asked, HumanChangeRequester: "clubanderson", HumanChangeRequestHead: goldenHead}, + wantStage: fixing, + wantReason: autoMergeReasonHumanChangesRequested, + }, + { + name: "bare approve on the head → the merge path, not 085", + reason: "ci-pending", + detail: stageDetail{VerdictKnown: true, Verdict: asked, HumanApprover: "clubanderson", HumanApprovalHead: goldenHead}, + wantStage: stagelabels.None, + }, + { + name: "decision recorded for an older head → the question on this head stands", + reason: "ci-pending", + detail: stageDetail{VerdictKnown: true, Verdict: asked, HumanChangeRequester: "clubanderson", HumanChangeRequestHead: "0ld0ld0ld0ld0ld0ld0ld0ld0ld0ld0ld0ld0ld0"}, + wantStage: stagelabels.NeedsDecision, + wantReason: StageReasonDecisionRequested, + wantHuman: true, + }, + { + name: "no decision → 085 as before", + reason: "ci-pending", + detail: stageDetail{VerdictKnown: true, Verdict: asked}, + wantStage: stagelabels.NeedsDecision, + wantReason: StageReasonDecisionRequested, + wantHuman: true, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + v := ClassifyStage(stageObservation{Lane: stageLaneSelf, Reason: tc.reason, HeadSHA: goldenHead, Detail: tc.detail}) + if v.Stage == stagelabels.NeedsDecision && tc.wantStage != stagelabels.NeedsDecision { + t.Fatalf("classified as %+v, want not needs-decision", v) + } + if tc.wantStage != stagelabels.None && (v.Stage != tc.wantStage || v.Reason != tc.wantReason || v.Human != tc.wantHuman) { + t.Fatalf("classified as %+v, want stage=%s reason=%q human=%v", v, tc.wantStage, tc.wantReason, tc.wantHuman) + } + }) + } +} + +// The admission branch (a lane that cannot vouch for the author) takes the +// same answer: the owner's instruction on the head is fixing, not 085. +func TestClassifyStageHumanDecisionSupersedesDecisionRequestedOnAdmission(t *testing.T) { + asked := ContributorLaneVerdict{Configured: true, Verdict: "requires_human", DecisionRequested: true} + for reason, rank := range stageAdmissionReasons { + if rank == stageRankNone { + continue + } + o := stageObservation{Lane: stageLaneTrusted, Reason: reason, HeadSHA: goldenHead, Detail: stageDetail{VerdictKnown: true, Verdict: asked, HumanChangeRequester: "clubanderson", HumanChangeRequestHead: goldenHead}} + v := ClassifyStage(o) + if v.Stage != FixingStage(o) || v.Reason != autoMergeReasonHumanChangesRequested || v.Rank != stageRankOwned { + t.Fatalf("%q classified as %+v, want fixing on the owner's instruction", reason, v) + } + o.Detail.HumanChangeRequestHead = "0ld0ld0ld0ld0ld0ld0ld0ld0ld0ld0ld0ld0ld0" + if v := ClassifyStage(o); v.Stage != stagelabels.NeedsDecision { + t.Fatalf("%q with a stale decision classified as %+v, want needs-decision", reason, v) + } + } +} + +// ReviewFacts round-trips the requester only for the matching head, so a +// decision carried over from an older head cannot un-park the new one. +func TestReviewFactsCarryHumanChangeRequesterForHeadOnly(t *testing.T) { + d := stageDetail{VerdictKnown: true, Verdict: ContributorLaneVerdict{Configured: true, Verdict: "requires_human", DecisionRequested: true}, HumanChangeRequester: "clubanderson", HumanChangeRequestHead: goldenHead} + if r := ReviewFactsFrom(d, goldenHead); r.HumanChangeRequester != "clubanderson" { + t.Fatalf("ReviewFactsFrom lost the requester: %+v", r) + } + if r := ReviewFactsFrom(d, "other"); r.HumanChangeRequester != "" { + t.Fatalf("ReviewFactsFrom carried the requester to another head: %+v", r) + } + f := Facts{Open: true, PR: &PRFacts{HeadSHA: goldenHead, Review: ReviewFactsFrom(d, goldenHead), Lanes: []LaneFact{{Lane: stageLaneSelf, Reason: "ci-pending"}}}} + obs := ObservationsFromPRFacts(f) + if len(obs) != 1 || obs[0].Detail.HumanChangeRequester != "clubanderson" || obs[0].Detail.HumanChangeRequestHead != goldenHead { + t.Fatalf("observations = %+v", obs) + } + if v := ClassifyStage(obs[0]); v.Stage != FixingStage(obs[0]) { + t.Fatalf("round-tripped observation classified as %+v, want fixing", v) + } +} + +// PRDecided derives the stage the reply promises: an instruction on a +// hive-authored PR is 070 now; a bare approval abstains and leaves the +// merge path to the lanes' next pass; a decision with no head abstains. +func TestFactSinkPRDecidedDerivesFixingForInstruction(t *testing.T) { + ref := Ref{Owner: "o", Repo: "r", Number: 14628, Kind: stagelabels.PRItem} + cases := []struct { + name string + fact PRDecisionFact + want stagelabels.Stage + }{ + {"instruction on a hive PR → 070", PRDecisionFact{Head: goldenHead, By: "clubanderson", Instruction: true, SelfAuthored: true}, stagelabels.Fixing}, + {"instruction on a contributor PR → fixing for its author", PRDecisionFact{Head: goldenHead, By: "clubanderson", Instruction: true}, FixingStage(stageObservation{Lane: stageLaneTrusted})}, + {"bare approve → no opinion here", PRDecisionFact{Head: goldenHead, By: "clubanderson"}, stagelabels.None}, + {"no head → no opinion", PRDecisionFact{By: "clubanderson", Instruction: true, SelfAuthored: true}, stagelabels.None}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + var got Facts + sink := NewFactSink(deriveOnlyReconciler{on: func(f Facts) { got = f }}, FactSinkOptions{}) + if _, err := sink.PRDecided(context.Background(), ref, tc.fact); err != nil { + t.Fatal(err) + } + d := derivePR(got) + if tc.want == stagelabels.None { + if !d.Abstain { + t.Fatalf("derived %+v, want abstain", d) + } + return + } + if d.Abstain || d.Stage != tc.want || d.Reason != autoMergeReasonHumanChangesRequested { + t.Fatalf("derived %+v, want %s", d, tc.want) + } + }) + } +} + +// deriveOnlyReconciler hands the Facts a sink built to the test instead of +// writing anything. +type deriveOnlyReconciler struct{ on func(Facts) } + +func (r deriveOnlyReconciler) Reconcile(_ context.Context, f Facts) (Transition, error) { + r.on(f) + return Transition{Ref: f.Ref}, nil +} + +func (r deriveOnlyReconciler) ReconcileBatch(ctx context.Context, facts []Facts) ([]Transition, error) { + out := make([]Transition, 0, len(facts)) + for _, f := range facts { + tr, _ := r.Reconcile(ctx, f) + out = append(out, tr) + } + return out, nil +} diff --git a/src/pkg/stageengine/facts.go b/src/pkg/stageengine/facts.go index 886670223a..96844b1de1 100644 --- a/src/pkg/stageengine/facts.go +++ b/src/pkg/stageengine/facts.go @@ -264,12 +264,16 @@ type PriorStage struct { // ReviewFacts is THE "what counts as reviewed" fact (ADR-0025 Decision §6). type ReviewFacts struct { - State stagelabels.VerdictState // folded for HeadSHA - Verdict string // raw swarm verdict, "" when none - VerdictKnown bool - HumanApprover string // trusted human whose APPROVED review matches HeadSHA - HumanReviews int // review submissions by people on this head - HumanReviewsKnown bool + State stagelabels.VerdictState // folded for HeadSHA + Verdict string // raw swarm verdict, "" when none + VerdictKnown bool + HumanApprover string // trusted human whose APPROVED review matches HeadSHA + // HumanChangeRequester is the trusted human whose change request + // (review or `/hive decision `) stands against HeadSHA; it + // outranks a requires_human verdict on the same head (#14679). + HumanChangeRequester string + HumanReviews int // review submissions by people on this head + HumanReviewsKnown bool // DecisionRequested is set when the swarm's requires_human verdict was a // maintainer decision request (recorded reason // contributor-lane:decision-requested rather than diff --git a/src/pkg/stageengine/facts_sink.go b/src/pkg/stageengine/facts_sink.go index 86c77b78a3..d70e0b7ac8 100644 --- a/src/pkg/stageengine/facts_sink.go +++ b/src/pkg/stageengine/facts_sink.go @@ -21,6 +21,25 @@ type FactSink interface { Parked(ctx context.Context, ref Ref, label string) error // agent escalation (045/085/needs-human) Unparked(ctx context.Context, ref Ref, by string) error // /hive approve|decision Closed(ctx context.Context, ref Ref) error // the issue closed; its stage lifts + // PRDecided is a trusted merger's `/hive decision` answered on a PR + // parked at 085: the decision is recorded for Head, so the park lifts + // now — in the same breath as the reply — instead of waiting for the + // next sweep's lanes to notice (hivecommons/hive#14679). It returns + // the transition the reconcile wrote, for the caller's audit line. + PRDecided(ctx context.Context, ref Ref, d PRDecisionFact) (Transition, error) +} + +// PRDecisionFact is what a `/hive decision` on a PR establishes for the +// stage: who decided, on which head, and whether the decision carries an +// instruction the author agent must act on (→ fixing) or is a bare approval +// (→ the merge path, decided by the lanes on their next pass). +type PRDecisionFact struct { + Head string + By string + Instruction bool + // SelfAuthored says the hive opened the PR (the self lane owns it and + // fixing is 070); a PR it did not open is handed back to its author. + SelfAuthored bool } // NeedsHumanLabel is the non-stage park label an agent may request; a @@ -185,6 +204,35 @@ func (s *factSink) Unparked(ctx context.Context, ref Ref, by string) error { return s.submit(ctx, f) } +// PRDecided implements FactSink. A decision with an instruction is the +// self lane's human-changes-requested opinion on Head with the decider as +// the standing change requester, so ClassifyStage derives fixing over the +// reviewer's decision-requested verdict on the same head. A bare approval +// only lifts the park direction: the lanes release requires_human from the +// recorded approval on their next pass, and the deriver abstains here. +func (s *factSink) PRDecided(ctx context.Context, ref Ref, d PRDecisionFact) (Transition, error) { + ref.Kind = stagelabels.PRItem + f := Facts{Ref: ref, ObservedAt: s.opts.Now(), Open: true, Park: ParkFacts{ApprovedDirection: true}} + head := strings.TrimSpace(d.Head) + pr := &PRFacts{HeadSHA: head} + if d.Instruction && head != "" && strings.TrimSpace(d.By) != "" { + lane := stageLaneSelf + if !d.SelfAuthored { + lane = stageLaneTrusted + } + pr.Review.HumanChangeRequester = strings.TrimSpace(d.By) + pr.Lanes = []LaneFact{{Lane: lane, Reason: autoMergeReasonHumanChangesRequested}} + } + f.PR = pr + if s.opts.Enrich != nil { + var err error + if f, err = s.opts.Enrich(ctx, f); err != nil { + return Transition{Ref: ref}, err + } + } + return s.r.Reconcile(ctx, f) +} + // Closed implements FactSink: the issue closed (for any reason — a merged // fix, a maintainer's `/fixed`, a manual close) and is out of the pipeline; // the deriver answers a closed item with Terminal/None, so the writer takes diff --git a/src/pkg/stageengine/prstage/types.go b/src/pkg/stageengine/prstage/types.go index bb7ab7e5d5..ffa75488c6 100644 --- a/src/pkg/stageengine/prstage/types.go +++ b/src/pkg/stageengine/prstage/types.go @@ -20,7 +20,15 @@ type Detail struct { // overriding changes_requested/reject. HumanApprover string HumanApprovalHead string - Role stagelabels.Role + // HumanChangeRequester is the trusted human whose recorded change + // request (a CHANGES_REQUESTED review or a `/hive decision ` at + // 085) stands against HumanChangeRequestHead. It supersedes a + // requires_human / decision-requested reviewer verdict on that head: + // the person has answered, and the PR belongs in fixing, not 085 + // (hivecommons/hive#14679). + HumanChangeRequester string + HumanChangeRequestHead string + Role stagelabels.Role // RedChecks names the completed-red, non-required checks the CI gate // walked past on RedChecksHead (sorted). The lane ignores them by // design; the stage engine must not call the PR merge-queued or diff --git a/src/pkg/stageengine/stageenginetest/fake.go b/src/pkg/stageengine/stageenginetest/fake.go index 675ec422a9..8d42d2f651 100644 --- a/src/pkg/stageengine/stageenginetest/fake.go +++ b/src/pkg/stageengine/stageenginetest/fake.go @@ -170,13 +170,15 @@ type Recorder struct { // Recorded is one FactSink call. type Recorded struct { - Method string // Claimed | ClaimReleased | InProgress | CoveredBy | Uncovered | Parked | Unparked | Closed + Method string // Claimed | ClaimReleased | InProgress | CoveredBy | Uncovered | Parked | Unparked | Closed | PRDecided Ref stageengine.Ref Claim *stageengine.ClaimFact PR *stageengine.Ref Who string // holder / agent / by Label string Until time.Time + // Decision is the PRDecided fact. + Decision *stageengine.PRDecisionFact } func (r *Recorder) record(rec Recorded) error { @@ -217,6 +219,9 @@ func (r *Recorder) Unparked(_ context.Context, ref stageengine.Ref, by string) e func (r *Recorder) Closed(_ context.Context, ref stageengine.Ref) error { return r.record(Recorded{Method: "Closed", Ref: ref}) } +func (r *Recorder) PRDecided(_ context.Context, ref stageengine.Ref, d stageengine.PRDecisionFact) (stageengine.Transition, error) { + return stageengine.Transition{Ref: ref}, r.record(Recorded{Method: "PRDecided", Ref: ref, Who: d.By, Decision: &d}) +} var _ stageengine.FactSink = (*Recorder)(nil) var _ stageengine.StageWriter = (*Writer)(nil)