diff --git a/changelog.d/fixed-decision-path-owner-intent.md b/changelog.d/fixed-decision-path-owner-intent.md new file mode 100644 index 0000000000..7607865256 --- /dev/null +++ b/changelog.d/fixed-decision-path-owner-intent.md @@ -0,0 +1 @@ +- Preserve maintainer decision intent through PR decision paths: `/hive decision approve ` stays an approval (`yes, but …` stays an instruction), `/hive decision` is read at 070 as well as 085, a later same-head trusted APPROVED review releases a standing metadata-only request (and is dropped again if dismissed), edited non-closing issue references stay non-closing, and trusted contributor change requests return to the author (#14816). diff --git a/src/docs/maintainer-commands.md b/src/docs/maintainer-commands.md index 3e0769d74d..8bf971ff68 100644 --- a/src/docs/maintainer-commands.md +++ b/src/docs/maintainer-commands.md @@ -92,13 +92,26 @@ 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 +rather than waiting on a re-review. A `/hive decision` whose first word is +`approve`, `approved`, or `lgtm` (a trailing comma or period is fine) is +recorded as approval; the rest of the comment is retained as its rationale. A +bare `yes` approves too, but `yes, but …` is a conditional answer and is routed +as an instruction. To request changes, start with the instruction +(e.g. `/hive decision change the PR body to Refs #123`). No fix is kicked +for an approval, 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 sweep also reads `/hive decision` at `stage/070-fixing`: approve the +current head after a body or metadata fix to release a standing request without +pushing a cosmetic commit. A later trusted GitHub APPROVED review on the same +head also supersedes the recorded request; an older approval does not. If +that review is later dismissed, or the reviewer asks for changes again on the +same head, the review-backed approval is dropped and the earlier instruction +stands again — a `/hive decision approve` comment is durable and is not. +Issue-link repair preserves edited `Refs` bodies and PRs with a recorded +decision, so it cannot restore auto-close over the owner's direction. 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_contributor_lane.go b/src/pkg/github/automerge/automerge_contributor_lane.go index 08b77e72de..4b86878d86 100644 --- a/src/pkg/github/automerge/automerge_contributor_lane.go +++ b/src/pkg/github/automerge/automerge_contributor_lane.go @@ -1269,6 +1269,12 @@ func (c *Engine) evaluateContributorLanePR(ctx context.Context, displayRepo, own eval.verdict = verdict approver, humanApproved := c.trustedHumanApprovalForRequiresHuman(ctx, owner, repo, number, headSHA, verdict) c.noteStageVerdict(owner, repo, number, verdict) + // A trusted head-scoped change request answers the swarm's question + // even when admission or a requires_human verdict would return early. + if rv, ok := c.latestTrustedHumanChangesRequested(ctx, owner, repo, number, headSHA); ok { + c.noteStageHumanChangeRequest(owner, repo, number, headSHA, hgithub.SafeGetLogin(rv.GetUser())) + return eval, contributorLaneReasonChangesRequested, nil + } if claim.Reason != "" { // Neither this hive's registry nor an App-authored marker vouches // for the author, so GitHub's association is the only evidence left; diff --git a/src/pkg/github/automerge/automerge_contributor_lane_test.go b/src/pkg/github/automerge/automerge_contributor_lane_test.go index 06805777aa..38a368408b 100644 --- a/src/pkg/github/automerge/automerge_contributor_lane_test.go +++ b/src/pkg/github/automerge/automerge_contributor_lane_test.go @@ -18,8 +18,10 @@ import ( "time" gh "github.com/google/go-github/v72/github" + "github.com/hivecommons/hive/pkg/authorkind" hgithub "github.com/hivecommons/hive/pkg/github" "github.com/hivecommons/hive/pkg/intent" + "github.com/hivecommons/hive/pkg/stagelabels" ) const ( @@ -1681,3 +1683,31 @@ func TestContributorLaneAssociationTrusted(t *testing.T) { t.Fatal("nil PR must not be trusted") } } + +func TestContributorTrustedChangeRequestAnswersRequiresHuman(t *testing.T) { + fx := validContributorFixture() + fx.reviews = []map[string]any{humanReview(1, "clubanderson", "CHANGES_REQUESTED", "sha7", "please fix the metadata")} + api := newContributorLaneAPI(t, &fx) + defer api.Close() + policy := defaultContributorLanePolicy() + clock := &contributorLaneClock{at: time.Date(2026, 10, 28, 3, 0, 0, 0, time.UTC)} + engine := newContributorLaneEngine(api.URL, policy, clock, Options{ + ContributorLaneVerdict: func(string, int, string) ContributorLaneVerdict { + return ContributorLaneVerdict{Configured: true, Verdict: "requires_human", DecisionRequested: true} + }, + }) + engine.SetMergerAuthorizer(func(login string) bool { return login == "clubanderson" }) + engine.stageTracker = NewStageTracker() + engine.stageLabelPolicy = func() StageLabelPolicy { return StageLabelPolicy{Enabled: true} } + _, reason, err := engine.trySweepContributorLanePR(context.Background(), "widget", "acme", "widget", 7, policy) + if err != nil || reason != contributorLaneReasonChangesRequested || fx.merges != 0 { + t.Fatalf("reason=%s err=%v merges=%d", reason, err, fx.merges) + } + detail := engine.stageTracker.details[stageKey("acme", "widget", 7)] + // Production observations include the author kind; the lane alone does + // not distinguish an automated contributor (072) from a human (071). + o := stageObservation{AuthorKind: authorkind.Clanker, Lane: stageLaneContributor, HeadSHA: "sha7", Reason: reason, Detail: detail} + if v := classifyStage(o); v.Stage != stagelabels.ReturnedToContributor { + t.Fatalf("stage=%+v, want returned to contributor", v) + } +} diff --git a/src/pkg/github/automerge/automerge_human_changes_requested.go b/src/pkg/github/automerge/automerge_human_changes_requested.go index ecc61d8ac8..51e79e539e 100644 --- a/src/pkg/github/automerge/automerge_human_changes_requested.go +++ b/src/pkg/github/automerge/automerge_human_changes_requested.go @@ -20,6 +20,12 @@ import ( // already pushed past it, and the new head goes through the normal swarm // re-review rather than another kick. func (c *Engine) latestTrustedHumanChangesRequested(ctx context.Context, owner, repo string, number int, head string) (*gh.PullRequestReview, bool) { + return c.latestTrustedHumanReview(ctx, owner, repo, number, head, "CHANGES_REQUESTED") +} + +// latestTrustedHumanReview reads all pages before selecting an opinion. An +// older approval must never shadow a later change request or dismissal. +func (c *Engine) latestTrustedHumanReview(ctx context.Context, owner, repo string, number int, head, state string) (*gh.PullRequestReview, bool) { if c == nil || c.gh == nil || strings.TrimSpace(head) == "" { return nil, false } @@ -54,7 +60,7 @@ func (c *Engine) latestTrustedHumanChangesRequested(ctx context.Context, owner, c.noteStageReviews(owner, repo, number, seen) var found *gh.PullRequestReview for login, rv := range latest { - if !strings.EqualFold(rv.GetState(), "CHANGES_REQUESTED") || strings.TrimSpace(rv.GetCommitID()) != strings.TrimSpace(head) { + if !strings.EqualFold(rv.GetState(), state) || strings.TrimSpace(rv.GetCommitID()) != strings.TrimSpace(head) { continue } if c.isHiveAppReviewAuthor(rv) || strings.HasSuffix(login, "[bot]") { @@ -88,10 +94,26 @@ func (c *Engine) humanChangesRequestedForHead(ctx context.Context, owner, repo s if c.humanChangeRequests == nil || strings.TrimSpace(head) == "" { return false } - standing, found := c.humanChangeRequests.For(owner+"/"+repo, number, strings.TrimSpace(head)) + standing, found := c.reconcileReviewBackedApproval(ctx, owner, repo, number, strings.TrimSpace(head)) if !found || standing.IsApproval() { return false } + // A later trusted approval on this same head can acknowledge a body- + // only fix. Persist it so the planner also stops scheduling a fix. + if approval, approved := c.latestTrustedHumanReview(ctx, owner, repo, number, head, "APPROVED"); approved && approval.GetSubmittedAt().After(standing.RecordedAt) { + req := review.HumanChangeRequest{ + Repo: owner + "/" + repo, Number: number, HeadSHA: head, + Source: review.HumanChangeRequestSourceReview, SourceID: approval.GetID(), + Actor: hgithub.SafeGetLogin(approval.GetUser()), Body: approval.GetBody(), URL: approval.GetHTMLURL(), + Kind: review.HumanChangeRequestKindApprove, RecordedAt: approval.GetSubmittedAt().Time, + } + if err := c.humanChangeRequests.Record(req); err == nil { + c.noteStageTrustedHumanApproval(owner, repo, number, head, req.Actor) + return false + } else { + c.warn("could not record approval clearing human change request", "pr", number, "error", err) + } + } c.noteStageHumanChangeRequest(owner, repo, number, head, standing.Actor) return true } @@ -100,14 +122,15 @@ func (c *Engine) humanChangesRequestedForHead(ctx context.Context, owner, repo s return true } req := review.HumanChangeRequest{ - Repo: owner + "/" + repo, - Number: number, - HeadSHA: strings.TrimSpace(head), - Source: review.HumanChangeRequestSourceReview, - SourceID: rv.GetID(), - Actor: strings.TrimSpace(hgithub.SafeGetLogin(rv.GetUser())), - Body: rv.GetBody(), - URL: rv.GetHTMLURL(), + Repo: owner + "/" + repo, + Number: number, + HeadSHA: strings.TrimSpace(head), + Source: review.HumanChangeRequestSourceReview, + SourceID: rv.GetID(), + Actor: strings.TrimSpace(hgithub.SafeGetLogin(rv.GetUser())), + Body: rv.GetBody(), + URL: rv.GetHTMLURL(), + RecordedAt: rv.GetSubmittedAt().Time, } if existing, found := c.humanChangeRequests.For(req.Repo, number, req.HeadSHA); found && existing.Source == req.Source && existing.SourceID == req.SourceID { return true @@ -117,3 +140,29 @@ func (c *Engine) humanChangesRequestedForHead(ctx context.Context, owner, repo s } return true } + +// reconcileReviewBackedApproval returns the decision standing against head +// after dropping an approval-kind record that was persisted from a GitHub +// review which no longer stands: the reviewer dismissed it, or their latest +// opinion on head is not APPROVED any more. The revoked approval would +// otherwise keep answering requires_human and shadow the instruction +// recorded before it. Comment and dashboard decisions are durable and are +// never revalidated here. +func (c *Engine) reconcileReviewBackedApproval(ctx context.Context, owner, repo string, number int, head string) (review.HumanChangeRequest, bool) { + if c == nil || c.humanChangeRequests == nil || strings.TrimSpace(head) == "" { + return review.HumanChangeRequest{}, false + } + key := owner + "/" + repo + standing, found := c.humanChangeRequests.For(key, number, head) + if !found || !standing.IsApproval() || standing.Source != review.HumanChangeRequestSourceReview { + return standing, found + } + if live, ok := c.latestTrustedHumanReview(ctx, owner, repo, number, head, "APPROVED"); ok && live.GetID() == standing.SourceID { + return standing, true + } + if err := c.humanChangeRequests.Forget(key, number, standing.Source, standing.SourceID); err != nil { + c.warn("could not drop revoked review approval", "pr", number, "review", standing.SourceID, "error", err) + return review.HumanChangeRequest{}, false + } + return c.humanChangeRequests.For(key, number, head) +} 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 bd410cb065..ad5dac460d 100644 --- a/src/pkg/github/automerge/automerge_human_changes_requested_test.go +++ b/src/pkg/github/automerge/automerge_human_changes_requested_test.go @@ -4,6 +4,7 @@ import ( "context" "strings" "testing" + "time" "github.com/hivecommons/hive/pkg/review" "github.com/hivecommons/hive/pkg/stagelabels" @@ -228,3 +229,126 @@ func TestTrySweepSelfAuthoredPRRecordedDecisionNotesStageAndApprovalReleases(t * }) } } + +func TestHumanChangeRequestClearedByLaterApprovalWithoutNewHead(t *testing.T) { + for _, tc := range []struct { + name, login, head, state, submitted string + wantHeld bool + }{ + {"later trusted approval", "bob", "sha7", "APPROVED", "2026-10-28T02:00:00Z", false}, + {"old approval", "bob", "sha7", "APPROVED", "2026-10-28T00:00:00Z", true}, + {"approval on another head", "bob", "sha6", "APPROVED", "2026-10-28T02:00:00Z", true}, + {"untrusted approval", "mallory", "sha7", "APPROVED", "2026-10-28T02:00:00Z", true}, + {"still requesting changes", "bob", "sha7", "CHANGES_REQUESTED", "2026-10-28T02:00:00Z", true}, + } { + t.Run(tc.name, func(t *testing.T) { + rv := humanReview(2, tc.login, tc.state, tc.head, "metadata fix checked") + rv["submitted_at"] = tc.submitted + api := newSelfSweepGuardAPI(t, selfSweepFixture{reviews: []map[string]any{rv}}) + defer api.Close() + c := newAutoMergeSweepClient(api.URL) + store := review.NewHumanChangeRequests("") + c.humanChangeRequests = store + at, err := time.Parse(time.RFC3339, "2026-10-28T01:00:00Z") + if err != nil { + t.Fatal(err) + } + if err := store.Record(review.HumanChangeRequest{Repo: "acme/widget", Number: 7, HeadSHA: "sha7", Source: review.HumanChangeRequestSourceDecision, SourceID: 99, Actor: "bob", Body: "edit body", RecordedAt: at}); err != nil { + t.Fatal(err) + } + for i := 0; i < 2; i++ { + if held := c.humanChangesRequestedForHead(context.Background(), "acme", "widget", 7, "sha7"); held != tc.wantHeld { + t.Fatalf("held=%v, want %v", held, tc.wantHeld) + } + if scheduled := review.HumanChangeRequestFor(store, "acme/widget", 7, "sha7") != nil; scheduled != tc.wantHeld { + t.Fatalf("planner still schedules=%v, want %v", scheduled, tc.wantHeld) + } + } + }) + } +} + +func TestTrustedHumanApprovalUsesLatestOpinion(t *testing.T) { + api := newSelfSweepGuardAPI(t, selfSweepFixture{reviews: []map[string]any{ + humanReview(1, "bob", "APPROVED", "sha7", ""), + humanReview(2, "bob", "CHANGES_REQUESTED", "sha7", "please fix"), + }}) + defer api.Close() + c := newAutoMergeSweepClient(api.URL) + if login, ok := c.latestTrustedHumanApproval(context.Background(), "acme", "widget", 7, "sha7"); ok { + t.Fatalf("obsolete approval from %s accepted", login) + } +} + +// A same-head APPROVED review persisted as an approval-kind decision must +// not outlive the review: once it is dismissed (or the reviewer's latest +// opinion on the head is no longer APPROVED), the record is dropped, the +// earlier instruction stands again and requires_human is unanswered. A +// comment-sourced approval is durable and is not revalidated. +func TestReviewBackedApprovalRevokedOnDismissal(t *testing.T) { + for _, tc := range []struct { + name, revoke, wantBody string + }{ + {"dismissed", "DISMISSED", "edit body"}, + // The fresh change request is now the newest instruction. + {"changes requested again", "CHANGES_REQUESTED", "metadata fix checked"}, + } { + t.Run(tc.name, func(t *testing.T) { + approval := humanReview(2, "bob", "APPROVED", "sha7", "metadata fix checked") + approval["submitted_at"] = "2026-10-28T02:00:00Z" + api := newSelfSweepGuardAPI(t, selfSweepFixture{reviews: []map[string]any{approval}}) + defer api.Close() + c := newAutoMergeSweepClient(api.URL) + store := review.NewHumanChangeRequests("") + c.humanChangeRequests = store + at, err := time.Parse(time.RFC3339, "2026-10-28T01:00:00Z") + if err != nil { + t.Fatal(err) + } + if err := store.Record(review.HumanChangeRequest{Repo: "acme/widget", Number: 7, HeadSHA: "sha7", Source: review.HumanChangeRequestSourceDecision, SourceID: 99, Actor: "bob", Body: "edit body", RecordedAt: at}); err != nil { + t.Fatal(err) + } + if c.humanChangesRequestedForHead(context.Background(), "acme", "widget", 7, "sha7") { + t.Fatal("approval on the same head did not release the request") + } + if login, ok := c.trustedHumanApprovalForRequiresHuman(context.Background(), "acme", "widget", 7, "sha7", ContributorLaneVerdict{Configured: true, Verdict: "requires_human"}); !ok || login != "bob" { + t.Fatalf("approval not seen: %q %v", login, ok) + } + + // The reviewer takes the approval back without a new head. + approval["state"] = tc.revoke + approval["submitted_at"] = "2026-10-28T03:00:00Z" + if login, ok := c.trustedHumanApprovalForRequiresHuman(context.Background(), "acme", "widget", 7, "sha7", ContributorLaneVerdict{Configured: true, Verdict: "requires_human"}); ok { + t.Fatalf("revoked review approval still answers requires_human as %q", login) + } + if !c.humanChangesRequestedForHead(context.Background(), "acme", "widget", 7, "sha7") { + t.Fatal("instruction recorded before the revoked approval no longer holds the lane") + } + req := review.HumanChangeRequestFor(store, "acme/widget", 7, "sha7") + if req == nil || req.Body != tc.wantBody { + t.Fatalf("planner instruction = %+v, want %q", req, tc.wantBody) + } + if got, ok := store.Lookup("acme/widget", 7, review.HumanChangeRequestSourceReview, 2); ok && got.IsApproval() { + t.Fatal("revoked review approval still persisted") + } + }) + } +} + +func TestCommentApprovalSurvivesReviewDismissal(t *testing.T) { + dismissed := humanReview(2, "bob", "DISMISSED", "sha7", "") + api := newSelfSweepGuardAPI(t, selfSweepFixture{reviews: []map[string]any{dismissed}}) + defer api.Close() + c := newAutoMergeSweepClient(api.URL) + store := review.NewHumanChangeRequests("") + c.humanChangeRequests = store + if err := store.Record(review.HumanChangeRequest{Repo: "acme/widget", Number: 7, HeadSHA: "sha7", Source: review.HumanChangeRequestSourceDecision, SourceID: 4242, Actor: "bob", Body: "approve", Kind: review.HumanChangeRequestKindApprove}); err != nil { + t.Fatal(err) + } + if login, ok := c.trustedHumanApprovalForRequiresHuman(context.Background(), "acme", "widget", 7, "sha7", ContributorLaneVerdict{Configured: true, Verdict: "requires_human"}); !ok || login != "bob" { + t.Fatalf("durable /hive decision approve dropped: %q %v", login, ok) + } + if c.humanChangesRequestedForHead(context.Background(), "acme", "widget", 7, "sha7") { + t.Fatal("durable approval read as a change request") + } +} diff --git a/src/pkg/github/automerge/automerge_review_gate.go b/src/pkg/github/automerge/automerge_review_gate.go index 26b6c70ae4..5671beb9b6 100644 --- a/src/pkg/github/automerge/automerge_review_gate.go +++ b/src/pkg/github/automerge/automerge_review_gate.go @@ -312,43 +312,13 @@ func reviewGateRecordLane(lane string) string { } func (c *Engine) latestTrustedHumanApproval(ctx context.Context, owner, repo string, number int, head string) (string, bool) { - if c == nil || c.gh == nil { + rv, ok := c.latestTrustedHumanReview(ctx, owner, repo, number, head, "APPROVED") + if !ok { return "", false } - if ctx == nil { - ctx = context.Background() - } - opts := &gh.ListOptions{PerPage: 100} - var seen []*gh.PullRequestReview - for { - reviews, resp, err := c.gh.PullRequests.ListReviews(ctx, owner, repo, number, opts) - if err != nil { - c.warn("automerge review gate could not read PR reviews for human approval", "owner", owner, "repo", repo, "pr", number, "error", err) - return "", false - } - seen = append(seen, reviews...) - for _, review := range reviews { - if !strings.EqualFold(review.GetState(), "APPROVED") || strings.TrimSpace(review.GetCommitID()) != head { - continue - } - login := strings.TrimSpace(hgithub.SafeGetLogin(review.GetUser())) - if login == "" || c.isHiveAppReviewAuthor(review) || strings.HasSuffix(strings.ToLower(login), "[bot]") { - continue - } - trusted, configured := c.isTrustedMerger(login) - if configured && trusted { - c.noteStageReviews(owner, repo, number, seen) - c.noteStageTrustedHumanApproval(owner, repo, number, head, login) - return login, true - } - } - if resp.NextPage == 0 { - break - } - opts.Page = resp.NextPage - } - c.noteStageReviews(owner, repo, number, seen) - return "", false + login := strings.TrimSpace(hgithub.SafeGetLogin(rv.GetUser())) + c.noteStageTrustedHumanApproval(owner, repo, number, head, login) + return login, true } func (c *Engine) trustedHumanApprovalForRequiresHuman(ctx context.Context, owner, repo string, number int, head string, verdict ContributorLaneVerdict) (string, bool) { @@ -358,6 +328,9 @@ func (c *Engine) trustedHumanApprovalForRequiresHuman(ctx context.Context, owner if login, ok := c.latestTrustedHumanApproval(ctx, owner, repo, number, head); ok { return login, true } + // No live trusted approval on head: a persisted review-backed approval + // is revoked, so drop it before reading the recorded decision. + c.reconcileReviewBackedApproval(ctx, owner, repo, number, head) return c.recordedHumanApprovalForHead(owner, repo, number, head) } diff --git a/src/pkg/github/issue_unpark_command.go b/src/pkg/github/issue_unpark_command.go index 8f10375ead..16e64f6704 100644 --- a/src/pkg/github/issue_unpark_command.go +++ b/src/pkg/github/issue_unpark_command.go @@ -99,12 +99,22 @@ type unparkCommand struct { 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": +// Approval reports whether the decision explicitly approves the head: the +// first word is `approve`, `approved` or `lgtm` (trailing punctuation +// ignored) and the rest is retained as the approval rationale. A bare `yes` +// approves too, but `yes, but …` is a conditional answer and stays an +// instruction for the fix lane (hivecommons/hive#14816). +func (c unparkCommand) Approval() bool { + text := strings.TrimSpace(c.DecisionText()) + words := strings.Fields(text) + if len(words) == 0 { + return false + } + switch strings.ToLower(strings.TrimRight(words[0], ".:,;!")) { + case "approve", "approved", "lgtm": return true + case "yes": + return len(words) == 1 } return false } @@ -155,7 +165,7 @@ type IssueUnparkSweepOptions struct { LabelApprovalAudit func(IssueLabelApprovalEvent) // HumanChangeRequests receives `/hive decision ` left by a trusted // maintainer on a hive-authored PR parked at stage/085-needs-decision - // (hivecommons/hive#13041); the review planner turns it into a fix kick. + // or stage/070-fixing; the review planner turns instructions into a fix kick. // nil means the sweep answers the PR but cannot route the decision. HumanChangeRequests review.HumanChangeRequestStore // TrustedMerger is the automerge lane's merger trust test. A PR-side @@ -179,7 +189,7 @@ type PullRequestDecisionEvent struct { Actor string Decision string // Mode is "changes_requested" (the decision carries an instruction) - // or "approve" (a bare `/hive decision approve`). + // or "approve" (an approval word followed by optional rationale). Mode string CommentURL string } @@ -311,9 +321,9 @@ func (c *Client) SweepIssueUnparkCommands(ctx context.Context, opts IssueUnparkS } } // Otherwise PRs take one command only — `/hive decision` - // while parked at 085 (hivecommons/hive#13041) — and never a + // while at 085 or 070 — and never a // notice. - if !labelPresent(labels, PRNeedsDecisionStageLabel) { + if !labelPresent(labels, PRNeedsDecisionStageLabel) && !labelPresent(labels, stagelabels.Fixing.Label()) { continue } result.Seen++ diff --git a/src/pkg/github/issue_unpark_command_test.go b/src/pkg/github/issue_unpark_command_test.go index d8b5e4ce1d..a246e94a54 100644 --- a/src/pkg/github/issue_unpark_command_test.go +++ b/src/pkg/github/issue_unpark_command_test.go @@ -1243,16 +1243,15 @@ func TestSweepClosedIssueStageLabelsCap(t *testing.T) { } // 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. +// approve` followed by rationale retains the whole text and reads as approval. 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) + if !cmd.Approval() { + t.Fatalf("approve with rationale did not read as 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) { @@ -1261,12 +1260,12 @@ func TestParseUnparkCommandKeepsDecisionTextAfterFirstLine(t *testing.T) { } 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() == "" { + if !ok || !cmd.Approval() || 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() { + if single.DecisionText() != "keep 10 stable tags" || single.Approval() { t.Fatalf("single-line decision = %+v", single) } } diff --git a/src/pkg/github/pr_issue_link.go b/src/pkg/github/pr_issue_link.go index 9732d80c96..200d933efd 100644 --- a/src/pkg/github/pr_issue_link.go +++ b/src/pkg/github/pr_issue_link.go @@ -254,11 +254,20 @@ func (c *Client) EnsureIssueStagePRLink(ctx context.Context, repo string, issueN Name string `json:"name"` } `json:"defaultBranchRef"` PullRequest struct { - State string `json:"state"` - BaseRefName string `json:"baseRefName"` - Body string `json:"body"` - URL string `json:"url"` - Author struct { + State string `json:"state"` + BaseRefName string `json:"baseRefName"` + Body string `json:"body"` + URL string `json:"url"` + LastEditedAt string `json:"lastEditedAt"` + Comments struct { + Nodes []struct { + Body string `json:"body"` + Author struct { + Login string `json:"login"` + } `json:"author"` + } `json:"nodes"` + } `json:"comments"` + Author struct { Login string `json:"login"` } `json:"author"` } `json:"pullRequest"` @@ -272,6 +281,8 @@ func (c *Client) EnsureIssueStagePRLink(ctx context.Context, repo string, issueN baseRefName body url + lastEditedAt + comments(last:100) { nodes { body author { login } } } author { login } } } @@ -303,8 +314,23 @@ func (c *Client) EnsureIssueStagePRLink(ctx context.Context, repo string, issueN res.StageComment = issueStagePRLinkComment(prURL, claim.PRNumber, "GitHub only shows its linked-PR icon for closing-keyword PRs that target the repository default branch; this PR targets `"+res.Base+"`, so Hive cannot make GitHub display that icon for this issue.") return res, nil } + // A human decision is stronger than a missing-closing-keyword repair. + // Preserve the author's applied metadata even across subsequent heads. + decided := strings.Contains(pr.Body, prDecisionHeadMarker) + for _, comment := range pr.Comments.Nodes { + if c.isOwnBotLogin(comment.Author.Login) && strings.Contains(comment.Body, prDecisionHeadMarker) { + decided = true + } + } + if decided { + res.Skipped = "human-decision" + res.StageComment = issueStagePRLinkComment(prURL, claim.PRNumber, "A recorded human decision governs this PR; Hive will not add a closing keyword over that decision.") + return res, nil + } if claim.Reference { - if body, ok := rewriteRefsIssueLinkToClosing(pr.Body, owner+"/"+name, issueNumber); !claim.KeepReference && ok && c.isOwnBotLogin(pr.Author.Login) { + // An edited Refs body may be an intentional downgrade from Closes. + // Without edit-history proof, preserve it rather than re-arm auto-close. + if body, ok := rewriteRefsIssueLinkToClosing(pr.Body, owner+"/"+name, issueNumber); !claim.KeepReference && pr.LastEditedAt == "" && ok && c.isOwnBotLogin(pr.Author.Login) { if _, _, err := c.client.PullRequests.Edit(WithRESTCaller(ctx, "hive:issue_stage_pr_link"), owner, name, claim.PRNumber, &gh.PullRequest{Body: gh.Ptr(body)}); err != nil { return res, fmt.Errorf("EnsureIssueStagePRLink %s#%d->#%d edit body: %w", repo, issueNumber, claim.PRNumber, err) } @@ -339,7 +365,7 @@ func (c *Client) EnsureIssueStagePRLink(ctx context.Context, repo string, issueN func rewriteRefsIssueLinkToClosing(body, repo string, issue int) (string, bool) { // A watcher downgrade is intentional, even when the caller has no issue // body or child ledger available. Never re-arm auto-close through repair. - if body == "" || issue <= 0 || strings.Contains(body, issueLinkFixedMarker) || strings.Contains(body, closingKeywordWithheldNote) { + if body == "" || issue <= 0 || strings.Contains(body, issueLinkFixedMarker) || strings.Contains(body, prDecisionHeadMarker) || strings.Contains(body, closingKeywordWithheldNote) { return "", false } if _, ok := FindClosingKeywordReference(body, repo, repo, issue); ok { diff --git a/src/pkg/github/pr_issue_link_test.go b/src/pkg/github/pr_issue_link_test.go index d39463d4f0..71a38454d9 100644 --- a/src/pkg/github/pr_issue_link_test.go +++ b/src/pkg/github/pr_issue_link_test.go @@ -339,6 +339,7 @@ func TestRewriteRefsIssueLinkToClosingPreservesWatcherDowngrade(t *testing.T) { want bool }{ {"bare-reference", "Refs #7", true}, + {"recorded-decision", "Refs #7\n" + prDecisionHeadMarkerLine("head", prDecisionChangesRequested), false}, {"watcher-downgrade", "Refs #7" + downgradeNote("unfinished-delegated-work"), false}, {"watcher-downgrade-multiple-refs", "Refs #7" + downgradeNote("unfinished-delegated-work") + "\nRefs #8", false}, } { @@ -355,13 +356,16 @@ func TestRewriteRefsIssueLinkToClosingPreservesWatcherDowngrade(t *testing.T) { } type issueStagePRLinkFixture struct { - body string - base string - defaultBranch string - author string - state string - patches atomic.Int32 - patchedBody string + lastEditedAt string + decisionBody string + decisionAuthor string + body string + base string + defaultBranch string + author string + state string + patches atomic.Int32 + patchedBody string } func (f *issueStagePRLinkFixture) handler(t *testing.T) http.HandlerFunc { @@ -387,11 +391,13 @@ func (f *issueStagePRLinkFixture) handler(t *testing.T) http.HandlerFunc { "repository": map[string]any{ "defaultBranchRef": map[string]any{"name": f.defaultBranch}, "pullRequest": map[string]any{ - "state": f.state, - "baseRefName": f.base, - "body": f.body, - "url": "https://github.com/hivecommons/hive/pull/1", - "author": map[string]any{"login": f.author}, + "state": f.state, + "baseRefName": f.base, + "body": f.body, + "lastEditedAt": f.lastEditedAt, + "comments": map[string]any{"nodes": []map[string]any{{"body": f.decisionBody, "author": map[string]string{"login": f.decisionAuthor}}}}, + "url": "https://github.com/hivecommons/hive/pull/1", + "author": map[string]any{"login": f.author}, }, }, }}) @@ -490,3 +496,23 @@ func TestEnsureIssueStagePRLinkNeverEditsHumanPR(t *testing.T) { t.Fatalf("result=%+v patches=%d, want human no-op", got, f.patches.Load()) } } + +func TestEnsureIssueStagePRLinkPreservesOwnerReference(t *testing.T) { + for _, tc := range []struct { + name, edited, actor string + wantEdit bool + }{ + {name: "recorded decision", actor: "hive[bot]"}, + {name: "body edited after opening", edited: "2026-10-28T01:15:00Z"}, + {name: "untrusted pasted decision marker", actor: "outsider", wantEdit: true}, + } { + t.Run(tc.name, func(t *testing.T) { + f := &issueStagePRLinkFixture{body: "Refs #7 — further expectations remain open on the issue.", base: "v5", defaultBranch: "v5", author: "hive[bot]", lastEditedAt: tc.edited, decisionAuthor: tc.actor, decisionBody: prDecisionHeadMarkerLine("head", prDecisionChangesRequested)} + c := newIssueStagePRLinkClient(t, f) + got, err := c.EnsureIssueStagePRLink(context.Background(), "hivecommons/hive", 7, &IssueClaimContext{PRNumber: 1, Reference: true}) + if err != nil || got.EditedBody != tc.wantEdit || (f.patches.Load() > 0) != tc.wantEdit { + t.Fatalf("result=%+v err=%v patches=%d", got, err, f.patches.Load()) + } + }) + } +} diff --git a/src/pkg/github/pr_unpark_decision.go b/src/pkg/github/pr_unpark_decision.go index e897135894..ca5e08790f 100644 --- a/src/pkg/github/pr_unpark_decision.go +++ b/src/pkg/github/pr_unpark_decision.go @@ -16,13 +16,14 @@ import ( ) // tryUnparkPullRequest answers the newest eligible `/hive …` command on a PR -// parked at stage/085-needs-decision (hivecommons/hive#13041). A PR is not +// at stage/085-needs-decision or stage/070-fixing. A PR is not // an issue: there is no park label to clear and no "What to reply" notice, // because GitHub already gives a maintainer the two levers — an Approve // review merges the head, a changes-requested review sends it back. What // the sweep adds is the text path: // -// - `/hive decision ` on a hive-authored PR is a changes_requested +// - `/hive decision approve ` records approval for the head; +// - other `/hive decision ` on a hive-authored PR is a changes_requested // review in comment form: the decision is recorded against the head and // the review planner kicks the author agent with verbatim; // - `/hive decision` on a PR the hive did not open gets one reply naming @@ -147,7 +148,7 @@ 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 + // prDecisionApprove: `/hive decision approve` with optional rationale; the owner answered // the swarm's question with "yes" and the merge path takes over. prDecisionApprove prDecisionMode = "approve" ) @@ -160,7 +161,7 @@ func (m prDecisionMode) kind() string { } func prDecisionModeFor(cmd unparkCommand) prDecisionMode { - if cmd.BareApproval() { + if cmd.Approval() { return prDecisionApprove } return prDecisionChangesRequested diff --git a/src/pkg/github/pr_unpark_decision_test.go b/src/pkg/github/pr_unpark_decision_test.go index dec3ede984..a1d536b96b 100644 --- a/src/pkg/github/pr_unpark_decision_test.go +++ b/src/pkg/github/pr_unpark_decision_test.go @@ -145,10 +145,8 @@ func TestSweepIssueUnparkCommandsDecisionOnHivePRRoutesFixKick(t *testing.T) { } // 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. +// followed by a rationale remains an approval. The whole text is recorded, +// but no fix kick is scheduled. 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 { @@ -161,9 +159,9 @@ func TestSweepIssueUnparkCommandsDecisionApproveModes(t *testing.T) { 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: "approve with rationale → approve", body: instructions, + wantMode: "approve", wantKind: review.HumanChangeRequestKindApprove, + wantReply: []string{"Approval recorded by @clubanderson", "merge path", prDecisionHeadMarkerLine(liveDecisionHead, prDecisionApprove)}, }, { name: "bare approve → approve", body: "/hive decision approve", @@ -187,6 +185,10 @@ func TestSweepIssueUnparkCommandsDecisionApproveModes(t *testing.T) { if !ok || req.Kind != tc.wantKind || req.Actor != "clubanderson" { t.Fatalf("recorded = %+v, %v", req, ok) } + parsed, _ := parseUnparkCommand(tc.body) + if req.Body != parsed.DecisionText() { + t.Fatalf("recorded text = %q, want %q", req.Body, parsed.DecisionText()) + } 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) { @@ -389,8 +391,8 @@ func TestSweepIssueUnparkCommandsPRIgnoresUntrustedAndUnparked(t *testing.T) { wantSeen: 1, }, { - name: "PR not at 085 is not read", - issue: parkedPR(5, "hive[bot]", []string{"stage/070-fixing"}, humanComment(1, "clubanderson", "/hive decision do it")), + name: "PR outside 070 and 085 is not read", + issue: parkedPR(5, "hive[bot]", []string{"stage/060-reviewed"}, humanComment(1, "clubanderson", "/hive decision do it")), permissions: map[string]string{"clubanderson": "admin"}, trusted: trustedMergerSet("clubanderson"), }, @@ -535,3 +537,47 @@ func TestSweepIssueUnparkCommandsIgnoresHiveSelfDecision(t *testing.T) { t.Fatalf("real maintainer decision not recorded: %+v", result3) } } + +func TestDecisionApprovalReleasesFixingWithoutNewHead(t *testing.T) { + issue := parkedPR(liveDecisionPR, "hive[bot]", []string{"stage/070-fixing", "author/hive"}, humanComment(4243, "clubanderson", "/hive decision approve — the body change is applied")) + c, _ := newUnparkPRClient(t, []unparkWireIssue{issue}, 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: "change the PR body"}); err != nil { + t.Fatal(err) + } + result, err := c.SweepIssueUnparkCommands(context.Background(), IssueUnparkSweepOptions{HumanChangeRequests: store, TrustedMerger: trustedMergerSet("clubanderson")}) + if err != nil || len(result.PRDecisions) != 1 || result.PRDecisions[0].Mode != "approve" { + t.Fatalf("result=%+v err=%v", result, err) + } + if review.HumanChangeRequestFor(store, "org/repo", liveDecisionPR, liveDecisionHead) != nil { + t.Fatal("standing change request still schedules a fix") + } + facts := prDecisionFacts(t, c) + if len(facts) != 1 || facts[0].Instruction || facts[0].Head != liveDecisionHead { + t.Fatalf("stage facts=%+v", facts) + } +} + +func TestDecisionApprovalFirstWord(t *testing.T) { + for _, tc := range []struct { + text string + approve bool + }{ + {"approve because the metadata fix is applied", true}, + {"APPROVED: rationale on the next line\nCI is green", true}, + {"lgtm the decision is satisfied", true}, + {"yes", true}, + {"yes.", true}, + {"approve, the body change is applied", true}, + {"lgtm; ship it", true}, + {"yes, but rename the flag to --foo first", false}, + {"do not approve this", false}, + {"approve-later", false}, + {"change the body, then approve", false}, + } { + cmd, ok := parseUnparkCommand("/hive decision " + tc.text) + if !ok || cmd.Approval() != tc.approve { + t.Errorf("%q: %+v", tc.text, cmd) + } + } +} diff --git a/src/pkg/review/human_change_request.go b/src/pkg/review/human_change_request.go index 02068bd375..f24b91c6a7 100644 --- a/src/pkg/review/human_change_request.go +++ b/src/pkg/review/human_change_request.go @@ -102,6 +102,10 @@ type HumanChangeRequestStore interface { Record(req HumanChangeRequest) error // For returns the newest request recorded against repo#number at head. For(repo string, number int, head string) (HumanChangeRequest, bool) + // Forget drops the entry recorded from source/sourceID against + // repo#number, leaving every other entry (an older instruction on the + // same head included) standing. Unknown entries are a no-op. + Forget(repo string, number int, source string, sourceID int64) error } // HumanChangeRequests is the file-backed HumanChangeRequestStore. A zero @@ -224,6 +228,31 @@ func (s *HumanChangeRequests) For(repo string, number int, head string) (HumanCh return newest, found } +// Forget implements HumanChangeRequestStore. +func (s *HumanChangeRequests) Forget(repo string, number int, source string, sourceID int64) error { + if s == nil { + return errors.New("human change request store is nil") + } + repo = strings.TrimSpace(repo) + s.mu.Lock() + defer s.mu.Unlock() + s.load() + kept := s.items[:0] + dropped := false + for _, item := range s.items { + if item.Number == number && strings.EqualFold(item.Repo, repo) && item.Source == source && item.SourceID == sourceID { + dropped = true + continue + } + kept = append(kept, item) + } + if !dropped { + return nil + } + s.items = kept + return s.persist() +} + // 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.