From 23a75d2e4d36e0321cb8cd14eb8535f680bc7106 Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Wed, 28 Oct 2026 22:28:09 -0400 Subject: [PATCH 1/3] fix: clanker PRs with a human changes-requested review show Returned to contributor, not Sentinel alert A trusted human's CHANGES_REQUESTED review on the current head of a clanker-authored PR is the human the sentinel/hold/workflow-path parks were waiting for: RouteHuman and ClassifyStage now route it to stage/072-returned-to-contributor (071 for a person's PR, 070 for the hive's) ahead of 085, and the contributor lane reads reviews before it settles on sentinel-blocked. A new head re-arms the park (per head, as in #15216). Dashboard direction decisions are accepted on clanker PRs: the text is recorded as a change request against the head, posted to the contributor's hive, and the PR moves to 072; the 409 stays for a person's PR only. SPA: the 071/072 chevron keeps its routing word with the sentinel finding as a suffix; Give direction names the contributor's hive. Fixes #15255 Signed-off-by: Andrew Anderson --- .../fixed-clanker-returned-to-contributor.md | 1 + src/docs/api-reference.md | 2 +- src/docs/dashboard-sections.md | 2 + src/pkg/dashboard/api_repo_item_decision.go | 24 +++- src/pkg/dashboard/stage_tracker.go | 52 +++++++ .../dashboard/stage_tracker_adoption_test.go | 26 ++++ .../stage_tracker_row_actions_test.go | 1 + .../stage_tracker_sentinel_lane_test.go | 38 ++++- src/pkg/dashboard/stage_tracker_ui_test.go | 5 +- src/pkg/dashboard/static/index.html | 43 +++++- .../automerge/automerge_contributor_lane.go | 4 +- .../automerge_contributor_lane_test.go | 61 ++++++++ .../automerge_human_changes_requested.go | 24 ++++ .../github/automerge/automerge_stage_human.go | 7 + src/pkg/github/issue_unpark_command.go | 4 + src/pkg/github/pr_decision_operator.go | 79 ++++++++--- src/pkg/github/pr_decision_operator_test.go | 47 +++++++ src/pkg/github/pr_unpark_decision.go | 16 +++ src/pkg/github/stage_facts_sink.go | 9 ++ src/pkg/github/stage_facts_sink_test.go | 25 +++- src/pkg/stageengine/derive_pr_classify.go | 9 ++ .../derive_pr_returned_author_kind_test.go | 133 ++++++++++++++++++ src/pkg/stagelabels/human.go | 24 +++- src/pkg/stagelabels/human_test.go | 39 +++++ 24 files changed, 639 insertions(+), 36 deletions(-) create mode 100644 changelog.d/fixed-clanker-returned-to-contributor.md create mode 100644 src/pkg/stageengine/derive_pr_returned_author_kind_test.go diff --git a/changelog.d/fixed-clanker-returned-to-contributor.md b/changelog.d/fixed-clanker-returned-to-contributor.md new file mode 100644 index 0000000000..b60ef0fb50 --- /dev/null +++ b/changelog.d/fixed-clanker-returned-to-contributor.md @@ -0,0 +1 @@ +- Activity Monitor: a clanker-authored PR that a trusted human sends back with a CHANGES_REQUESTED review now shows **Returned to contributor** (072, actor the owning contributor, caption `Returned to @thatguywob's hive — @clubanderson requested changes`) instead of `Sentinel alert · needs human` — the human's review on the current head is the human the sentinel, hold and workflow-path parks were waiting for, so the sentinel pass no longer re-asserts 085 over 072 until a new head re-arms it (per head, like the dashboard Approve release). "Needs author" (071) stays a person's PR. The dashboard **Give direction** decision is accepted on clanker PRs too: the direction is posted to the contributor's hive as a change request and the row moves to 072; the 409 "the hive did not open this pull request" is kept only for a person's PR, which no hive can carry direction to. The 071/072 chevron keeps its routing word with any sentinel finding as a ` · sentinel` suffix ([#15159](https://github.com/hivecommons/hive/pull/15159)). diff --git a/src/docs/api-reference.md b/src/docs/api-reference.md index ade562be9b..84d722e300 100644 --- a/src/docs/api-reference.md +++ b/src/docs/api-reference.md @@ -285,7 +285,7 @@ Read the result from `GET /api/kick/{agent}/status`, which returns `status` of ` | `GET` | `/api/repos/{owner}/{repo}/hold-permission` | Dashboard auth/session | Reports whether the signed-in user can toggle hold chips for a repository card. Owners are allowed; otherwise the server checks GitHub `repos/{owner}/{repo}/collaborators/{user}/permission` and briefly caches the effective permission | `pkg/dashboard/api.go:333`, `pkg/dashboard/api_repo_hold.go` | | `GET` | `/api/repos/{owner}/{repo}/items/{number}` | Dashboard session | Per-item detail for the activity monitor's decision badge: `{repo, number, stage, stage_slug, operator_actions[], operator_action_count, last_operator_action}`. `operator_actions[]` is the server-side ledger of every row action submitted from the dashboard (hold/release, decision, decide-delegated, send-to-human, accept-triage — recorded by `recordOperatorAction` around those routes) as `{action, actor, at, note, target, outcome: pending|applied|no-op|failed, detail, head_sha, stage}`; `last_operator_action` adds the derived `state` (`waiting|addressed|stuck|pending|failed`), `stuck_after_seconds` and `followed[]` (the stage hops after the action). The same `last_operator_action` / `operator_action_count` ride every stage-tracker row and linked PR. Persisted in `/data/operator-actions.json`; `HIVE_OPERATOR_ACTION_STUCK_AFTER` (default `30m`) sets the stuck window. | `pkg/dashboard/api.go`, `pkg/dashboard/operator_actions.go` | | `POST` | `/api/repos/{owner}/{repo}/items/{number}/hold` | Owner or repo write/maintain/admin | Add or remove a dashboard hold chip for an issue or PR. Body `{"held": true}` adds the hive's exact-match canonical `hive-pause/` label; `{"held": false}` removes exactly the labels causing the hold (`hive-pause/` and/or generic hold labels) and never removes `hive/` provenance. Every toggle writes an audit-log entry; the #8851 upgrade migration writes `/data/hive-hold-migration-.json` with audit-backed, provenance-only, and ambiguous legacy `hive/` classifications. | `pkg/dashboard/api.go:337`, `pkg/dashboard/api_repo_hold.go` | -| `POST` | `/api/repos/{owner}/{repo}/items/{number}/decision` | Owner or repo write/maintain/admin, signed-in GitHub user | Record an operator decision from the activity monitor's row menu / selection bar. Body `{"decision": "approve"|"direction"|"close-superseded"|"close-wontfix", "comment": "…", "type": "issue"|"pr", "superseded_by": "#458"}`. On an issue parked at 045, `approve`/`direction` act exactly as a maintainer's `/hive approve` / `/hive decision ` comment would (labels, `approved-direction`, stage-engine Unparked fact, reply comment naming the operator). On a PR parked at 085 (`type: "pr"`), `approve` posts the `/lgtm` and `/approve` commands as two comments attributed to the operator, records the approval against the head as the human answer to a `requires_human` / decision-requested verdict (the lanes and the stage engine honour it like a trusted merger's Approve review), lifts `needs-human`, clears the sentinel label and acknowledges the bundle's sentinel findings for that head, re-derives the stage and drops the tracker cache — the response adds `released` (`approval-recorded`, `needs-human`, `sentinel-label`, `sentinel-acknowledged`) and `stage`; the merge gate decides from there (no review as the operator, no merge) — and `direction` records the text as a human change request against the head — the `/hive decision` fix lane — on a hive-authored PR only (409 otherwise). The close variants post a comment naming the operator (and the superseding PR when `superseded_by` is given) and close the item as not planned. Never merges. Every decision writes an audit-log entry (`repo_item_decision_*`). | `pkg/dashboard/api.go:338`, `pkg/dashboard/api_repo_item_decision.go` | +| `POST` | `/api/repos/{owner}/{repo}/items/{number}/decision` | Owner or repo write/maintain/admin, signed-in GitHub user | Record an operator decision from the activity monitor's row menu / selection bar. Body `{"decision": "approve"|"direction"|"close-superseded"|"close-wontfix", "comment": "…", "type": "issue"|"pr", "superseded_by": "#458"}`. On an issue parked at 045, `approve`/`direction` act exactly as a maintainer's `/hive approve` / `/hive decision ` comment would (labels, `approved-direction`, stage-engine Unparked fact, reply comment naming the operator). On a PR parked at 085 (`type: "pr"`), `approve` posts the `/lgtm` and `/approve` commands as two comments attributed to the operator, records the approval against the head as the human answer to a `requires_human` / decision-requested verdict (the lanes and the stage engine honour it like a trusted merger's Approve review), lifts `needs-human`, clears the sentinel label and acknowledges the bundle's sentinel findings for that head, re-derives the stage and drops the tracker cache — the response adds `released` (`approval-recorded`, `needs-human`, `sentinel-label`, `sentinel-acknowledged`) and `stage`; the merge gate decides from there (no review as the operator, no merge) — and `direction` records the text as a human change request against the head — the `/hive decision` fix lane — on a hive-authored PR, and on a contributor's clanker PR (`author/clanker` / hive attribution markers) where the text is posted to the contributor's hive and the PR moves to `stage/072-returned-to-contributor` (`status: "direction-returned-to-contributor"`); a person's PR, which no hive can carry direction to, answers 409. The close variants post a comment naming the operator (and the superseding PR when `superseded_by` is given) and close the item as not planned. Never merges. Every decision writes an audit-log entry (`repo_item_decision_*`). | `pkg/dashboard/api.go:338`, `pkg/dashboard/api_repo_item_decision.go` | | `POST` / `GET` | `/api/repos/{owner}/{repo}/items/{number}/decide-delegated` | Same as `…/hold` (owner or repo write), signed-in GitHub user; `decisions.delegate.enabled` (403 when off) | *Let hive decide*: enqueue a delegated-decision job in which the hive decides the parked item itself as the owner's delegate under `pkg/delegatedecision.PolicyText` and records it as a human decision (`/hive decision` comment with the `` marker, park labels off, `triage/accepted`, queue approval on a PR head). Body `{"type": "issue"|"pr", "reason", "caption", "sentinel_reason"}`. `POST` answers 202 with the job (`{id, status: "running"|"done"|"failed", decision: {verdict, rule, text, rationale, actions, keeps_park}, notes, error}`); 409 with the running job while one is in flight; `GET` reads it. Rails: never merges, refuses items wearing `hold`, never grants secrets/permissions (`needs-owner` + `hold` instead), recommends only on hive policy/governance questions (keeps 085). Audited as `repo_item_decision_delegated[_failed]`. See [dashboard-sections.md](dashboard-sections.md#let-hive-decide). | `pkg/dashboard/api.go:329`, `pkg/dashboard/api_repo_item_decide_delegated.go` | | `POST` | `/api/repos/{owner}/{repo}/items/{number}/accept-triage` | Owner or repo write/maintain/admin | Accept triage on an issue from the activity monitor's row menu — what a maintainer accepting triage on GitHub does by hand: adds the reporter-trust triage label (`triage/accepted`, or the first of `issue_filter.reporter_trust.untrusted_require_labels`; the label is created in the repo if missing) and removes the awaiting label (`needs-triage` / `reporter_trust.awaiting_label`) and a Hive-written `stage/015-triage-needed`. Empty body. Returns `{ok, repo, number, acceptLabel, added, removed, alreadyAccepted, minStatusSeq}`; an issue already carrying the accept label with nothing left to remove is a no-op (`alreadyAccepted: true`, no write, no audit). 404 for a pull request or an unknown item. The status snapshot's labels are patched so the next reconcile reads 010 Actionable before the engine's own 015 → 010 derivation. Every write is audited as `repo_item_accept_triage` under the dashboard user. | `pkg/dashboard/api.go:532`, `pkg/dashboard/api_repo_item_accept_triage.go` | | `GET` | `/api/acmm/evaluation` | Dashboard auth/session | ACMMEvaluation — combined codebase + operational result, cached server-side for 1 hour (`acmmEvalTTL`). `?refresh=1` (the dashboard's "🔄 Re-evaluate" button, #5877) bypasses the hourly TTL but is debounced server-side: requests within 1 minute of the last evaluation (`acmmRefreshDebounce`) still serve the cache, since a full refresh costs up to ~29 GitHub GetContents calls per repo. The response's `last_evaluated_at` timestamp reports when the cached evaluation was computed | `pkg/dashboard/api.go:342`, `pkg/dashboard/api_acmm_eval.go` | diff --git a/src/docs/dashboard-sections.md b/src/docs/dashboard-sections.md index 289254664a..dc319897f5 100644 --- a/src/docs/dashboard-sections.md +++ b/src/docs/dashboard-sections.md @@ -682,6 +682,8 @@ Fed by `GET /api/stage-tracker`. Every issue and pull request follows the same p | `needs human decision` (`needs-decision` labels on another stage) | merge gate | PR at stage/080 or later; always on an issue at its own stage | | history decision badge (`last_operator_action`) | before the pills; the history mark + action count, neutral / amber (still at the same stage past the stuck window) / red (failed) / dotted (hive deciding) | always, once a row action was submitted from the dashboard; tooltip tells what you chose, when, and what the hive did next | +**Returned to a contributor's hive (072).** `stage/071-needs-author` is a person's PR: a human-authored pull request sent back by a maintainer's CHANGES_REQUESTED review or by the review swarm. The same verdict on a clanker-authored PR (`author/clanker`, or an author resolved to a contributor's hive agent) routes to `stage/072-returned-to-contributor`, whichever lane carried it: the actor is the owning contributor, the caption reads `Returned to @thatguywob's hive — @clubanderson requested changes`, and the normal contributor nudge goes to that hive ([hivecommons/hive#15159](https://github.com/hivecommons/hive/pull/15159): a human's out-of-cycle review on a clanker PR parked it at 071 under a maintainer's name). The 071/072 chevron names the routing — `Needs @sam`, `Returned to @thatguywob's hive` — and a sentinel finding on such a row is a ` · sentinel` suffix on that word (the chip folds into it, the tooltip carries the finding); `Sentinel alert · needs human` is only the chevron word when the maintainer's review is still outstanding (085). A trusted human's CHANGES_REQUESTED review on the current head *is* the human those parks (sentinel alert, `hold`, workflow-path) were waiting for: the PR routes to 071/072 and the sentinel pass does not re-assert 085 until a new head re-arms the alert. **Give direction** on a clanker PR is accepted as well — the direction is posted to the contributor's hive as a change request and the row moves to 072; only a person's PR, which no hive can carry direction to, still answers `409 the hive did not open this pull request`. + **Adoption pill (072).** A nudged `author/clanker` pull request at `stage/072-returned-to-contributor` carries `adoption{author, due, blocked_by, since, nudges, author_online, author_registered, author_last_seen, author_maintainer, policy, action, text}` — the nudge count and first-nudge time from the stage record, the author's live hub presence (the same lookup the contributor-offline adoption itself consults), and, when the adoption engine judged adoption due and held it, why (`blocked_by: author-is-maintainer`). The row's caption and an amber pill say it in plain words instead of a bare "Returned to contributor": `waiting on @hanthor (maintainer, offline 26h) — adopt?` under `governor.labels.stage.adoption.maintainer_policy: ask`, `waiting on @zoe (offline 40m, 2 nudges)` while the default `adopt` policy's clock runs, `… — not adopted: maintainer_policy is never` under `never` ([hivecommons/hive#14524](https://github.com/hivecommons/hive/pull/14524): the PR sat 26h at 072 with its author's hive gone and nothing on screen saying why). When `action` is `decide:adopt` the row also carries `decision_needed` (question "@hanthor maintains this repository and has been offline for 26h; adopt the PR?", `blocker_reason: adoption:author-is-maintainer`, options Adopt then Hold/Release), so the lit 072 chevron and the `adopt?` pill open the Needs-human popover, and the row menu and the selection bar offer **Adopt (hive takes over)** — same action-id vocabulary as the other `decide:*` entries — which, after an in-app confirm, POSTs `{"decision":"adopt"}` to the item's decision endpoint: the hive posts an attributed note, sets `adoption/supersede` (the owner-delegate's request label) and the next sweep adopts the head on the existing adopt/supersede path; the toast reads `adoption-queued`. Write access required; the action is absent when nothing is the owner's to decide. **Adopted → #N (074 / 085).** An adopted pull request names the hive's superseding copy in its detour word (`adopted_by`). When that copy was closed without merging (hivecommons/hive#15052) the row does not fall back to *Needs human decision*: `adopted_by_state: "closed"` renders "Adopted → #N (closed) · recovering" while the hive opens a fresh copy from the same head, and the caption says so in plain words; once the new copy is on record the word reads "Adopted → #M". If two copies are closed within an hour the hive stops (`adopted_by_state: "closed-twice"`, park reason `adoption-child-closed-twice`): the row reads "Adopted → #N (closed twice) · needs a person" and the popover question asks you to reopen the last copy, give direction, or close the PR. With close-first supersession (the default, hivecommons/hive#15135) the original is closed in the adopting pass and has **no row** while its copy is open — the copy is the one active PR for the issue, and the original's record is superseded (no chevron, no *Needs human decision*). A copy that then fails (closed unmerged, or red at two heads) reopens the original: `adopted_by_state: "copy-failed"` renders "Adopted → #N (copy failed) · reopened, needs a person" at 085 with the caption "The hive's copy #N failed; this PR was reopened and needs a person". diff --git a/src/pkg/dashboard/api_repo_item_decision.go b/src/pkg/dashboard/api_repo_item_decision.go index 8685500dfd..a78f1d6fb6 100644 --- a/src/pkg/dashboard/api_repo_item_decision.go +++ b/src/pkg/dashboard/api_repo_item_decision.go @@ -38,7 +38,10 @@ import ( // (hivecommons/hive#14821, #14822, crux#30). // - direction → `/hive decision `; the comment is required. On // a hive-authored PR it is recorded as a human change request so the -// author agent is kicked with it (Client.RecordOperatorPullRequestDecision). +// author agent is kicked with it (Client.RecordOperatorPullRequestDecision); +// on a contributor's clanker PR it is recorded the same way and carried +// to that contributor's hive — the PR goes to 072 returned-to-contributor +// (hivecommons/hive#15159). A PR a person opened answers 409. // - close-superseded / close-wontfix → one comment naming the operator // (and, when given, the superseding PR), then a not_planned close (a PR // takes the supersession sweep's own labelled close path). @@ -220,6 +223,11 @@ type repoItemApproveFacts struct { // because Prow already rejected the hive's commands on this PR // (dibs#510); the hive's own approval record is what counts. CommandsSkipped bool + + // ToContributor is the contributor whose hive a direction was carried + // to (a clanker-authored PR, hivecommons/hive#15159); "" when the + // hive's own author agent takes it. + ToContributor string } // repoItemDecisionResult reads a recorded human decision into the shared @@ -242,7 +250,9 @@ func repoItemDecisionResultWith(repoFull string, number int, itemType, decision, case repoItemDecisionDirection: out.Action = rowActionDirected out.Outcome = "Direction recorded as `/hive decision`: " + strings.TrimSuffix(strings.TrimSpace(comment), ".") + "." - if itemType == "pr" { + if itemType == "pr" && strings.TrimSpace(facts.ToContributor) != "" { + out.Next = "Returned to @" + strings.TrimPrefix(strings.TrimSpace(facts.ToContributor), "@") + "'s hive with your direction; the row moves when it pushes a new head." + } else if itemType == "pr" { out.Next = "The author agent pushes a new head; the row moves when it lands." } else { out.Next = "The hive carries on with that direction; nothing is merged." @@ -598,6 +608,7 @@ func (s *Server) handlePullRequestDecision(ctx context.Context, w http.ResponseW var released []string stage, commandsSkipped := "", "" sentinelOpen, prow := false, false + toContributor := "" if decision == repoItemDecisionApprove { var event ghpkg.PullRequestApprovalEvent event, err = gh.RecordOperatorPullRequestApprovalWith(ctx, repoFull, number, user, ghpkg.PullRequestApprovalOptions{ @@ -611,7 +622,7 @@ func (s *Server) handlePullRequestDecision(ctx context.Context, w http.ResponseW } else { var event ghpkg.PullRequestDecisionEvent event, err = gh.RecordOperatorPullRequestDecision(ctx, repoFull, number, user, comment, repoItemDecisionChangeRequests()) - head = event.HeadSHA + head, toContributor = event.HeadSHA, event.ToContributor } switch { case errors.Is(err, ghpkg.ErrPullRequestNotFound): @@ -634,6 +645,9 @@ func (s *Server) handlePullRequestDecision(ctx context.Context, w http.ResponseW admitted := "" if decision == repoItemDecisionDirection { action, status = auditRepoItemDecisionDirection, "direction-recorded" + if toContributor != "" { + status = "direction-returned-to-contributor" + } } else { // The person's Approve is the trust override for this head: the // contributor lane merges it as-is and the adoption engine leaves @@ -642,13 +656,13 @@ func (s *Server) handlePullRequestDecision(ctx context.Context, w http.ResponseW released = append(released, "admitted") } } - s.audit.LogRecord(user, action, auditDetail("repo", repoFull, "number", numStr, "type", "pr", "head", head, "decision", comment, "released", strings.Join(released, ","), "stage", stage, "admitted_by", admitted, "commands_skipped", commandsSkipped), "", repoFull, number) + s.audit.LogRecord(user, action, auditDetail("repo", repoFull, "number", numStr, "type", "pr", "head", head, "decision", comment, "released", strings.Join(released, ","), "stage", stage, "admitted_by", admitted, "commands_skipped", commandsSkipped, "to_contributor", toContributor), "", repoFull, number) // The row's park was just answered: serve the re-derived stage on the // next tracker read instead of the cached 085. s.invalidateStageTrackerForWebhook() jsonResponse(w, repoItemDecisionResponse{OK: true, Repo: repoFull, Number: number, Decision: decision, Status: status, Released: released, Stage: stage, Head: head, AdmittedBy: admitted, CommandsSkipped: commandsSkipped, Result: repoItemDecisionResultWith(repoFull, number, "pr", decision, comment, "", "", repoItemApproveFacts{ - User: user, Released: released, Stage: stage, SentinelOpen: sentinelOpen, SentinelLabel: s.sentinelLabel(), SoakMinutes: s.approveSoakMinutes(admitted != ""), Prow: prow, CommandsSkipped: commandsSkipped != "", + User: user, Released: released, Stage: stage, SentinelOpen: sentinelOpen, SentinelLabel: s.sentinelLabel(), SoakMinutes: s.approveSoakMinutes(admitted != ""), Prow: prow, CommandsSkipped: commandsSkipped != "", ToContributor: toContributor, })}) } diff --git a/src/pkg/dashboard/stage_tracker.go b/src/pkg/dashboard/stage_tracker.go index e0fdf711b7..2d85ab8031 100644 --- a/src/pkg/dashboard/stage_tracker.go +++ b/src/pkg/dashboard/stage_tracker.go @@ -1300,6 +1300,9 @@ func humanizeStageReason(reason string) string { if rest, ok := strings.CutPrefix(r, "shared-ci-incident:"); ok { return "deferred to shared-CI incident #" + rest + " — not this PR's fault" } + if lower == stageengineprstage.AutoMergeReasonHumanChangesRequested { + return "a maintainer requested changes" + } if rest, ok := strings.CutPrefix(lower, "reviewer-verdict:"); ok { switch rest { case "changes_requested", "request_changes": @@ -1519,6 +1522,48 @@ func adoptedWorkCaption(reason string) string { return owned } +// stageTrackerReturnedToHiveCaption rewrites a 072 caption for a +// clanker-authored PR so it names whose hive the PR went back to and who +// sent it: "Returned to @thatguywob's hive — @clubanderson requested +// changes" (hivecommons/hive#15159). The human has already acted and +// nothing is owed by a maintainer, so the "@x must act" tail goes; the +// contributor's hive is the actor. +func stageTrackerReturnedToHiveCaption(caption, author string, requesters []string) string { + who := strings.TrimSpace(author) + if who == "" { + return caption + } + who = "@" + strings.TrimPrefix(who, "@") + head := "Returned to " + who + if !strings.HasPrefix(caption, head) { + return caption + } + rest := strings.TrimPrefix(caption, head) + rest = strings.Replace(rest, " — "+who+" must act", "", 1) + if by := mentionLogins(requesters); by != "" { + rest = strings.Replace(rest, " — a maintainer requested changes", " — "+by+" requested changes", 1) + } + return head + "'s hive" + rest +} + +// mentionLogins is "@a", "@a and @b" or "@a, @b and @c" for the given +// logins; "" when there are none. +func mentionLogins(logins []string) string { + out := make([]string, 0, len(logins)) + for _, l := range logins { + if l = strings.TrimPrefix(strings.TrimSpace(l), "@"); l != "" { + out = append(out, "@"+l) + } + } + switch len(out) { + case 0: + return "" + case 1: + return out[0] + } + return strings.Join(out[:len(out)-1], ", ") + " and " + out[len(out)-1] +} + func joinClause(head, clause string) string { if clause == "" { return head @@ -2083,6 +2128,13 @@ func (s *Server) buildStageTracker(status *StatusPayload, store *stagelabels.Sto it.Lane = laneHive } finish(&it, pr.Labels, labelStage(pr.Labels), rec, ok, pr.Draft) + if it.Stage == stagelabels.ReturnedToContributor.Number() && it.AuthorKind == authorKindClanker { + var requesters []string + if pr.Protection != nil { + requesters = pr.Protection.ChangesRequestedBy + } + it.Caption = stageTrackerReturnedToHiveCaption(it.Caption, it.Author, requesters) + } applyStageTrackerNew(&it, stageTrackerNewState(it, ok, issueFilter, status.Governor, now)) it.SentinelAlert, it.SentinelFindings, it.SentinelReason = s.stageTrackerSentinel(evidenceVerifier, repoName, pr.Number, pr.HeadSHA, pr.Labels) // The sentinel chip is a merge-gate pill too (the trusted-author diff --git a/src/pkg/dashboard/stage_tracker_adoption_test.go b/src/pkg/dashboard/stage_tracker_adoption_test.go index f2883bb38c..a3fbd580e6 100644 --- a/src/pkg/dashboard/stage_tracker_adoption_test.go +++ b/src/pkg/dashboard/stage_tracker_adoption_test.go @@ -376,3 +376,29 @@ func TestStageTrackerAdoptionPersonAuthoredSaysNotAdopted(t *testing.T) { } } } + +// hivecommons/hive#15159: a clanker-authored 072 row names whose hive the +// PR went back to and who sent it; the "@x must act" tail — a person's +// turn — goes. +func TestStageTrackerReturnedToHiveCaption(t *testing.T) { + cases := []struct { + caption string + requesters []string + want string + }{ + {"Returned to @thatguywob — a maintainer requested changes — @thatguywob must act", []string{"clubanderson"}, "Returned to @thatguywob's hive — @clubanderson requested changes"}, + {"Returned to @thatguywob — a maintainer requested changes — @thatguywob must act", nil, "Returned to @thatguywob's hive — a maintainer requested changes"}, + {"Returned to @thatguywob — a maintainer requested changes — @thatguywob must act (2 nudges sent)", []string{"a", "b"}, "Returned to @thatguywob's hive — @a and @b requested changes (2 nudges sent)"}, + {"Returned to @thatguywob — review swarm requested changes — @thatguywob must act", []string{"clubanderson"}, "Returned to @thatguywob's hive — review swarm requested changes"}, + {"Returned to @thatguywob — review swarm requested changes — waiting on @thatguywob (offline 2h)", nil, "Returned to @thatguywob's hive — review swarm requested changes — waiting on @thatguywob (offline 2h)"}, + {"Returned to contributor", nil, "Returned to contributor"}, + } + for _, tc := range cases { + if got := stageTrackerReturnedToHiveCaption(tc.caption, "thatguywob", tc.requesters); got != tc.want { + t.Errorf("%q → %q, want %q", tc.caption, got, tc.want) + } + } + if got := stageTrackerReturnedToHiveCaption("Returned to @x — @x must act", "", nil); got != "Returned to @x — @x must act" { + t.Errorf("no author changed the caption: %q", got) + } +} diff --git a/src/pkg/dashboard/stage_tracker_row_actions_test.go b/src/pkg/dashboard/stage_tracker_row_actions_test.go index 2c015bd1d1..39269218c2 100644 --- a/src/pkg/dashboard/stage_tracker_row_actions_test.go +++ b/src/pkg/dashboard/stage_tracker_row_actions_test.go @@ -792,6 +792,7 @@ func stageTrackerConfirmOptOutJS(t *testing.T, html string) string { jsFunc(t, html, "stageTrackerDelegateConfirm"), jsFunc(t, html, "stageTrackerDCOCaveat"), jsFunc(t, html, "stageTrackerActionPayload"), + jsFunc(t, html, "stageTrackerDirectionCarrier"), `const store = {}; global.localStorage = { getItem: k => (k in store ? store[k] : null), setItem: (k, v) => { store[k] = String(v); }, removeItem: k => { delete store[k]; } }; global.window = { _hiveUser: 'clubanderson' }; const dialogs = []; let dialogAnswer = true; diff --git a/src/pkg/dashboard/stage_tracker_sentinel_lane_test.go b/src/pkg/dashboard/stage_tracker_sentinel_lane_test.go index 2252cc7228..1dd3d3780b 100644 --- a/src/pkg/dashboard/stage_tracker_sentinel_lane_test.go +++ b/src/pkg/dashboard/stage_tracker_sentinel_lane_test.go @@ -29,6 +29,9 @@ func stageTrackerSentinelJS(t *testing.T, html string) string { jsFunc(t, html, "stageTrackerDeferredMods"), jsFunc(t, html, "stageTrackerSentinelTip"), jsFunc(t, html, "stageTrackerSentinelInLane"), + jsFunc(t, html, "stageTrackerSentinelAsSuffix"), + jsFunc(t, html, "stageTrackerReturnedWord"), + jsFunc(t, html, "stageTrackerDirectionCarrier"), jsFunc(t, html, "stageTrackerSentinelChipHtml"), }, "\n") } @@ -271,7 +274,7 @@ func TestStageTrackerSentinelLaneWiring(t *testing.T) { `function stageTrackerSentinelInLane(item)`, `function stageTrackerSentinelChipHtml(item)`, `function stageTrackerSentinelPreface(items)`, - `sentinel ? 'ham-sentinel' : ''`, + `sentinel || sentinelSuffix ? 'ham-sentinel' : ''`, `.ham-badge-sentinel { color: var(--status-error);`, `.ham-seg.active.ham-sentinel { background: var(--status-error); color: var(--surface-0); }`, `const sentinel = id.indexOf('decide:') === 0 ? stageTrackerSentinelPreface(items) : '';`, @@ -371,7 +374,38 @@ assert.ok(!review.includes('ham-sentinel"'), 'the chevron is not tinted off the const noMods = stageTrackerRowHtml(P('o/r', 110, 50, flagged), stages, ctx); assert.ok(noMods.includes('ham-badge-sentinel') && !noMods.includes('ham-badge-mod'), 'chip alone when there are no modifiers'); const generic = stageTrackerRowHtml(P('o/r', 110, 71, { sentinel_alert: true }), stages, ctx); -assert.ok(generic.includes('title="Sentinel flagged security-relevant changes: ' + esc(STAGE_TRACKER_SENTINEL_TIP_FALLBACK) + '"'), 'generic tooltip without a reason: ' + generic); +assert.ok(generic.includes('Sentinel flagged security-relevant changes: ' + esc(STAGE_TRACKER_SENTINEL_TIP_FALLBACK)), 'generic tooltip without a reason: ' + generic); + +// 071/072 + sentinel (hivecommons/hive#15159): the chevron keeps the +// routing word — the human already acted — with the alert as a suffix, +// never "needs human"; the chip is folded into the word. +assert.strictEqual(stageTrackerReturnedWord({ stage: 72, kind: 'pr', author: 'thatguywob', author_kind: 'clanker' }, 'Returned to contributor'), "Returned to @thatguywob's hive"); +assert.strictEqual(stageTrackerReturnedWord({ stage: 72, kind: 'pr', author: 'sam', author_kind: 'human' }, 'Returned to contributor'), 'Returned to @sam'); +assert.strictEqual(stageTrackerReturnedWord({ stage: 71, kind: 'pr', author: 'sam' }, 'Needs author'), 'Needs @sam'); +assert.strictEqual(stageTrackerReturnedWord({ stage: 72, kind: 'pr' }, 'Returned to contributor'), 'Returned to contributor', 'no author → stage word'); +assert.strictEqual(stageTrackerReturnedWord(Object.assign({ stage: 72, kind: 'pr', author: 'thatguywob', author_kind: 'clanker' }, flagged), 'x'), "Returned to @thatguywob's hive · sentinel"); +assert.ok(stageTrackerSentinelAsSuffix(P('o/r', 1, 72, flagged)) && stageTrackerSentinelAsSuffix(P('o/r', 1, 71, flagged))); +assert.ok(!stageTrackerSentinelAsSuffix(P('o/r', 1, 85, flagged)) && !stageTrackerSentinelAsSuffix(I('o/r', 1, 72, flagged))); +const returned = stageTrackerRowHtml(P('o/r', 15159, 72, Object.assign({ author: 'thatguywob', author_kind: 'clanker' }, flagged)), stages, ctx); +const retLit = /
  • ]*)>([\s\S]*?)<\/li>/.exec(returned); +assert.ok(retLit, 'the lit 072 chevron is tinted: ' + returned); +assert.ok(retLit[2].includes("Returned to @thatguywob's hive · sentinel"), 'routing word with sentinel suffix: ' + retLit[2]); +assert.ok(!returned.includes('needs human') && !returned.includes('Needs human'), 'no needs-human wording at 072: ' + returned); +assert.ok(retLit[1].includes("aria-label=\"Returned to @thatguywob's hive · sentinel — " + TIP + '"'), 'aria names the routing: ' + retLit[1]); +assert.ok(retLit[1].includes(' — ' + TIP), 'the tooltip carries the reason: ' + retLit[1]); +assert.ok(!returned.includes('ham-badge-sentinel'), 'no chip when the word carries the suffix'); +const needsAuthor = stageTrackerRowHtml(P('o/r', 15160, 71, Object.assign({ author: 'sam', author_kind: 'human' }, flagged)), stages, ctx); +assert.ok(needsAuthor.includes('Needs @sam · sentinel') && !needsAuthor.includes('needs human'), needsAuthor); +const returnedClean = stageTrackerRowHtml(P('o/r', 15161, 72, { author: 'thatguywob', author_kind: 'clanker' }), stages, ctx); +assert.ok(returnedClean.includes("Returned to @thatguywob's hive") && !returnedClean.includes('ham-sentinel') && !returnedClean.includes('entinel'), returnedClean); +// 085 still says it in full. +assert.ok(stageTrackerRowHtml(P('o/r', 15162, 85, flagged), stages, ctx).includes('Sentinel alert · needs human')); +// Give direction on a clanker PR is carried to the contributor's hive, not +// to the hive's own fixer. +assert.strictEqual(stageTrackerDirectionCarrier([{ kind: 'pr', author: 'thatguywob', author_kind: 'clanker' }]), "@thatguywob's hive"); +assert.strictEqual(stageTrackerDirectionCarrier([{ kind: 'pr', author: '@a', author_kind: 'clanker' }, { kind: 'pr', author: 'b', author_kind: 'clanker' }]), "the contributor's hive"); +assert.strictEqual(stageTrackerDirectionCarrier([{ kind: 'pr', author: 'x', author_kind: 'clanker' }, { kind: 'pr', author: 'hive[bot]', author_kind: 'hive' }]), 'the author agent'); +assert.strictEqual(stageTrackerDirectionCarrier([]), 'the author agent'); // Clean rows carry none of it. const clean = stageTrackerRowHtml(P('o/r', 104, 85), stages, ctx); diff --git a/src/pkg/dashboard/stage_tracker_ui_test.go b/src/pkg/dashboard/stage_tracker_ui_test.go index 3a84a688a8..766b9b7873 100644 --- a/src/pkg/dashboard/stage_tracker_ui_test.go +++ b/src/pkg/dashboard/stage_tracker_ui_test.go @@ -470,7 +470,8 @@ assert.strictEqual(stageTrackerAnchor(95, stages, 'pr'), STAGE_TRACKER_MERGE_COL // PR returned to contributor: detour badge rides Review; chip cap = author kind + first modifier (+N). row = stageTrackerRowHtml({ repo: 'acme/console', number: 102, kind: 'pr', title: 'Fix flaky', stage: 72, lane: 'contributor', tier: 'trusted', author: 'karibhou', author_kind: 'clanker', author_kind_source: 'inferred', modifiers: ['needs-rebase', 'needs-human'], caption: 'Returned to @karibhou', history: [{number:50,slug:'review-pending'},{number:60,slug:'reviewed'},{number:72,slug:'returned-to-contributor',from:60}] }, stages, ctx); assert.deepStrictEqual(segStates(row), [D, D, D, D, 'active detoured', T, 'todo cap']); -assert.ok(row.includes('Returned to contributor')); +// hivecommons/hive#15159: the chevron names the routing — the contributor's hive, for a clanker's PR. +assert.ok(row.includes('Returned to @karibhou's hive'), row); // Invariant: a PR never occupies the issue slot. A PR with no linked issue // puts the muted "no linked issue" placeholder on the left and names itself // — author icon, #N, title — in the PR column, where a covering PR sits on @@ -564,7 +565,7 @@ assert.ok(row.includes('aria-label="Next move: clanker"') && row.includes('Needs authorNeeds @samWhere to get help function stageTrackerSentinelInLane(item) { return !!(item && item.sentinel_alert) && (Number(item.stage) || 0) === STAGE_TRACKER_NEEDS_DECISION && (item.kind === 'pr' || !!item.via_pr); } + // A returned PR (071/072) keeps its routing word — the human already + // acted, nothing is owed by the maintainer — and carries the alert as + // a " · sentinel" suffix instead (hivecommons/hive#15159); the chip + // then adds nothing. + function stageTrackerSentinelAsSuffix(item) { + const st = Number(item && item.stage) || 0; + return !!(item && item.sentinel_alert) && (st === 71 || st === 72) && (item.kind === 'pr' || !!item.via_pr); + } + // The 071/072 chevron word names the routing: "Needs @author" at 071, + // "Returned to @author's hive" at 072 for a clanker-authored PR (the + // contributor's agent picks it up), "Returned to @author" for a human's. + function stageTrackerReturnedWord(item, fallback) { + const st = Number(item && item.stage) || 0; + const author = String((item && item.author) || '').replace(/^@/, ''); + let text = fallback; + if (author && st === 71) text = 'Needs @' + author; + else if (author && st === 72) text = 'Returned to @' + author + (item.author_kind === 'human' ? '' : "'s hive"); + return text + (stageTrackerSentinelAsSuffix(item) ? ' · ' + STAGE_TRACKER_SENTINEL_CHIP : ''); + } // Which strip segment a stage lights: main stages light themselves, // 040 shares the PR in progress column with 030, 060, 095 and 100 share @@ -15017,6 +15036,10 @@

    Where to get help

    const detour = (!terminal && STAGE_TRACKER_PATH.indexOf(cur) < 0 && cur !== STAGE_TRACKER_TRIAGE_NEEDED && cur !== STAGE_TRACKER_POSSIBLY_EXISTS && cur !== 40 && cur !== 60 && cur !== STAGE_TRACKER_PRE_MERGE_SOAK && cur !== 100) ? { text: sentinelLane ? STAGE_TRACKER_SENTINEL_WORD : (cur === STAGE_TRACKER_HUMAN_GATED && typeof stageTrackerTrainWord === 'function' && stageTrackerTrainWord(item)) || (cur === STAGE_TRACKER_READY_FOR_HUMAN_MERGE && item.manual_merge ? stageTrackerManualMergeWord(item) : (cur === STAGE_TRACKER_HUMAN_GATED && stageTrackerUnauthorizedWord(item)) || ((cur === STAGE_TRACKER_ADOPTED_BY_HIVE || (cur === STAGE_TRACKER_HUMAN_GATED && item.adopted_by_state)) && stageTrackerAdoptedWord(item)) || (cur === STAGE_TRACKER_READY_FOR_HUMAN_MERGE && stageTrackerReadyForHumanWord(item, STAGE_TRACKER_ACTIVE_WORD[cur] || curStage.short || curStage.label || String(cur))) || (STAGE_TRACKER_ACTIVE_WORD[cur] || curStage.short || curStage.label || String(cur))), sentinel: sentinelLane } : null; if (detour && cur === 70 && !detour.sentinel && typeof stageTrackerFixingWord === 'function') detour.text = stageTrackerFixingWord(item, detour.text); + if (detour && (cur === 71 || cur === 72) && typeof stageTrackerReturnedWord === 'function') { + detour.text = stageTrackerReturnedWord(item, detour.text); + detour.sentinelSuffix = stageTrackerSentinelAsSuffix(item); + } const segs = STAGE_TRACKER_PATH.map(n => { const st = n === 0 ? { label: 'Open', short: 'Open', description: 'Open, not yet in a stage' } : (byNum[n] || {}); let state = 'todo'; @@ -15242,7 +15265,8 @@

    Where to get help

    return segs.map(sg => { if (sg.number < from || sg.number > to) return `
  • `; const sentinel = !!(sg.detour && sg.detour.sentinel); - const cls = ['ham-seg', sg.state, sg.cap ? 'cap' : '', sg.cap && sg.terminal ? 'merged' : '', sg.detour ? 'detoured' : '', sg.hold ? 'ham-open-hold' : '', sg.blocked ? 'ham-open-blocked' : '', sg.draft ? 'ham-open-draft' : '', sg.isNew ? 'ham-open-new' : '', sg.openSince && sg.openSince.stale ? 'ham-open-stale' : '', sentinel ? 'ham-sentinel' : ''].filter(Boolean).join(' '); + const sentinelSuffix = !!(sg.detour && sg.detour.sentinelSuffix); + const cls = ['ham-seg', sg.state, sg.cap ? 'cap' : '', sg.cap && sg.terminal ? 'merged' : '', sg.detour ? 'detoured' : '', sg.hold ? 'ham-open-hold' : '', sg.blocked ? 'ham-open-blocked' : '', sg.draft ? 'ham-open-draft' : '', sg.isNew ? 'ham-open-new' : '', sg.openSince && sg.openSince.stale ? 'ham-open-stale' : '', sentinel || sentinelSuffix ? 'ham-sentinel' : ''].filter(Boolean).join(' '); const active = sg.state === 'active'; let tip = ''; if (active) { @@ -15265,6 +15289,7 @@

    Where to get help

    // The sentinel's reason leads the lane tooltip so the security // implication is read before the stage mechanics. if (sentinel) tip = stageTrackerSentinelTip(item) + ' — ' + tip; + else if (sentinelSuffix) tip = tip + ' — ' + stageTrackerSentinelTip(item); // Working or waiting leads: what happens now, or what it waits on. if (!sg.cap && typeof stageTrackerCueLead === 'function') tip = stageTrackerCueLead(item, worker, nowMs) + tip; } @@ -15288,7 +15313,7 @@

    Where to get help

    if (sg.cap) inner = sg.terminal ? stageTrackerIcon(sg.number, 'ham-ico') : stageTrackerIcon('history', 'ham-ico ham-history-ico', 'History — no decisions or actions recorded yet'); else if (active) inner = gateCue + workIco + (decision ? stageTrackerDecisionTriggerHtml(decision, word, tip) : word) + actorIco; else inner = stageTrackerIcon(sg.number, 'ham-ico'); - return `
  • ${inner}
  • `; + return `
  • ${inner}
  • `; }).join(''); } @@ -15438,7 +15463,7 @@

    Where to get help

    return `${esc(text)}`; } function stageTrackerSentinelChipHtml(item) { - if (!item || !item.sentinel_alert || stageTrackerSentinelInLane(item) || stageTrackerDeferredMods(item).indexOf(STAGE_TRACKER_SENTINEL_CHIP) >= 0) return ''; + if (!item || !item.sentinel_alert || stageTrackerSentinelInLane(item) || stageTrackerSentinelAsSuffix(item) || stageTrackerDeferredMods(item).indexOf(STAGE_TRACKER_SENTINEL_CHIP) >= 0) return ''; return `${esc(STAGE_TRACKER_SENTINEL_CHIP)}`; } @@ -17698,6 +17723,16 @@

    All labels

    const nested = stageTrackerNestedOpenPRs(item); return nested.length >= STAGE_TRACKER_DELEGATE_ALL_MIN ? nested : []; } + // Pure: who carries a direction on these PRs — the hive's own author + // agent, or (a clanker-authored PR, hivecommons/hive#15159) the owning + // contributor's hive, which is nudged with the text. + function stageTrackerDirectionCarrier(items) { + const list = (items || []).filter(it => it && it.kind === 'pr'); + if (!list.length || !list.every(it => it.author_kind === 'clanker')) return 'the author agent'; + const authors = Array.from(new Set(list.map(it => String(it.author || '').replace(/^@/, '')).filter(Boolean))); + if (authors.length === 1) return "@" + authors[0] + "'s hive"; + return "the contributor's hive"; + } // Pure: the decision choices for one decision target. On an issue // parked at 045 the verbs are /hive approve and /hive decision. On a PR // parked at 085, Approve posts the /lgtm + /approve commands as the @@ -18661,7 +18696,7 @@

    All labels

    case 'decide:direction': { // The direction is required, so this prompt is never skipped. const v = await hivePrompt(prs - ? { title: 'Give direction', label: preface + 'What should the hive change on ' + refs + '? (recorded as "/hive decision …"; the author agent pushes a new head)', placeholder: 'e.g. drop the retry loop and keep the flag', validate: s => s ? true : 'A direction is required', confirmLabel: 'Send' } + ? { title: 'Give direction', label: preface + 'What should the hive change on ' + refs + '? (recorded as "/hive decision …"; ' + stageTrackerDirectionCarrier(items) + ' pushes a new head)', placeholder: 'e.g. drop the retry loop and keep the flag', validate: s => s ? true : 'A direction is required', confirmLabel: 'Send' } : { title: 'Send back to the hive', label: 'Direction for the hive on ' + refs + ' (recorded as "/hive decision …")', placeholder: 'e.g. take option B and keep the API as is', validate: s => s ? true : 'A direction is required', confirmLabel: 'Send' }); return v == null ? null : { comment: v }; } diff --git a/src/pkg/github/automerge/automerge_contributor_lane.go b/src/pkg/github/automerge/automerge_contributor_lane.go index 4b86878d86..e4319e3755 100644 --- a/src/pkg/github/automerge/automerge_contributor_lane.go +++ b/src/pkg/github/automerge/automerge_contributor_lane.go @@ -443,7 +443,7 @@ func (c *Engine) SweepContributorLaneAutoMerges(ctx context.Context, opts AutoMe stage(reason, false, nil) continue } - if reason := c.prefilterContributorLanePR(pr, policy); reason != "" { + if reason := c.sentinelBlockedUnlessHumanChangesRequested(ctx, owner, repoName, pr, c.prefilterContributorLanePR(pr, policy)); reason != "" { c.recordContributorLaneSkip(displayRepo, number, reason) result.Skipped++ stage(reason, false, nil) @@ -1237,7 +1237,7 @@ func (c *Engine) evaluateContributorLanePR(ctx context.Context, displayRepo, own return contributorLaneEval{}, "fetch-pr", err } c.noteStagePR(owner, repo, number, pr) - if reason := c.prefilterContributorLanePR(pr, policy); reason != "" { + if reason := c.sentinelBlockedUnlessHumanChangesRequested(caller, owner, repo, pr, c.prefilterContributorLanePR(pr, policy)); reason != "" { if reason == contributorLaneReasonAppAuthored { c.noteStageRole(owner, repo, number, stagelabels.RoleTrusted) } else { diff --git a/src/pkg/github/automerge/automerge_contributor_lane_test.go b/src/pkg/github/automerge/automerge_contributor_lane_test.go index 18bda101d9..dba5134f7f 100644 --- a/src/pkg/github/automerge/automerge_contributor_lane_test.go +++ b/src/pkg/github/automerge/automerge_contributor_lane_test.go @@ -22,6 +22,7 @@ import ( hgithub "github.com/hivecommons/hive/pkg/github" "github.com/hivecommons/hive/pkg/intent" "github.com/hivecommons/hive/pkg/review" + hreview "github.com/hivecommons/hive/pkg/review" "github.com/hivecommons/hive/pkg/stagelabels" ) @@ -1757,3 +1758,63 @@ func TestContributorTrustedChangeRequestAnswersRequiresHuman(t *testing.T) { t.Fatalf("stage=%+v, want returned to contributor", v) } } + +// TestTrySweepContributorLaneSentinelYieldsToHumanChangesRequested: the +// sentinel alert parks a contributor PR for a human; a trusted human's +// CHANGES_REQUESTED review on the current head is that human. The lane +// reports human-changes-requested (→ 071/072) instead of sentinel-blocked +// (→ 085), reads the standing request from the durable store too, and +// re-arms the park on a new head (hivecommons/hive#15159). +func TestTrySweepContributorLaneSentinelYieldsToHumanChangesRequested(t *testing.T) { + review := func(state, commit, login string) []map[string]any { + return []map[string]any{{"id": 1, "state": state, "commit_id": commit, "user": map[string]string{"login": login}, "body": "drop the workflow change"}} + } + for _, tt := range []struct { + name string + reviews []map[string]any + trusted bool + store *hreview.HumanChangeRequests + wantReason string + }{ + {name: "no review stays parked", trusted: true, wantReason: contributorLaneReasonSentinelBlocked}, + {name: "trusted changes requested on head", reviews: review("CHANGES_REQUESTED", "sha7", "clubanderson"), trusted: true, wantReason: autoMergeReasonHumanChangesRequested}, + {name: "untrusted reviewer stays parked", reviews: review("CHANGES_REQUESTED", "sha7", "clubanderson"), wantReason: contributorLaneReasonSentinelBlocked}, + {name: "review on an older head re-arms", reviews: review("CHANGES_REQUESTED", "sha6", "clubanderson"), trusted: true, wantReason: contributorLaneReasonSentinelBlocked}, + {name: "approval is not a change request", reviews: review("APPROVED", "sha7", "clubanderson"), trusted: true, wantReason: contributorLaneReasonSentinelBlocked}, + {name: "standing request in the store", trusted: true, store: storedChangeRequest(t, "sha7"), wantReason: autoMergeReasonHumanChangesRequested}, + {name: "stored request on an older head re-arms", trusted: true, store: storedChangeRequest(t, "sha6"), wantReason: contributorLaneReasonSentinelBlocked}, + } { + t.Run(tt.name, func(t *testing.T) { + fx := validContributorFixture() + fx.labels = []string{"hive-sentinel"} + fx.reviews = tt.reviews + api := newContributorLaneAPI(t, &fx) + defer api.Close() + policy := defaultContributorLanePolicy() + clock := &contributorLaneClock{at: time.Date(2026, 10, 15, 13, 0, 0, 0, time.UTC)} + engine := newContributorLaneEngine(api.URL, policy, clock, Options{ContributorSoak: soakedTracker(clock), HumanChangeRequests: tt.store}) + if tt.trusted { + engine.SetMergerAuthorizer(func(login string) bool { return strings.EqualFold(login, "clubanderson") }) + } + _, reason, err := engine.trySweepContributorLanePR(context.Background(), "widget", "acme", "widget", 7, policy) + if err != nil { + t.Fatal(err) + } + if reason != tt.wantReason { + t.Fatalf("reason = %q, want %q", reason, tt.wantReason) + } + if fx.merges != 0 { + t.Fatalf("merged %d, want 0", fx.merges) + } + }) + } +} + +func storedChangeRequest(t *testing.T, head string) *hreview.HumanChangeRequests { + t.Helper() + store := hreview.NewHumanChangeRequests("") + if err := store.Record(hreview.HumanChangeRequest{Repo: "acme/widget", Number: 7, HeadSHA: head, Source: hreview.HumanChangeRequestSourceDecision, Actor: "clubanderson", Body: "drop it"}); err != nil { + t.Fatal(err) + } + return store +} diff --git a/src/pkg/github/automerge/automerge_human_changes_requested.go b/src/pkg/github/automerge/automerge_human_changes_requested.go index 51e79e539e..e200e961c1 100644 --- a/src/pkg/github/automerge/automerge_human_changes_requested.go +++ b/src/pkg/github/automerge/automerge_human_changes_requested.go @@ -166,3 +166,27 @@ func (c *Engine) reconcileReviewBackedApproval(ctx context.Context, owner, repo } return c.humanChangeRequests.For(key, number, head) } + +// sentinelBlockedUnlessHumanChangesRequested refines the contributor lane's +// sentinel-blocked prefilter skip: a sentinel alert parks the PR on a person +// (085), and a trusted maintainer's CHANGES_REQUESTED review on the current +// head IS that person's answer — the author acts next, so the lane reason +// becomes human-changes-requested and the stage pass derives the fixing +// stage (072 for a clanker's PR) instead of re-asserting 085 over it every +// sweep (hivecommons/hive#15159). The review is read only for a sentinel- +// blocked PR, and the standing request is noted on the stage detail and +// recorded for the nudge like the self lane's. Any other reason is returned +// unchanged; a new head without a review on it is blocked again. +func (c *Engine) sentinelBlockedUnlessHumanChangesRequested(ctx context.Context, owner, repo string, pr *gh.PullRequest, reason string) string { + if reason != contributorLaneReasonSentinelBlocked || pr == nil || pr.GetHead() == nil { + return reason + } + head := strings.TrimSpace(pr.GetHead().GetSHA()) + if head == "" { + return reason + } + if c.humanChangesRequestedForHead(ctx, owner, repo, pr.GetNumber(), head) { + return autoMergeReasonHumanChangesRequested + } + return reason +} diff --git a/src/pkg/github/automerge/automerge_stage_human.go b/src/pkg/github/automerge/automerge_stage_human.go index e2881641a1..eb35dbc4e0 100644 --- a/src/pkg/github/automerge/automerge_stage_human.go +++ b/src/pkg/github/automerge/automerge_stage_human.go @@ -120,6 +120,13 @@ func (c *Engine) humanEvidence(ctx context.Context, tracker *StageTracker, key s if approver := strings.TrimSpace(obs.Detail.HumanApprover); approver != "" && obs.HeadSHA != "" && strings.TrimSpace(obs.Detail.HumanApprovalHead) == obs.HeadSHA { e.HumanApprover = approver } + // A trusted maintainer's CHANGES_REQUESTED review (or recorded + // direction) on exactly this head is the human answer every park on it + // was waiting for: the route is the author's fixing stage, not 085 + // (hivecommons/hive#15159). + if requester := strings.TrimSpace(obs.Detail.HumanChangeRequester); requester != "" && obs.HeadSHA != "" && strings.TrimSpace(obs.Detail.HumanChangeRequestHead) == obs.HeadSHA { + e.HumanChangeRequester = requester + } if rec, ok := c.stageStoreOrShared().Get(key); ok && rec.AdoptedHead != "" && rec.AdoptDiffFence != "" && rec.AdoptDiffFence == obs.Reason && e.CauseReason != "" { // An adopted head whose diff fence is the blocker: the 085 note // says the hive repaired it and why it still will not merge it. diff --git a/src/pkg/github/issue_unpark_command.go b/src/pkg/github/issue_unpark_command.go index 16e64f6704..6d041b73b7 100644 --- a/src/pkg/github/issue_unpark_command.go +++ b/src/pkg/github/issue_unpark_command.go @@ -192,6 +192,10 @@ type PullRequestDecisionEvent struct { // or "approve" (an approval word followed by optional rationale). Mode string CommentURL string + // ToContributor is the owning contributor's login when the direction + // was carried to their hive rather than the hive's own author agent (a + // clanker-authored PR, hivecommons/hive#15159); "" for the hive's PRs. + ToContributor string } // IssueLabelApprovalEvent records one acceptance the sweep acted on, for the diff --git a/src/pkg/github/pr_decision_operator.go b/src/pkg/github/pr_decision_operator.go index 392121aa26..fc529614f8 100644 --- a/src/pkg/github/pr_decision_operator.go +++ b/src/pkg/github/pr_decision_operator.go @@ -252,22 +252,46 @@ func (c *Client) openPullRequestHead(ctx context.Context, owner, name string, nu // openPullRequestHeadLabels is openPullRequestHead plus the PR's labels as // read in the same fetch. func (c *Client) openPullRequestHeadLabels(ctx context.Context, owner, name string, number int) (head string, selfAuthored bool, labels []string, err error) { + t, err := c.openPullRequestDecisionTarget(ctx, owner, name, number) + return t.head, t.selfAuthored, t.labels, err +} + +// prDecisionTarget is what one open-PR read tells a dashboard decision: +// the head, whether the hive opened the PR, and — when it did not — +// whether a contributor's hive did (author/clanker, the origin marker, the +// attribution trailer), so a direction has a hive to carry it to. +type prDecisionTarget struct { + head string + selfAuthored bool + clanker bool + author string + labels []string +} + +func (c *Client) openPullRequestDecisionTarget(ctx context.Context, owner, name string, number int) (prDecisionTarget, error) { pr, resp, err := c.client.PullRequests.Get(ctx, owner, name, number) if err != nil { if resp != nil && resp.StatusCode == http.StatusNotFound { - return "", false, nil, fmt.Errorf("pull request %s/%s#%d: %w", owner, name, number, ErrPullRequestNotFound) + return prDecisionTarget{}, fmt.Errorf("pull request %s/%s#%d: %w", owner, name, number, ErrPullRequestNotFound) } - return "", false, nil, fmt.Errorf("fetching pull request %s/%s#%d: %w", owner, name, number, err) + return prDecisionTarget{}, fmt.Errorf("fetching pull request %s/%s#%d: %w", owner, name, number, err) } if strings.EqualFold(pr.GetState(), "closed") { - return "", false, nil, ErrPullRequestClosed + return prDecisionTarget{}, ErrPullRequestClosed } + t := prDecisionTarget{author: strings.TrimSpace(safeGetLogin(pr.GetUser()))} if pr.GetHead() != nil { - head = strings.TrimSpace(pr.GetHead().GetSHA()) + t.head = strings.TrimSpace(pr.GetHead().GetSHA()) + } + t.labels = issueLabelNames(pr.Labels) + t.selfAuthored = c.isHiveAccount(pr.GetUser()) || labelPresent(t.labels, authorkind.Hive.Label()) + if !t.selfAuthored { + // The author/clanker stamp is the hive's own earlier reading of the + // body; honour it alongside the markers in case the body was edited. + t.clanker = labelPresent(t.labels, authorkind.Clanker.Label()) || + authorkind.Detect(authorkind.Input{Author: t.author, AppLogin: c.AppBotLogin(), Labels: t.labels, Body: pr.GetBody()}) == authorkind.Clanker } - labels = issueLabelNames(pr.Labels) - selfAuthored = c.isHiveAccount(pr.GetUser()) || labelPresent(labels, authorkind.Hive.Label()) - return head, selfAuthored, labels, nil + return t, nil } func (c *Client) operatorPRTarget(repo string, number int, actor, what string) (owner, name string, err error) { @@ -406,13 +430,19 @@ func (c *Client) warnOperatorApproval(what, repo string, number int, head string } } -// RecordOperatorPullRequestDecision records a maintainer's direction on a -// hive-authored open pull request made through the dashboard — the same -// effect as that maintainer commenting `/hive decision ` and the -// un-park sweep answering it: the text is stored against the head as a -// human change request (the review planner kicks the author agent with it -// verbatim) and one reply naming the actor is posted. The caller is -// responsible for having verified actor's write access. +// RecordOperatorPullRequestDecision records a maintainer's direction on an +// open pull request made through the dashboard — the same effect as that +// maintainer commenting `/hive decision ` and the un-park sweep +// answering it: the text is stored against the head as a human change +// request and one reply naming the actor is posted. On a PR the hive +// opened the review planner kicks the hive's own author agent with the +// text verbatim. On a contributor's clanker PR (author/clanker, a foreign +// origin marker) the direction is carried to that contributor's hive +// instead: it stands as a changes-requested review on the head, the PR +// goes to 072 returned-to-contributor and the contributor nudge delivers +// the text (hivecommons/hive#15159). A PR a person opened has no hive to +// carry it: ErrPullRequestNotHiveAuthored, leave a review instead. The +// caller is responsible for having verified actor's write access. func (c *Client) RecordOperatorPullRequestDecision(ctx context.Context, repo string, number int, actor, decision string, store review.HumanChangeRequestStore) (PullRequestDecisionEvent, error) { owner, name, err := c.operatorPRTarget(repo, number, actor, "RecordOperatorPullRequestDecision") if err != nil { @@ -426,17 +456,23 @@ func (c *Client) RecordOperatorPullRequestDecision(ctx context.Context, repo str if store == nil { return PullRequestDecisionEvent{}, fmt.Errorf("RecordOperatorPullRequestDecision: no human change request store") } - head, selfAuthored, err := c.openPullRequestHead(ctx, owner, name, number) + target, err := c.openPullRequestDecisionTarget(ctx, owner, name, number) if err != nil { return PullRequestDecisionEvent{}, err } - if !selfAuthored { + head, selfAuthored := target.head, target.selfAuthored + if !selfAuthored && !target.clanker { return PullRequestDecisionEvent{}, ErrPullRequestNotHiveAuthored } if head == "" { return PullRequestDecisionEvent{}, ErrPullRequestHeadUnknown } mode := prDecisionModeFor(unparkCommand{Kind: unparkCommandDecision, Decision: decision, Text: decision}) + if !selfAuthored && mode == prDecisionApprove { + // A bare "approve" is not a direction a contributor's hive can act + // on; the dashboard's Approve action is the release for that. + return PullRequestDecisionEvent{}, ErrPullRequestNotHiveAuthored + } req := review.HumanChangeRequest{ Repo: owner + "/" + name, Number: number, @@ -453,11 +489,18 @@ func (c *Client) RecordOperatorPullRequestDecision(ctx context.Context, repo str return PullRequestDecisionEvent{}, fmt.Errorf("recording dashboard decision on %s/%s#%d: %w", owner, name, number, err) } stage := c.applyPRDecisionStage(ctx, owner, name, number, head, actor, mode, selfAuthored) - body := renderPRDecisionReply(actor, head, mode) + "\n\n_Recorded from the hive dashboard._" + reply := renderPRDecisionReply(actor, head, mode) + if !selfAuthored { + reply = renderPRDecisionToContributorHiveReply(actor, head, target.author, decision) + } + body := reply + "\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, Mode: string(mode)} + event := PullRequestDecisionEvent{Repo: owner + "/" + name, Number: number, HeadSHA: head, Actor: actor, Decision: decision, Mode: string(mode), ToContributor: target.author} + if selfAuthored { + event.ToContributor = "" + } 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 3f056b18b9..2e87499678 100644 --- a/src/pkg/github/pr_decision_operator_test.go +++ b/src/pkg/github/pr_decision_operator_test.go @@ -290,3 +290,50 @@ func TestRecordOperatorPullRequestApprovalSkipsCommandsProwRejected(t *testing.T }) } } + +// TestRecordOperatorPullRequestDecisionCarriesDirectionToContributorHive: +// a direction on a contributor's clanker PR (author/clanker) is accepted +// and carried to that contributor's hive — recorded against the head as a +// change request, the stage fact says the PR is not the hive's own, and the +// reply addresses the contributor's hive, not "the author agent" +// (hivecommons/hive#15159 answered 409 and left the row at 085). A bare +// "approve" is still not a direction a foreign hive can act on. +func TestRecordOperatorPullRequestDecisionCarriesDirectionToContributorHive(t *testing.T) { + clanker := parkedPR(78, "thatguywob", []string{PRNeedsDecisionStageLabel, "author/clanker", "role/trusted", "sentinel-alert"}) + c, rec := newUnparkPRClient(t, []unparkWireIssue{hiveParkedPR(), clanker}, nil) + store := review.NewHumanChangeRequests("") + + event, err := c.RecordOperatorPullRequestDecision(context.Background(), "org/repo", 78, "clubanderson", "drop the workflow change", store) + if err != nil { + t.Fatalf("direction on a clanker PR: %v", err) + } + if event.ToContributor != "thatguywob" || event.Mode != string(prDecisionChangesRequested) || event.HeadSHA != liveDecisionHead { + t.Fatalf("event = %+v, want the contributor named", event) + } + got, ok := store.For("org/repo", 78, liveDecisionHead) + if !ok || got.Actor != "clubanderson" || got.Body != "drop the workflow change" || got.IsApproval() { + t.Fatalf("stored request = %+v ok=%v", got, ok) + } + facts := prDecisionFacts(t, c) + if len(facts) != 1 || !facts[0].Instruction || facts[0].SelfAuthored || facts[0].Head != liveDecisionHead || facts[0].By != "clubanderson" { + t.Fatalf("stage facts = %+v, want one non-self PRDecided with the instruction", facts) + } + posted := strings.Join(rec.posted[78], "\n") + if !strings.Contains(posted, "Direction recorded by @clubanderson") || !strings.Contains(posted, "@thatguywob's hive") || !strings.Contains(posted, "> drop the workflow change") { + t.Fatalf("reply must address the contributor's hive with the direction, got %q", posted) + } + if strings.Contains(posted, "author agent") || strings.Contains(posted, "did not open this PR") { + t.Fatalf("reply must not speak of the hive's own fixer or refuse, got %q", posted) + } + + if _, err := c.RecordOperatorPullRequestDecision(context.Background(), "org/repo", 78, "clubanderson", "approve", store); !errors.Is(err, ErrPullRequestNotHiveAuthored) { + t.Fatalf("bare approve on a clanker PR: err = %v, want ErrPullRequestNotHiveAuthored", err) + } + // The hive's own PR keeps the hive-fixer reply. + if _, err := c.RecordOperatorPullRequestDecision(context.Background(), "org/repo", liveDecisionPR, "clubanderson", "do it", store); err != nil { + t.Fatalf("own PR: %v", err) + } + if own := strings.Join(rec.posted[liveDecisionPR], "\n"); !strings.Contains(own, "Decision recorded by @clubanderson") || strings.Contains(own, "'s hive") { + t.Fatalf("own-PR reply = %q", own) + } +} diff --git a/src/pkg/github/pr_unpark_decision.go b/src/pkg/github/pr_unpark_decision.go index ca5e08790f..f7a48dff35 100644 --- a/src/pkg/github/pr_unpark_decision.go +++ b/src/pkg/github/pr_unpark_decision.go @@ -412,6 +412,22 @@ func renderPRDecisionRecordedReply(actor, head string) string { prDecisionHeadMarkerLine(head, prDecisionChangesRequested), actor, prHeadRef(head)) } +// renderPRDecisionToContributorHiveReply is the reply for a direction +// recorded on a contributor's clanker PR: the fix is the contributor's +// hive's to push, not the hive's own author agent's (hivecommons/hive#15159). +func renderPRDecisionToContributorHiveReply(actor, head, author, decision string) string { + who := "the contributor's hive" + if a := strings.TrimPrefix(strings.TrimSpace(author), "@"); a != "" { + who = "@" + a + "'s hive" + } + body := fmt.Sprintf("%s\nDirection recorded by @%s for %s. This PR was opened by %s, so the hive treats it as a *changes requested* review on that head: the PR is returned to the contributor and %s is nudged with the instruction below verbatim. When a new head is pushed the review swarm re-reviews it; if it approves, the PR comes back for your merge approval.", + prDecisionHeadMarkerLine(head, prDecisionChangesRequested), actor, prHeadRef(head), who, who) + if d := strings.TrimSpace(decision); d != "" { + body += "\n\n> " + strings.ReplaceAll(d, "\n", "\n> ") + } + return body +} + 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)) diff --git a/src/pkg/github/stage_facts_sink.go b/src/pkg/github/stage_facts_sink.go index defba7a28e..df6546780b 100644 --- a/src/pkg/github/stage_facts_sink.go +++ b/src/pkg/github/stage_facts_sink.go @@ -163,6 +163,15 @@ func (c *Client) enrichStageFacts(ctx context.Context, f stageengine.Facts) (sta f.Author.Kind = authorkind.Hive } } + // A PR fact (a human's CHANGES_REQUESTED review, an un-park) carries no + // author kind either; left Unknown, the deriver's 07x split read every + // contributor PR as a person's and routed hivecommons/hive#15159 — a + // contributor's clanker PR — to 071 needs-author + // instead of 072 returned-to-contributor. Resolve it the way the sweep + // does: App login, agent/ stamp, body markers. + if f.Author.Kind == authorkind.Unknown && f.Ref.Kind == stagelabels.PRItem { + f.Author.Kind = authorkind.Detect(authorkind.Input{Author: issue.GetUser().GetLogin(), AppLogin: c.AppBotLogin(), Labels: f.Labels, Body: issue.GetBody()}) + } return f, nil } diff --git a/src/pkg/github/stage_facts_sink_test.go b/src/pkg/github/stage_facts_sink_test.go index 983c27537c..e2e926efad 100644 --- a/src/pkg/github/stage_facts_sink_test.go +++ b/src/pkg/github/stage_facts_sink_test.go @@ -25,6 +25,7 @@ type stageFactsServer struct { labels []string state string isPR bool + body string added []string removed []string // prState / prMerged answer GET /pulls/N (the covering-PR re-read); @@ -56,7 +57,7 @@ func newStageFactsServer(t *testing.T, labels ...string) *stageFactsServer { } _ = json.NewEncoder(w).Encode(body) case r.Method == http.MethodGet && strings.Contains(r.URL.Path, "/issues/"): - body := map[string]any{"number": 7, "state": s.state, "labels": wireLabelsOf(s.labels), "user": map[string]any{"login": "dev"}} + body := map[string]any{"number": 7, "state": s.state, "labels": wireLabelsOf(s.labels), "user": map[string]any{"login": "dev"}, "body": s.body} if s.isPR { body["pull_request"] = map[string]any{"url": "https://api.github.com/repos/o/r/pulls/7"} } @@ -266,6 +267,28 @@ func TestEnrichStageFacts(t *testing.T) { t.Fatalf("author kind = %q, want the fact's own kind kept", f.Author.Kind) } + // hivecommons/hive#15159: a PR fact resolves the author kind too, so a + // human's CHANGES_REQUESTED on a contributor's clanker PR derives 072 + // returned-to-contributor, not 071 needs-author. + srv.isPR = true + srv.body = "Fixes it.\n\n— hive: thatguywob-hive" + pf, err := c.enrichStageFacts(context.Background(), stageengine.Facts{Ref: c.PRStageRef("o/r", 7), PR: &stageengine.PRFacts{}}) + if err != nil { + t.Fatal(err) + } + if pf.Author.Kind != authorkind.Clanker { + t.Fatalf("PR author kind = %q, want clanker from the attribution trailer", pf.Author.Kind) + } + srv.body = "Hand written." + pf, err = c.enrichStageFacts(context.Background(), stageengine.Facts{Ref: c.PRStageRef("o/r", 7), PR: &stageengine.PRFacts{}}) + if err != nil { + t.Fatal(err) + } + if pf.Author.Kind != authorkind.Human { + t.Fatalf("PR author kind = %q, want human for a plain PR", pf.Author.Kind) + } + srv.isPR = false + var nilClient *Client if _, err := nilClient.enrichStageFacts(context.Background(), stageengine.Facts{}); err == nil { t.Fatal("nil client must fail") diff --git a/src/pkg/stageengine/derive_pr_classify.go b/src/pkg/stageengine/derive_pr_classify.go index 8a9f296c56..2a738c14bf 100644 --- a/src/pkg/stageengine/derive_pr_classify.go +++ b/src/pkg/stageengine/derive_pr_classify.go @@ -399,6 +399,15 @@ func ClassifyStage(o stageObservation) stageVerdict { if HasLabelFold(o.Labels, "needs-rebase") { return stageVerdict{Stage: fixing, Rank: stageRankOwned} } + if v, ok := HumanChangeRequestStage(o); ok { + // The "needs a human" the lane parked on — a sentinel alert, a + // workflow-path fence, a hold — is answered for this head: a + // trusted maintainer reviewed it and asked for changes, so the + // author acts next. Without this the sentinel-blocked + // contributor lane re-derived 085 over the owner's 072 every + // sweep (hivecommons/hive#15159); a new head re-asks. + return v + } return stageVerdict{Stage: stagelabels.NeedsDecision, Rank: stageRankOwned, Human: true} } if v, ok := HumanChangeRequestStage(o); ok { diff --git a/src/pkg/stageengine/derive_pr_returned_author_kind_test.go b/src/pkg/stageengine/derive_pr_returned_author_kind_test.go new file mode 100644 index 0000000000..79b44f43ee --- /dev/null +++ b/src/pkg/stageengine/derive_pr_returned_author_kind_test.go @@ -0,0 +1,133 @@ +package stageengine + +import ( + "testing" + + "github.com/hivecommons/hive/pkg/authorkind" + "github.com/hivecommons/hive/pkg/stagelabels" +) + +// hivecommons/hive#15159: "Needs author" (071) is for a person's PR only. +// A clanker-authored PR that a human or the review swarm sends back is 072 +// returned-to-contributor — the owning contributor's hive picks it up — +// whichever lane carried the verdict. +func TestClassifyStageChangesRequestedSplitsOnAuthorKind(t *testing.T) { + cases := []struct { + name string + lane string + reason string + detail stageDetail + kind authorkind.Kind + wantStage stagelabels.Stage + wantReason string + }{ + { + name: "human CHANGES_REQUESTED on a human's PR → 071", + lane: stageLaneTrusted, + reason: autoMergeReasonHumanChangesRequested, + detail: stageDetail{HumanChangeRequester: "clubanderson", HumanChangeRequestHead: goldenHead}, + kind: authorkind.Human, + wantStage: stagelabels.NeedsAuthor, + wantReason: autoMergeReasonHumanChangesRequested, + }, + { + name: "human CHANGES_REQUESTED on a clanker's PR → 072", + lane: stageLaneTrusted, + reason: autoMergeReasonHumanChangesRequested, + detail: stageDetail{HumanChangeRequester: "clubanderson", HumanChangeRequestHead: goldenHead}, + kind: authorkind.Clanker, + wantStage: stagelabels.ReturnedToContributor, + wantReason: autoMergeReasonHumanChangesRequested, + }, + { + name: "swarm changes_requested on a human's PR → 071", + lane: stageLaneTrusted, + reason: autoMergeReasonReviewGatePrefix + ReviewGateOutcomeChangesRequested, + kind: authorkind.Human, + wantStage: stagelabels.NeedsAuthor, + wantReason: stagelabels.LaneReasonChangesRequested, + }, + { + name: "swarm changes_requested on a clanker's PR → 072", + lane: stageLaneContributor, + reason: autoMergeReasonReviewGatePrefix + ReviewGateOutcomeChangesRequested, + kind: authorkind.Clanker, + wantStage: stagelabels.ReturnedToContributor, + wantReason: stagelabels.LaneReasonChangesRequested, + }, + { + name: "unknown kind still reads as a person's PR", + lane: stageLaneTrusted, + reason: autoMergeReasonHumanChangesRequested, + detail: stageDetail{HumanChangeRequester: "clubanderson", HumanChangeRequestHead: goldenHead}, + kind: authorkind.Unknown, + wantStage: stagelabels.NeedsAuthor, + wantReason: autoMergeReasonHumanChangesRequested, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + v := ClassifyStage(stageObservation{Lane: tc.lane, Reason: tc.reason, HeadSHA: goldenHead, Detail: tc.detail, AuthorKind: tc.kind}) + if v.Stage != tc.wantStage || v.Reason != tc.wantReason { + t.Fatalf("classified as %+v, want stage=%s reason=%q", v, tc.wantStage, tc.wantReason) + } + }) + } +} + +// Through Derive: the same two facts differ only in the author kind the +// sink resolved, and land on 071 vs 072. +func TestDerivePRChangesRequestedRoutesByAuthorKind(t *testing.T) { + for _, tc := range []struct { + kind authorkind.Kind + want stagelabels.Stage + }{ + {authorkind.Human, stagelabels.NeedsAuthor}, + {authorkind.Clanker, stagelabels.ReturnedToContributor}, + } { + f := Facts{ + Ref: Ref{Owner: "o", Repo: "r", Number: 15159, Kind: stagelabels.PRItem}, + Open: true, + Author: AuthorFacts{Login: "thatguywob", Kind: tc.kind}, + PR: &PRFacts{ + HeadSHA: goldenHead, + Review: ReviewFacts{HumanChangeRequester: "clubanderson"}, + Lanes: []LaneFact{{Lane: stageLaneTrusted, Reason: autoMergeReasonHumanChangesRequested}}, + }, + } + d := derivePR(f) + if d.Abstain || d.Stage != tc.want { + t.Fatalf("kind %s: derived %+v, want %s", tc.kind, d, tc.want) + } + } +} + +// hivecommons/hive#15159: the contributor lane parked a clanker PR on its +// sentinel alert (085) and kept re-asserting it over the owner's 072 after +// the owner's CHANGES_REQUESTED review. A trusted human's standing change +// request on the current head is the human the park waited for: the PR is +// the author's to fix. On another head it is not (per-head, like #15216's +// sentinel release), and the park stands. +func TestClassifyStageHumanChangeRequestWinsOverSentinelPark(t *testing.T) { + reviewed := stageDetail{HumanChangeRequester: "clubanderson", HumanChangeRequestHead: goldenHead} + for _, reason := range []string{contributorLaneReasonSentinelBlocked, "sentinel", contributorLaneReasonWorkflowPath} { + t.Run(reason, func(t *testing.T) { + parked := ClassifyStage(stageObservation{Lane: stageLaneContributor, Reason: reason, HeadSHA: goldenHead, Labels: []string{"sentinel-alert"}, AuthorKind: authorkind.Clanker}) + if parked.Stage != stagelabels.NeedsDecision || !parked.Human { + t.Fatalf("no review: %+v, want 085", parked) + } + v := ClassifyStage(stageObservation{Lane: stageLaneContributor, Reason: reason, HeadSHA: goldenHead, Labels: []string{"sentinel-alert"}, Detail: reviewed, AuthorKind: authorkind.Clanker}) + if v.Stage != stagelabels.ReturnedToContributor || v.Reason != autoMergeReasonHumanChangesRequested || v.Human { + t.Fatalf("human changes_requested on the head: %+v, want 072 %s", v, autoMergeReasonHumanChangesRequested) + } + human := ClassifyStage(stageObservation{Lane: stageLaneContributor, Reason: reason, HeadSHA: goldenHead, Labels: []string{"sentinel-alert"}, Detail: reviewed, AuthorKind: authorkind.Human}) + if human.Stage != stagelabels.NeedsAuthor { + t.Fatalf("a person's PR goes to 071: %+v", human) + } + stale := ClassifyStage(stageObservation{Lane: stageLaneContributor, Reason: reason, HeadSHA: "newhead0000", Labels: []string{"sentinel-alert"}, Detail: reviewed, AuthorKind: authorkind.Clanker}) + if stale.Stage != stagelabels.NeedsDecision { + t.Fatalf("a new head re-arms the park: %+v", stale) + } + }) + } +} diff --git a/src/pkg/stagelabels/human.go b/src/pkg/stagelabels/human.go index 7d976c47e9..420c6ef25e 100644 --- a/src/pkg/stagelabels/human.go +++ b/src/pkg/stagelabels/human.go @@ -139,6 +139,15 @@ type Evidence struct { // requires_human verdict and on a manual-merge lane rule: the person // read the reviewer's objection and ruled the head lands as-is. HumanApprover string + // HumanChangeRequester is the trusted maintainer whose CHANGES_REQUESTED + // review (or `/hive decision `) stands on exactly Head ("" when + // none). A person has reviewed this head and asked for a fix: that + // answers every "needs a human" park on it — the sentinel alert, a + // workflow-path fence, a hold — so the PR is the author's to act on + // (071 / 072 / 070), not 085 (hivecommons/hive#15159: a clanker PR + // with the owner's changes-requested review kept re-deriving + // "Sentinel alert · needs human" over the operator's 072). + HumanChangeRequester string // ManualMergeRule is true when CauseReason names a lane rule no // approval can override — the hive never merges the head unattended // (CI workflow / action edits, removed tests, a human-merge path). With @@ -225,7 +234,11 @@ type Route struct { // Lane-vocabulary reasons RouteHuman emits for the fixing stages. const ( - LaneReasonChangesRequested = "reviewer-verdict:changes_requested" + LaneReasonChangesRequested = "reviewer-verdict:changes_requested" + // LaneReasonHumanChangesRequested is a trusted maintainer's standing + // change request on the head (prstage.AutoMergeReasonHumanChangesRequested + // spells the same token; prstage imports this package). + LaneReasonHumanChangesRequested = "human-changes-requested" LaneReasonDCOMissing = "dco-missing" LaneReasonHiveSignoffAttribution = "hive-signoff-attribution" LaneReasonConflicting = "conflicting" @@ -255,6 +268,12 @@ func RouteHuman(e Evidence) Route { laneReason = lane } } + if requester := strings.TrimPrefix(strings.TrimSpace(e.HumanChangeRequester), "@"); requester != "" { + // A person reviewed this head and asked for changes: the sentinel's + // or the lane rule's "needs a human" is answered for it, and the + // author acts next (hivecommons/hive#15159). A new head re-asks. + note("@"+requester+" requested changes @"+ShortSHA(e.Head), LaneReasonHumanChangesRequested) + } if e.Verdict == VerdictChangesRequested { note("verdict changes_requested @"+ShortSHA(e.Head), LaneReasonChangesRequested) } @@ -423,6 +442,9 @@ func summarize(e Evidence) string { if approver := strings.TrimSpace(e.HumanApprover); approver != "" { parts = append(parts, "approved by @"+approver) } + if requester := strings.TrimPrefix(strings.TrimSpace(e.HumanChangeRequester), "@"); requester != "" { + parts = append(parts, "changes requested by @"+requester) + } switch { case !e.Checks.Known: parts = append(parts, "checks unknown") diff --git a/src/pkg/stagelabels/human_test.go b/src/pkg/stagelabels/human_test.go index f7caea57b3..4e9dd929ab 100644 --- a/src/pkg/stagelabels/human_test.go +++ b/src/pkg/stagelabels/human_test.go @@ -631,3 +631,42 @@ func TestRouteHumanAuthorOwesAnswer(t *testing.T) { t.Fatalf("approved head routed to %s: %+v", r.Stage, r) } } + +// TestRouteHumanChangeRequesterWinsOverParks: a trusted maintainer's +// CHANGES_REQUESTED review on the head is the person's answer to every +// "needs a human" park on it — the sentinel alert, a hold, a manual-merge +// lane rule — so the PR goes back to its author (072 for a clanker's, 071 +// for a person's, 070 for the hive's) instead of 085 +// (hivecommons/hive#15159: "Sentinel alert · needs human" re-derived over +// the owner's 072 every sweep). +func TestRouteHumanChangeRequesterWinsOverParks(t *testing.T) { + e := readyEvidence() + e.Sentinel = true + e.Cause = CauseDecision + e.CauseReason = "contributor-lane:sentinel-blocked" + e.Holds = []string{"hold"} + e.ManualMergeRule = true + if r := RouteHuman(e); r.Stage != NeedsDecision { + t.Fatalf("without a review the parks hold: %+v", r) + } + e.HumanChangeRequester = "@clubanderson" + e.AuthorKind = authorkind.Clanker + r := RouteHuman(e) + if r.Stage != ReturnedToContributor || r.LaneReason != LaneReasonHumanChangesRequested { + t.Fatalf("clanker route = %+v", r) + } + if len(r.Reasons) != 1 || r.Reasons[0] != "@clubanderson requested changes @abc1234" { + t.Fatalf("reasons = %q", r.Reasons) + } + if !strings.Contains(r.Summary, "changes requested by @clubanderson") { + t.Fatalf("summary = %q", r.Summary) + } + e.AuthorKind = authorkind.Human + if r := RouteHuman(e); r.Stage != NeedsAuthor { + t.Fatalf("human route = %+v", r) + } + e.SelfAuthored = true + if r := RouteHuman(e); r.Stage != Fixing { + t.Fatalf("self-authored route = %+v", r) + } +} From eef2ed704825e1ece43eea14f7549534ccda7cd0 Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Wed, 28 Oct 2026 22:55:44 -0400 Subject: [PATCH 2/3] fix: honour a hand-placed stage/071/072 over the sentinel park for the current head The reconciler logged added=[stage/085] removed=[stage/072-returned-to- contributor] on hive#15159 after the owner swapped the labels by hand. A trusted maintainer's return label the hive did not write is now read from the label event once per head, recorded as a stage-label change request against the head, and folded into the pass like a review, so classification keeps 071/072 ahead of the sentinel/hold/workflow-path parks; a new head re-arms the park. A standing change request in the store now also folds into the stage detail when no reviewer verdict was read for the head. Signed-off-by: Andrew Anderson --- .../fixed-clanker-returned-to-contributor.md | 2 +- src/docs/dashboard-sections.md | 2 +- .../automerge/automerge_stage_human_return.go | 111 ++++++++++++++++ .../automerge_stage_human_return_test.go | 123 ++++++++++++++++++ .../automerge/automerge_stage_labels.go | 13 +- src/pkg/github/automerge/automerge_sweep.go | 7 +- .../automerge/reporter_trust_release.go | 8 +- src/pkg/review/human_change_request.go | 7 +- 8 files changed, 267 insertions(+), 6 deletions(-) create mode 100644 src/pkg/github/automerge/automerge_stage_human_return.go create mode 100644 src/pkg/github/automerge/automerge_stage_human_return_test.go diff --git a/changelog.d/fixed-clanker-returned-to-contributor.md b/changelog.d/fixed-clanker-returned-to-contributor.md index b60ef0fb50..c26782c1a6 100644 --- a/changelog.d/fixed-clanker-returned-to-contributor.md +++ b/changelog.d/fixed-clanker-returned-to-contributor.md @@ -1 +1 @@ -- Activity Monitor: a clanker-authored PR that a trusted human sends back with a CHANGES_REQUESTED review now shows **Returned to contributor** (072, actor the owning contributor, caption `Returned to @thatguywob's hive — @clubanderson requested changes`) instead of `Sentinel alert · needs human` — the human's review on the current head is the human the sentinel, hold and workflow-path parks were waiting for, so the sentinel pass no longer re-asserts 085 over 072 until a new head re-arms it (per head, like the dashboard Approve release). "Needs author" (071) stays a person's PR. The dashboard **Give direction** decision is accepted on clanker PRs too: the direction is posted to the contributor's hive as a change request and the row moves to 072; the 409 "the hive did not open this pull request" is kept only for a person's PR, which no hive can carry direction to. The 071/072 chevron keeps its routing word with any sentinel finding as a ` · sentinel` suffix ([#15159](https://github.com/hivecommons/hive/pull/15159)). +- Activity Monitor: a clanker-authored PR that a trusted human sends back with a CHANGES_REQUESTED review now shows **Returned to contributor** (072, actor the owning contributor, caption `Returned to @thatguywob's hive — @clubanderson requested changes`) instead of `Sentinel alert · needs human` — the human's review on the current head is the human the sentinel, hold and workflow-path parks were waiting for, so the sentinel pass no longer re-asserts 085 over 072 until a new head re-arms it (per head, like the dashboard Approve release). The same holds for a return placed by hand: when a trusted maintainer removes `stage/085` and adds `stage/071`/`stage/072` themselves, the reconciler reads the label event, records it against the head and keeps the stage instead of logging `added=[stage/085] removed=[stage/072-returned-to-contributor]`. "Needs author" (071) stays a person's PR. The dashboard **Give direction** decision is accepted on clanker PRs too: the direction is posted to the contributor's hive as a change request and the row moves to 072; the 409 "the hive did not open this pull request" is kept only for a person's PR, which no hive can carry direction to. The 071/072 chevron keeps its routing word with any sentinel finding as a ` · sentinel` suffix ([#15159](https://github.com/hivecommons/hive/pull/15159)). diff --git a/src/docs/dashboard-sections.md b/src/docs/dashboard-sections.md index dc319897f5..8bcb37d873 100644 --- a/src/docs/dashboard-sections.md +++ b/src/docs/dashboard-sections.md @@ -682,7 +682,7 @@ Fed by `GET /api/stage-tracker`. Every issue and pull request follows the same p | `needs human decision` (`needs-decision` labels on another stage) | merge gate | PR at stage/080 or later; always on an issue at its own stage | | history decision badge (`last_operator_action`) | before the pills; the history mark + action count, neutral / amber (still at the same stage past the stuck window) / red (failed) / dotted (hive deciding) | always, once a row action was submitted from the dashboard; tooltip tells what you chose, when, and what the hive did next | -**Returned to a contributor's hive (072).** `stage/071-needs-author` is a person's PR: a human-authored pull request sent back by a maintainer's CHANGES_REQUESTED review or by the review swarm. The same verdict on a clanker-authored PR (`author/clanker`, or an author resolved to a contributor's hive agent) routes to `stage/072-returned-to-contributor`, whichever lane carried it: the actor is the owning contributor, the caption reads `Returned to @thatguywob's hive — @clubanderson requested changes`, and the normal contributor nudge goes to that hive ([hivecommons/hive#15159](https://github.com/hivecommons/hive/pull/15159): a human's out-of-cycle review on a clanker PR parked it at 071 under a maintainer's name). The 071/072 chevron names the routing — `Needs @sam`, `Returned to @thatguywob's hive` — and a sentinel finding on such a row is a ` · sentinel` suffix on that word (the chip folds into it, the tooltip carries the finding); `Sentinel alert · needs human` is only the chevron word when the maintainer's review is still outstanding (085). A trusted human's CHANGES_REQUESTED review on the current head *is* the human those parks (sentinel alert, `hold`, workflow-path) were waiting for: the PR routes to 071/072 and the sentinel pass does not re-assert 085 until a new head re-arms the alert. **Give direction** on a clanker PR is accepted as well — the direction is posted to the contributor's hive as a change request and the row moves to 072; only a person's PR, which no hive can carry direction to, still answers `409 the hive did not open this pull request`. +**Returned to a contributor's hive (072).** `stage/071-needs-author` is a person's PR: a human-authored pull request sent back by a maintainer's CHANGES_REQUESTED review or by the review swarm. The same verdict on a clanker-authored PR (`author/clanker`, or an author resolved to a contributor's hive agent) routes to `stage/072-returned-to-contributor`, whichever lane carried it: the actor is the owning contributor, the caption reads `Returned to @thatguywob's hive — @clubanderson requested changes`, and the normal contributor nudge goes to that hive ([hivecommons/hive#15159](https://github.com/hivecommons/hive/pull/15159): a human's out-of-cycle review on a clanker PR parked it at 071 under a maintainer's name). The 071/072 chevron names the routing — `Needs @sam`, `Returned to @thatguywob's hive` — and a sentinel finding on such a row is a ` · sentinel` suffix on that word (the chip folds into it, the tooltip carries the finding); `Sentinel alert · needs human` is only the chevron word when the maintainer's review is still outstanding (085). A trusted human's CHANGES_REQUESTED review on the current head *is* the human those parks (sentinel alert, `hold`, workflow-path) were waiting for: the PR routes to 071/072 and the sentinel pass does not re-assert 085 until a new head re-arms the alert. A return placed by hand counts too: when a trusted maintainer swaps `stage/085` for `stage/071`/`stage/072` on the PR, the reconciler reads the label event once per head, records it as that maintainer's change request against the head, and keeps the stage; the hive's own label events and untrusted actors are not honoured. **Give direction** on a clanker PR is accepted as well — the direction is posted to the contributor's hive as a change request and the row moves to 072; only a person's PR, which no hive can carry direction to, still answers `409 the hive did not open this pull request`. **Adoption pill (072).** A nudged `author/clanker` pull request at `stage/072-returned-to-contributor` carries `adoption{author, due, blocked_by, since, nudges, author_online, author_registered, author_last_seen, author_maintainer, policy, action, text}` — the nudge count and first-nudge time from the stage record, the author's live hub presence (the same lookup the contributor-offline adoption itself consults), and, when the adoption engine judged adoption due and held it, why (`blocked_by: author-is-maintainer`). The row's caption and an amber pill say it in plain words instead of a bare "Returned to contributor": `waiting on @hanthor (maintainer, offline 26h) — adopt?` under `governor.labels.stage.adoption.maintainer_policy: ask`, `waiting on @zoe (offline 40m, 2 nudges)` while the default `adopt` policy's clock runs, `… — not adopted: maintainer_policy is never` under `never` ([hivecommons/hive#14524](https://github.com/hivecommons/hive/pull/14524): the PR sat 26h at 072 with its author's hive gone and nothing on screen saying why). When `action` is `decide:adopt` the row also carries `decision_needed` (question "@hanthor maintains this repository and has been offline for 26h; adopt the PR?", `blocker_reason: adoption:author-is-maintainer`, options Adopt then Hold/Release), so the lit 072 chevron and the `adopt?` pill open the Needs-human popover, and the row menu and the selection bar offer **Adopt (hive takes over)** — same action-id vocabulary as the other `decide:*` entries — which, after an in-app confirm, POSTs `{"decision":"adopt"}` to the item's decision endpoint: the hive posts an attributed note, sets `adoption/supersede` (the owner-delegate's request label) and the next sweep adopts the head on the existing adopt/supersede path; the toast reads `adoption-queued`. Write access required; the action is absent when nothing is the owner's to decide. diff --git a/src/pkg/github/automerge/automerge_stage_human_return.go b/src/pkg/github/automerge/automerge_stage_human_return.go new file mode 100644 index 0000000000..26da2f6f60 --- /dev/null +++ b/src/pkg/github/automerge/automerge_stage_human_return.go @@ -0,0 +1,111 @@ +package automerge + +import ( + "context" + "strings" + + hgithub "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/review" + "github.com/hivecommons/hive/pkg/stagelabels" +) + +// foldHumanReturnLabel honours a person's hand-placed return of a PR to +// its author. hivecommons/hive#15159: the owner left a CHANGES_REQUESTED +// review, removed stage/085 and added stage/072-returned-to-contributor; +// the next pass re-derived 085 from the sentinel park and logged +// `added=[stage/085] removed=[stage/072-returned-to-contributor]`. The +// hive is the single writer of the stage family, so it must read a stage +// label it did not write as what it is — a trusted human's decision on +// this head — rather than as drift to repair. +// +// When the PR wears 071/072, the hive's own record does not say it put +// that label there, and no human change request stands against the head, +// the newest label event for that stage is read once per head; if a +// trusted merger added it, the request is recorded against the head in +// the durable store (source stage-label) and folded into the pass like a +// review, so classification routes to 071/072 ahead of the sentinel, +// hold and workflow-path parks. A new head carries no request and +// re-arms the park (per head, as hivecommons/hive#15216). The hive's own +// label events and untrusted actors are ignored. +func (c *Engine) foldHumanReturnLabel(ctx context.Context, store *stagelabels.Store, list []stageObservation) { + if c == nil || c.humanChangeRequests == nil || len(list) == 0 { + return + } + var o *stageObservation + for i := range list { + if strings.TrimSpace(list[i].HeadSHA) != "" && len(list[i].Labels) > 0 { + o = &list[i] + break + } + } + if o == nil { + return + } + worn := stagelabels.Current(o.Labels) + if worn != stagelabels.NeedsAuthor && worn != stagelabels.ReturnedToContributor { + return + } + head := strings.TrimSpace(o.HeadSHA) + repo := o.Owner + "/" + o.Repo + if _, ok := c.humanChangeRequests.For(repo, o.Number, head); ok { + return + } + key := stageKey(o.Owner, o.Repo, o.Number) + if rec, ok := store.Get(key); ok && rec.Stage == worn { + // The hive wrote this stage itself; nothing to attribute. + return + } + if c.humanReturnAlreadyChecked(key, head) { + return + } + ev, err := c.latestLabelEvent(ctx, o.Owner, o.Repo, o.Number, worn.Label()) + if err != nil { + c.debug("stage labels: return label provenance unreadable", "repo", o.Display, "pr", o.Number, "error", err) + return + } + c.markHumanReturnChecked(key, head) + if ev == nil || ev.GetEvent() != "labeled" { + return + } + actor := strings.TrimSpace(hgithub.SafeGetLogin(ev.GetActor())) + if actor == "" || normalizeBotLogin(actor) == normalizeBotLogin(c.transport.AppBotLogin()) { + return + } + if trusted, _ := c.isTrustedMerger(actor); !trusted { + c.debug("stage labels: return label set by an untrusted actor is not honoured", "repo", o.Display, "pr", o.Number, "stage", worn.String(), "by", actor) + return + } + req := review.HumanChangeRequest{ + Repo: repo, + Number: o.Number, + HeadSHA: head, + Source: review.HumanChangeRequestSourceStageLabel, + SourceID: ev.GetID(), + Actor: actor, + URL: o.URL, + RecordedAt: ev.GetCreatedAt().Time, + } + if err := c.humanChangeRequests.Record(req); err != nil { + c.warn("stage labels: could not record hand-placed return", "repo", o.Display, "pr", o.Number, "error", err) + return + } + c.info("stage labels: honouring a hand-placed return to author", "repo", o.Display, "pr", o.Number, "stage", worn.String(), "by", actor, "head", head) + for i := range list { + list[i].Detail.HumanChangeRequester, list[i].Detail.HumanChangeRequestHead = actor, head + } +} + +func (c *Engine) humanReturnAlreadyChecked(key, head string) bool { + c.humanReturnCheckedMu.Lock() + defer c.humanReturnCheckedMu.Unlock() + return c.humanReturnChecked[key] == head +} + +func (c *Engine) markHumanReturnChecked(key, head string) { + c.humanReturnCheckedMu.Lock() + defer c.humanReturnCheckedMu.Unlock() + if c.humanReturnChecked == nil { + c.humanReturnChecked = map[string]string{} + } + c.humanReturnChecked[key] = head +} diff --git a/src/pkg/github/automerge/automerge_stage_human_return_test.go b/src/pkg/github/automerge/automerge_stage_human_return_test.go new file mode 100644 index 0000000000..f81de18a58 --- /dev/null +++ b/src/pkg/github/automerge/automerge_stage_human_return_test.go @@ -0,0 +1,123 @@ +package automerge + +import ( + "context" + "slices" + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/review" + "github.com/hivecommons/hive/pkg/stagelabels" +) + +func stageLabelEvent(event, label, actor, at string) map[string]any { + return map[string]any{ + "id": int64(len(label) + len(at)), + "event": event, + "label": map[string]string{"name": label}, + "actor": map[string]string{"login": actor}, + "created_at": at, + } +} + +// TestApplyStageLabelsHonoursHandPlacedReturnOverSentinelPark is the +// hivecommons/hive#15159 log line: the contributor lane skipped +// `contributor-lane:sentinel-blocked`, the owner had swapped stage/085 for +// stage/072 by hand, and the reconciler logged `stage labels reconciled +// pr=15159 stage=085-needs-decision author_kind=clanker added=[stage/085] +// removed=[stage/072-returned-to-contributor]`. A trusted human's return +// label on the current head is that human's decision: the hive keeps 072, +// records it against the head, and only a new head re-arms the park. The +// hive's own label event and an untrusted actor change nothing. +func TestApplyStageLabelsHonoursHandPlacedReturnOverSentinelPark(t *testing.T) { + const sentinel = "hive-sentinel" + for _, tc := range []struct { + name string + actor string + trusted bool + held bool + }{ + {name: "trusted owner", actor: "clubanderson", trusted: true, held: true}, + {name: "untrusted actor", actor: "someone", trusted: false}, + {name: "the hive's own label", actor: testHiveAppBotLogin, trusted: true}, + } { + t.Run(tc.name, func(t *testing.T) { + api, closeAPI := seededStageAPI(t) + defer closeAPI() + api.issueEvents = map[int][]map[string]any{15159: { + stageLabelEvent("labeled", "stage/085-needs-decision", testHiveAppBotLogin, "2026-10-29T00:00:16Z"), + stageLabelEvent("unlabeled", "stage/085-needs-decision", tc.actor, "2026-10-29T02:40:00Z"), + stageLabelEvent("labeled", "stage/072-returned-to-contributor", tc.actor, "2026-10-29T02:40:05Z"), + }} + clock := &contributorLaneClock{at: time.Date(2026, 10, 29, 2, 48, 0, 0, time.UTC)} + e, _, store := newStageEngine(t, apiURLOf(t, api), clock) + requests := review.NewHumanChangeRequests("") + e.humanChangeRequests = requests + e.SetMergerAuthorizer(func(login string) bool { return strings.EqualFold(login, "clubanderson") }) + + // Pass 1: the hive parks the PR at 085 on the sentinel alert. + pr := nudgePR(15159, "sha7", sentinel, "role/trusted", "author/clanker") + e.recordStage(stageLaneContributor, "acme/widget", "acme", "widget", pr, contributorLaneReasonSentinelBlocked, false, nil) + e.noteStageRole("acme", "widget", 15159, stagelabels.RoleTrusted) + if _, err := e.ApplyStageLabels(context.Background()); err != nil { + t.Fatal(err) + } + if rec, ok := store.Get(stageKey("acme", "widget", 15159)); !ok || rec.Stage != stagelabels.NeedsDecision { + t.Fatalf("pass 1 record = %+v, want 085", rec) + } + + // Pass 2: the operator swapped 085 for 072 by hand; the lane + // still reports sentinel-blocked on the same head. + api.reset() + pr = nudgePR(15159, "sha7", sentinel, "role/trusted", "author/clanker", "stage/072-returned-to-contributor") + e.recordStage(stageLaneContributor, "acme/widget", "acme", "widget", pr, contributorLaneReasonSentinelBlocked, false, nil) + e.noteStageRole("acme", "widget", 15159, stagelabels.RoleTrusted) + if _, err := e.ApplyStageLabels(context.Background()); err != nil { + t.Fatal(err) + } + rec, _ := store.Get(stageKey("acme", "widget", 15159)) + req, recorded := requests.For("acme/widget", 15159, "sha7") + if !tc.held { + if !slices.Contains(api.removed, "stage/072-returned-to-contributor") || rec.Stage != stagelabels.NeedsDecision || recorded { + t.Fatalf("%s: removed=%v record=%+v recorded=%v, want 085 re-asserted", tc.name, api.removed, rec, recorded) + } + return + } + if len(api.removed) != 0 || slices.ContainsFunc(api.added, func(l []string) bool { return slices.Contains(l, "stage/085-needs-decision") }) { + t.Fatalf("hand-placed 072 overridden: added=%v removed=%v", api.added, api.removed) + } + if rec.Stage != stagelabels.ReturnedToContributor || rec.Reason != autoMergeReasonHumanChangesRequested { + t.Fatalf("record = %+v, want 072 %s", rec, autoMergeReasonHumanChangesRequested) + } + if !recorded || req.Source != review.HumanChangeRequestSourceStageLabel || req.Actor != "clubanderson" || req.IsApproval() { + t.Fatalf("recorded request = %+v ok=%v", req, recorded) + } + + // Pass 3: same head again — held from the store, no event read. + api.reset() + api.issueEvents = nil + e.recordStage(stageLaneContributor, "acme/widget", "acme", "widget", pr, contributorLaneReasonSentinelBlocked, false, nil) + e.noteStageRole("acme", "widget", 15159, stagelabels.RoleTrusted) + if _, err := e.ApplyStageLabels(context.Background()); err != nil { + t.Fatal(err) + } + if len(api.removed) != 0 || len(api.added) != 0 { + t.Fatalf("same head flapped: added=%v removed=%v", api.added, api.removed) + } + + // Pass 4: a new head re-arms the sentinel park. + api.reset() + pr = nudgePR(15159, "sha8", sentinel, "role/trusted", "author/clanker", "stage/072-returned-to-contributor") + e.recordStage(stageLaneContributor, "acme/widget", "acme", "widget", pr, contributorLaneReasonSentinelBlocked, false, nil) + e.noteStageRole("acme", "widget", 15159, stagelabels.RoleTrusted) + if _, err := e.ApplyStageLabels(context.Background()); err != nil { + t.Fatal(err) + } + rec, _ = store.Get(stageKey("acme", "widget", 15159)) + if !slices.Contains(api.removed, "stage/072-returned-to-contributor") || rec.Stage != stagelabels.NeedsDecision { + t.Fatalf("new head: removed=%v record=%+v, want 085 again", api.removed, rec) + } + }) + } +} diff --git a/src/pkg/github/automerge/automerge_stage_labels.go b/src/pkg/github/automerge/automerge_stage_labels.go index 6620ed2bf2..504d511801 100644 --- a/src/pkg/github/automerge/automerge_stage_labels.go +++ b/src/pkg/github/automerge/automerge_stage_labels.go @@ -532,13 +532,23 @@ func (c *Engine) foldRecordedDecision(list []stageObservation) { } for i := range list { o := &list[i] - if o.HeadSHA == "" || (o.Detail.VerdictKnown && o.Detail.Verdict.DecisionAnswered && o.Detail.Verdict.DecisionAnsweredHead == o.HeadSHA) { + if o.HeadSHA == "" { continue } req, ok := review.DecisionAnswerFor(c.humanChangeRequests, o.Owner+"/"+o.Repo, o.Number, o.HeadSHA) if !ok { continue } + // A standing change request is the person's answer whether or not + // a reviewer verdict was read for the head: a lane that skipped + // before reviews (the contributor lane on a sentinel park, + // hivecommons/hive#15159) carries no verdict to hang it on. + if !req.IsApproval() && o.Detail.HumanChangeRequestHead != o.HeadSHA { + o.Detail.HumanChangeRequester, o.Detail.HumanChangeRequestHead = strings.TrimSpace(req.Actor), o.HeadSHA + } + if o.Detail.VerdictKnown && o.Detail.Verdict.DecisionAnswered && o.Detail.Verdict.DecisionAnsweredHead == o.HeadSHA { + continue + } o.Detail.Verdict = o.Detail.Verdict.WithDecisionAnswer(strings.ToLower(req.Actor), o.HeadSHA, req.Directive()) o.Detail = normalizeStageDetail(o.Detail) } @@ -844,6 +854,7 @@ func (c *Engine) ApplyStageLabels(ctx context.Context) (StageLabelResult, error) continue } result.Items++ + c.foldHumanReturnLabel(ctx, store, list) c.foldRecordedDecision(list) verdict, role, obs := resolveStage(list) key := stageKey(obs.Owner, obs.Repo, obs.Number) diff --git a/src/pkg/github/automerge/automerge_sweep.go b/src/pkg/github/automerge/automerge_sweep.go index f8b3febc3b..fc809b2c70 100644 --- a/src/pkg/github/automerge/automerge_sweep.go +++ b/src/pkg/github/automerge/automerge_sweep.go @@ -203,7 +203,12 @@ type Engine struct { selfSkipWarned map[string]struct{} mergerAuthzMu sync.RWMutex - mergerAuthz MergerAuthorizer + // humanReturnChecked remembers, per PR key, the head whose worn + // 071/072 label was already attributed (see foldHumanReturnLabel), so + // the label events are read once per head, not every pass. + humanReturnCheckedMu sync.Mutex + humanReturnChecked map[string]string + mergerAuthz MergerAuthorizer // maintainerPerm caches whether a PR author holds admin or maintain on // the PR's repository (authorMaintainsRepo): adoption never takes over diff --git a/src/pkg/github/automerge/reporter_trust_release.go b/src/pkg/github/automerge/reporter_trust_release.go index 189a3e85ae..a06d6302fd 100644 --- a/src/pkg/github/automerge/reporter_trust_release.go +++ b/src/pkg/github/automerge/reporter_trust_release.go @@ -93,6 +93,12 @@ func (c *Engine) listAllIssueComments(ctx context.Context, owner, repo string, n // latestHoldLabelEvent returns the newest labeled / unlabeled event for the // literal `hold` label, nil when there is none. func (c *Engine) latestHoldLabelEvent(ctx context.Context, owner, repo string, number int) (*gh.IssueEvent, error) { + return c.latestLabelEvent(ctx, owner, repo, number, "hold") +} + +// latestLabelEvent returns the newest labeled / unlabeled event for the +// named label, nil when there is none. +func (c *Engine) latestLabelEvent(ctx context.Context, owner, repo string, number int, name string) (*gh.IssueEvent, error) { var latest *gh.IssueEvent opts := &gh.ListOptions{PerPage: 100} for { @@ -101,7 +107,7 @@ func (c *Engine) latestHoldLabelEvent(ctx context.Context, owner, repo string, n return nil, fmt.Errorf("listing issue events: %w", err) } for _, event := range events { - if event == nil || !strings.EqualFold(event.GetLabel().GetName(), "hold") { + if event == nil || !strings.EqualFold(event.GetLabel().GetName(), name) { continue } if event.GetEvent() != "labeled" && event.GetEvent() != "unlabeled" { diff --git a/src/pkg/review/human_change_request.go b/src/pkg/review/human_change_request.go index f24b91c6a7..2427b3f918 100644 --- a/src/pkg/review/human_change_request.go +++ b/src/pkg/review/human_change_request.go @@ -28,6 +28,11 @@ const ( // HumanChangeRequestSourceDecision is a trusted human's `/hive decision // ` comment on the PR while it sat at stage 085. HumanChangeRequestSourceDecision = "decision" + // HumanChangeRequestSourceStageLabel is a trusted human moving the PR + // back to its author by hand — adding stage/071-needs-author or + // stage/072-returned-to-contributor — while the hive had it parked for + // a person (hivecommons/hive#15159). SourceID is the label event. + HumanChangeRequestSourceStageLabel = "stage-label" ) // Kinds of a HumanChangeRequest. @@ -53,7 +58,7 @@ type HumanChangeRequest struct { Repo string `json:"repo"` Number int `json:"number"` HeadSHA string `json:"head_sha"` - // Source is HumanChangeRequestSourceReview or ...Decision. + // Source is HumanChangeRequestSourceReview, ...Decision or ...StageLabel. Source string `json:"source"` // SourceID is the review ID or comment ID: with HeadSHA it is the // dedupe key, so the same review is never recorded (or kicked) twice. From 527d63cf78db92555f478bb40be5bb82b1187c8e Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Wed, 28 Oct 2026 23:12:23 -0400 Subject: [PATCH 3/3] fix: drop unused openPullRequestHead wrapper Signed-off-by: Andrew Anderson --- src/pkg/github/pr_decision_operator.go | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/src/pkg/github/pr_decision_operator.go b/src/pkg/github/pr_decision_operator.go index fc529614f8..d1146094d7 100644 --- a/src/pkg/github/pr_decision_operator.go +++ b/src/pkg/github/pr_decision_operator.go @@ -242,15 +242,9 @@ func ParsePRApprovalCommandComment(body string) (command, actor, head string, ok return command, actor, head, true } -// openPullRequestHead returns the PR's head SHA and whether the hive opened -// it, or ErrPullRequestClosed / a not-found error. -func (c *Client) openPullRequestHead(ctx context.Context, owner, name string, number int) (head string, selfAuthored bool, err error) { - head, selfAuthored, _, err = c.openPullRequestHeadLabels(ctx, owner, name, number) - return head, selfAuthored, err -} - -// openPullRequestHeadLabels is openPullRequestHead plus the PR's labels as -// read in the same fetch. +// openPullRequestHeadLabels returns the PR's head SHA, whether the hive +// opened it, and its labels as read in the same fetch, or +// ErrPullRequestClosed / a not-found error. func (c *Client) openPullRequestHeadLabels(ctx context.Context, owner, name string, number int) (head string, selfAuthored bool, labels []string, err error) { t, err := c.openPullRequestDecisionTarget(ctx, owner, name, number) return t.head, t.selfAuthored, t.labels, err