diff --git a/changelog.d/fixed-owner-approve-clears-park.md b/changelog.d/fixed-owner-approve-clears-park.md new file mode 100644 index 0000000000..13f43e666e --- /dev/null +++ b/changelog.d/fixed-owner-approve-clears-park.md @@ -0,0 +1 @@ +- Dashboard *Decide… → Approve* on a parked pull request now records the person's approval against the PR head (the auto-merge lanes and the stage engine read it as the answer to a `requires_human` / decision-requested verdict, like a trusted merger's Approve review), lifts the hive's `needs-human` park, removes the `sentinel-alert` label and records a head-keyed `sentinel_acknowledged` action in the review evidence bundle so bundle-only sentinel alerts clear too, re-derives the stage and drops the tracker cache. Before, it only posted the `/lgtm` + `/approve` comments, which no lane read, so the row stayed at stage/085 *Needs human decision*; the delegated *Let hive decide* path is unchanged (comments only, never clears a sentinel alert). The activity monitor's lit chevron for a detour (085 on the Merge gate column) now names the parking stage in its hover instead of borrowing "Awaiting merge admission … Next move: human" from the column. diff --git a/src/docs/api-reference.md b/src/docs/api-reference.md index 26c21a9ba2..a014d9319e 100644 --- a/src/docs/api-reference.md +++ b/src/docs/api-reference.md @@ -284,7 +284,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:332`, `pkg/dashboard/api_repo_hold.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:333`, `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 (the merge gate decides from there; no review, label or 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:334`, `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 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:334`, `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:524`, `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:338`, `pkg/dashboard/api_acmm_eval.go` | diff --git a/src/docs/dashboard-sections.md b/src/docs/dashboard-sections.md index 3ea34a22ef..b5d84fe34c 100644 --- a/src/docs/dashboard-sections.md +++ b/src/docs/dashboard-sections.md @@ -652,7 +652,7 @@ Fed by `GET /api/stage-tracker`. Every issue and pull request follows the same p **Movement animation (⚙ on the card header).** When a refresh moves an item's lit chevron to a different column — forward (advance) or backward (regress) — the row plays a short, subtle three-beat sequence so the eye can see where it went: first the chevron it is *leaving* flashes the active highlight twice (two ~140 ms pulses with a short gap), then the chosen effect travels from that chevron to the new one, and finally the new chevron lands lit — the whole sequence takes about a second. Pick the travel effect in the same settings modal, under **Movement animation** below the sound settings: **None**, **A Sliding puck** (a highlight glides from the old chevron to the new one and settles), **B Ripple** (each chevron between old and new lights in turn), **C Ghost crossfade** (the old highlight fades out while the new one fades in with a slight slide), **D Comet** (a streak with a bright head travels the strip and lands on the destination), **E Destination bump** (the destination chevron scales briefly with a fading direction arrow), or **F Colour wash** (default — a tinted sweep flows across the intermediate chevrons). Each option has a *Preview* button that plays the full flash → move → land sequence on a sample row inside the dialog. The choice is remembered per browser (`localStorage` key `hiveStageTrackerMotion`). Items that stay put never move; a row that leaves the list (merged, closed, or filtered away) collapses and fades out over `--ham-move-exit-ms` and a row that arrives fades in over `--ham-move-enter-ms`; nothing animates on first load, and at most twelve rows animate per refresh (a filter or page change that turns over more rows than that redraws at once). The list is reconciled row by row on every refresh rather than rebuilt, so a move keeps playing while the hive keeps publishing. When the operating system asks for reduced motion (`prefers-reduced-motion: reduce`), every style falls back to a single soft flash followed by a plain crossfade and departing rows only fade, regardless of the setting; **None** disables the flash, the effect and the row fades entirely. Durations, the flash timing (`--ham-move-flash-ms`, `--ham-move-flash-gap-ms`, `--ham-move-flash-count`) and tints come from the `--ham-move-*` tokens in `tokens.css`. -**Sentinel alert.** A pull request the suspicious-activity sentinel flagged — it wears the `sentinel-alert` label (`sentinel.label`), or the review evidence bundle for its current head records sentinel findings — carries `sentinel_alert: true` in the tracker payload (with `sentinel_findings` and a short `sentinel_reason` when the bundle has them); a webhook label change flips it live. In the **Needs human decision** lane the lit chevron's own words read **Sentinel alert · needs human** (danger-tinted, the same wording in the cell's `title` and `aria-label`, and in the compact caption), so a maintainer reads the security implication before the stage mechanics; in every other lane at or past the merge gate (080, 090, 095, 100) the row shows a compact danger-tinted `sentinel` chip ahead of `needs rebase` / `regressed` / `stalled`; before the gate the chip is held back with the other merge-gate pills (see *Pills before the merge gate*) while `sentinel_alert` stays truthful in the payload. The tooltip reads "Sentinel flagged security-relevant changes at ``: ``" (a generic description stands in when the bundle has no reason). An issue carried by one flagged PR shows the lane text too, and a nested PR sub-row shows its own. The *Decide…* dialogs for a flagged PR open with a ⚠ line per flagged PR naming the sentinel reason, and *Approve* is styled as a dangerous action. Lane text and chip update in place on refresh (keyed reconcile, no flash). +**Sentinel alert.** A pull request the suspicious-activity sentinel flagged — it wears the `sentinel-alert` label (`sentinel.label`), or the review evidence bundle for its current head records sentinel findings — carries `sentinel_alert: true` in the tracker payload (with `sentinel_findings` and a short `sentinel_reason` when the bundle has them); a webhook label change flips it live. In the **Needs human decision** lane the lit chevron's own words read **Sentinel alert · needs human** (danger-tinted, the same wording in the cell's `title` and `aria-label`, and in the compact caption), so a maintainer reads the security implication before the stage mechanics; in every other lane at or past the merge gate (080, 090, 095, 100) the row shows a compact danger-tinted `sentinel` chip ahead of `needs rebase` / `regressed` / `stalled`; before the gate the chip is held back with the other merge-gate pills (see *Pills before the merge gate*) while `sentinel_alert` stays truthful in the payload. The tooltip reads "Sentinel flagged security-relevant changes at ``: ``" (a generic description stands in when the bundle has no reason). An issue carried by one flagged PR shows the lane text too, and a nested PR sub-row shows its own. The *Decide…* dialogs for a flagged PR open with a ⚠ line per flagged PR naming the sentinel reason, and *Approve* is styled as a dangerous action. A person's *Approve* through that dialog **is** the human review the alert asked for: it removes the `sentinel-alert` label when present and records a `sentinel_acknowledged` human action keyed to the head in the review evidence bundle, so a bundle-only alert (findings but no label — hivecommons/crux#30) clears too; the payload then reads `sentinel_alert: false` with `sentinel_reason` suffixed `— acknowledged by @login`, the findings stay on record, and a new head starts over. The delegated *Let hive decide* path never clears it. Hovering the lit chevron of a parked row names the parking stage itself (`Needs human decision`), not the 080 column it rides on; `Next move` follows the real stage (human at 085, hive at 080). Lane text and chip update in place on refresh (keyed reconcile, no flash). **Unauthorized pill.** A pull request the hive cannot move because its GitHub App lacks a permission for the next step — it wears `hive:unauthorized` ([#14589](https://github.com/hivecommons/hive/issues/14589)); first case: approving held `action_required` workflow runs needs `actions: write` — carries the `unauthorized` modifier in the tracker payload, drawn in the far-right pill column exactly like `stalled` / `hold` / `draft` but muted (dashed, `--text-muted`), never red: it is nothing wrong, just a step only a person may take. It counts under **Needs attention**. Before the merge gate only the held-workflow-runs step shows (see *Pills before the merge gate*). Its tooltip (payload `unauthorized`) names the missing permission and the human step; on the **Needs human decision** lane the lit chevron and the caption read **Awaiting human: approve workflow runs** (payload `unauthorized_step`, from the `unauthorized:` stage reason). The pill, label and payload fields clear themselves in the tick the step is no longer needed. @@ -675,7 +675,7 @@ Fed by `GET /api/stage-tracker`. Every issue and pull request follows the same p **Row gutter.** Every issue and PR row (never a column or repo-group header) carries a left gutter with a select checkbox and a ⋯ actions button that is always present and always visible: dimmed at rest (`--ham-tool-rest-opacity`), at full emphasis on the row under the pointer or holding focus, on a selected row, and on every row while anything is selected or the context menu is open — the only animation is the hover fade (`--ham-tool-fade-ms`, ≤ 120 ms), and nothing about it depends on scrolling, row position or which rows the live refresh re-created. -**Row actions (right-click, ⋯, Shift+F10).** Right-clicking a row — or a nested PR sub-row — opens an in-app context menu of the actions that fit that item's current state; the ⋯ button in the row's left gutter opens the same menu for pointer-free use, and so do **Shift+F10** and the context-menu key while the row or anything in it has focus (every row is a tab stop). The menu is positioned at the pointer, clamped to the viewport, uses `menu` / `menuitem` roles, moves focus with ↑ ↓ Home End, opens the *Decide…* group with → and closes it with ←, and closes on Esc, Tab, click-away, scroll or resize, returning focus to the row. Shift+right-click keeps the browser's own menu. Entries, each shown only when it applies: **Decide…** on a row waiting on a person — a PR wearing the *Needs human decision* pill at 085 on the Merge gate column (the primary case: e.g. two competing `dibs` PRs), an issue row whose nested PR is parked there (the menu reads *Decide PR #458…* and acts on that PR, since the issue's own stage is only mirrored from it), or an issue parked at 045. The first entry is always *Let hive decide* (see [Let hive decide](#let-hive-decide) below): the hive decides as the owner's delegate and records it the way a person's decision is recorded. For a PR: *Approve (/lgtm + /approve)* posts those two commands as comments attributed to you — the merge gate takes it from there exactly as if you had typed them; the dashboard reviews, labels and merges nothing — *Close as superseded by…* (a picker listing the other open PRs in the repo, or type `#458` / `owner/repo#458` / a URL; then an optional comment, then the sweep's labelled close), *Won't fix…* (a comment naming you, then a not-planned close) and *Give direction…* (your text is recorded as `/hive decision ` against the head, so the author agent pushes a new head; only on PRs the hive opened). For an issue: *Approve direction* (records the same `/hive approve` a maintainer would comment: the parking labels come off, `approved-direction` goes on, the stage engine logs the un-park and a reply comment names you; nothing is merged), *Send back to the hive…* (`/hive decision `), *Close as superseded by…* and *Close as won't-fix…*. A selection mixing parked issues and parked PRs has Decide… greyed; **Hold** or **Release hold** depending on the `hold` chip (the same `…/items/{number}/hold` toggle as the repository cards, and the same permission — owner, or a signed-in user with write access to the repo); **Re-evaluate now** (the hive-wide read-only rescan behind the Overview's refresh — a rescan already running is reported, not duplicated); **Accept triage** (only on an issue the chevron calls *Triage needed* — stage 015, or the `needs-triage` chip on another stage — never on a PR; the one-click form of a maintainer accepting triage on GitHub: adds the reporter-trust triage label, `triage/accepted` by default or the first of `issue_filter.reporter_trust.untrusted_require_labels`, removes the awaiting label `needs-triage` / `reporter_trust.awaiting_label` and a Hive-written `stage/015-triage-needed`; the row re-reads *Actionable* with the 👤 gone at once, the reporter-trust gate admits the issue on its next poll and the stage engine records 015 → 010; same permission as Hold, audited as `repo_item_accept_triage`, a no-op when already accepted); **Mark needs-human…** (hidden once the chip is on; merger or owner role, applies `needs-human` and a marker comment through the review pipeline's send-to-human endpoint); **Open on GitHub**; **Copy link**. Entries you may not use are greyed with the reason in their tooltip, never hidden. Confirmation and free-text input use the dashboard's own dialogs — no browser prompts. Every action is an existing audited dashboard endpoint (the decision endpoint is `POST /api/repos/{owner}/{repo}/items/{number}/decision` and triage acceptance is `POST /api/repos/{owner}/{repo}/items/{number}/accept-triage`, see [api-reference.md](api-reference.md)); none of them bypasses the hive's governance or merges anything. +**Row actions (right-click, ⋯, Shift+F10).** Right-clicking a row — or a nested PR sub-row — opens an in-app context menu of the actions that fit that item's current state; the ⋯ button in the row's left gutter opens the same menu for pointer-free use, and so do **Shift+F10** and the context-menu key while the row or anything in it has focus (every row is a tab stop). The menu is positioned at the pointer, clamped to the viewport, uses `menu` / `menuitem` roles, moves focus with ↑ ↓ Home End, opens the *Decide…* group with → and closes it with ←, and closes on Esc, Tab, click-away, scroll or resize, returning focus to the row. Shift+right-click keeps the browser's own menu. Entries, each shown only when it applies: **Decide…** on a row waiting on a person — a PR wearing the *Needs human decision* pill at 085 on the Merge gate column (the primary case: e.g. two competing `dibs` PRs), an issue row whose nested PR is parked there (the menu reads *Decide PR #458…* and acts on that PR, since the issue's own stage is only mirrored from it), or an issue parked at 045. The first entry is always *Let hive decide* (see [Let hive decide](#let-hive-decide) below): the hive decides as the owner's delegate and records it the way a person's decision is recorded. For a PR: *Approve (/lgtm + /approve)* posts those two commands as comments attributed to you and records your approval against the PR's current head as the human answer the row was parked for — a `requires_human` / decision-requested reviewer verdict, the hive's own `needs-human` park (a supersession question, say), the `sentinel-alert` label and the evidence bundle's sentinel findings are all released by it (the response's `released` lists what was: `approval-recorded`, `needs-human`, `sentinel-label`, `sentinel-acknowledged`), the stage engine re-derives the stage on the spot and the tracker cache is dropped, so the row leaves *Needs human decision* for 080 *Awaiting merge admission* on the next read; the merge gate (and the auto-merge lanes, which honour the recorded approval on that head exactly as a trusted merger's GitHub Approve review) takes it from there; the dashboard never reviews as you and never merges. A new head carries no answer: pushing to the PR re-asks. The delegated *Let hive decide* path still posts the comments only — it recommends and never clears a sentinel alert — *Close as superseded by…* (a picker listing the other open PRs in the repo, or type `#458` / `owner/repo#458` / a URL; then an optional comment, then the sweep's labelled close), *Won't fix…* (a comment naming you, then a not-planned close) and *Give direction…* (your text is recorded as `/hive decision ` against the head, so the author agent pushes a new head; only on PRs the hive opened). For an issue: *Approve direction* (records the same `/hive approve` a maintainer would comment: the parking labels come off, `approved-direction` goes on, the stage engine logs the un-park and a reply comment names you; nothing is merged), *Send back to the hive…* (`/hive decision `), *Close as superseded by…* and *Close as won't-fix…*. A selection mixing parked issues and parked PRs has Decide… greyed; **Hold** or **Release hold** depending on the `hold` chip (the same `…/items/{number}/hold` toggle as the repository cards, and the same permission — owner, or a signed-in user with write access to the repo); **Re-evaluate now** (the hive-wide read-only rescan behind the Overview's refresh — a rescan already running is reported, not duplicated); **Accept triage** (only on an issue the chevron calls *Triage needed* — stage 015, or the `needs-triage` chip on another stage — never on a PR; the one-click form of a maintainer accepting triage on GitHub: adds the reporter-trust triage label, `triage/accepted` by default or the first of `issue_filter.reporter_trust.untrusted_require_labels`, removes the awaiting label `needs-triage` / `reporter_trust.awaiting_label` and a Hive-written `stage/015-triage-needed`; the row re-reads *Actionable* with the 👤 gone at once, the reporter-trust gate admits the issue on its next poll and the stage engine records 015 → 010; same permission as Hold, audited as `repo_item_accept_triage`, a no-op when already accepted); **Mark needs-human…** (hidden once the chip is on; merger or owner role, applies `needs-human` and a marker comment through the review pipeline's send-to-human endpoint); **Open on GitHub**; **Copy link**. Entries you may not use are greyed with the reason in their tooltip, never hidden. Confirmation and free-text input use the dashboard's own dialogs — no browser prompts. Every action is an existing audited dashboard endpoint (the decision endpoint is `POST /api/repos/{owner}/{repo}/items/{number}/decision` and triage acceptance is `POST /api/repos/{owner}/{repo}/items/{number}/accept-triage`, see [api-reference.md](api-reference.md)); none of them bypasses the hive's governance or merges anything. **Multi-select.** The checkbox in a row's left gutter selects the row; **Shift+click** selects the range from the last clicked row, **Cmd/Ctrl+click** toggles, **Cmd/Ctrl+Shift+click** adds a range to what is selected; with a row focused, **Space** toggles it (Shift+Space extends). Cmd/Ctrl- or Shift-clicking the row itself, away from its links, selects it too. A selection bar appears above the list with the count, **Clear**, and the same actions for the whole selection — *Decide…* (opens the group as a menu, *Let hive decide* first — each selected row gets its own delegated-decision job, see below), *Hold*, *Release hold*, *Re-evaluate now*, *Mark needs-human…*, *Copy links* — each enabled only when it is valid for every selected row and otherwise greyed with the first reason ("Not applicable to acme/console#12", "Sign in with write access…"). Right-clicking a selected row acts on the whole selection. Bulk actions run one request per row, in list order, under a progress toast ("Hold 2/5 — acme/console#12…"); the result toast lists each failure by row and the successes stand, after which the list and the status snapshot refresh (a hive-wide rescan is sent once per batch). Selection is keyed on the row's item (repository, kind, number), not its node, so the live re-render keeps it; a row that leaves the list — merged, closed, filtered or paged out — leaves the selection. diff --git a/src/pkg/dashboard/api_repo_item_decision.go b/src/pkg/dashboard/api_repo_item_decision.go index 4de2eef659..f419083dbd 100644 --- a/src/pkg/dashboard/api_repo_item_decision.go +++ b/src/pkg/dashboard/api_repo_item_decision.go @@ -23,8 +23,15 @@ import ( // maintainer with write access (Client.RecordOperatorIssueDecision): // park labels cleared, approved-direction applied, reply posted. On a // PR, the `/lgtm` and `/approve` commands posted as two attributed -// comments (Client.RecordOperatorPullRequestApproval) — the merge gate -// decides from there; nothing is reviewed, labelled or merged here. +// comments, the approval recorded against the head as the answer to a +// requires_human verdict, the hive's `needs-human` park and the +// sentinel alert (label and evidence-bundle findings) released, and the +// stage re-derived (Client.RecordOperatorPullRequestApprovalWith) — the +// merge gate decides from there; nothing is reviewed or merged here. +// The person's approval is the human review a requires_human verdict, +// a supersession ask or a sentinel alert was waiting for; before this +// the comments were read by no lane and the row stayed at stage/085 +// (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). @@ -110,6 +117,12 @@ type repoItemDecisionResponse struct { Decision string `json:"decision"` Status string `json:"status"` Label string `json:"label,omitempty"` + // Released lists what a PR approval cleared beyond posting the commands: + // "approval-recorded", "needs-human", "sentinel-label", + // "sentinel-acknowledged". Stage is the stage label the engine derived + // on the spot, when it did. + Released []string `json:"released,omitempty"` + Stage string `json:"stage,omitempty"` } func renderRepoItemDecisionCloseComment(verb, user, comment, supersededBy string) string { @@ -258,10 +271,17 @@ func (s *Server) handlePullRequestDecision(ctx context.Context, w http.ResponseW head string err error ) + var released []string + stage := "" if decision == repoItemDecisionApprove { var event ghpkg.PullRequestApprovalEvent - event, err = gh.RecordOperatorPullRequestApproval(ctx, repoFull, number, user) + event, err = gh.RecordOperatorPullRequestApprovalWith(ctx, repoFull, number, user, ghpkg.PullRequestApprovalOptions{ + HumanChangeRequests: repoItemDecisionChangeRequests(), + LiftNeedsHuman: true, + SentinelLabel: s.sentinelLabel(), + }) head = event.HeadSHA + released, stage = repoItemApprovalReleased(event), event.Stage } else { var event ghpkg.PullRequestDecisionEvent event, err = gh.RecordOperatorPullRequestDecision(ctx, repoFull, number, user, comment, repoItemDecisionChangeRequests()) @@ -288,6 +308,28 @@ func (s *Server) handlePullRequestDecision(ctx context.Context, w http.ResponseW if decision == repoItemDecisionDirection { action, status = auditRepoItemDecisionDirection, "direction-recorded" } - s.audit.LogRecord(user, action, auditDetail("repo", repoFull, "number", numStr, "type", "pr", "head", head, "decision", comment), "", repoFull, number) - jsonResponse(w, repoItemDecisionResponse{OK: true, Repo: repoFull, Number: number, Decision: decision, Status: status}) + s.audit.LogRecord(user, action, auditDetail("repo", repoFull, "number", numStr, "type", "pr", "head", head, "decision", comment, "released", strings.Join(released, ","), "stage", stage), "", 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}) +} + +// repoItemApprovalReleased names what a PR approval released, for the +// response and the audit line. +func repoItemApprovalReleased(event ghpkg.PullRequestApprovalEvent) []string { + var out []string + if event.Recorded { + out = append(out, "approval-recorded") + } + if event.NeedsHumanLifted { + out = append(out, "needs-human") + } + if event.SentinelLabelCleared { + out = append(out, "sentinel-label") + } + if event.SentinelAcknowledged { + out = append(out, "sentinel-acknowledged") + } + return out } diff --git a/src/pkg/dashboard/api_repo_item_decision_test.go b/src/pkg/dashboard/api_repo_item_decision_test.go index 5dbb6d182a..562bbb18c1 100644 --- a/src/pkg/dashboard/api_repo_item_decision_test.go +++ b/src/pkg/dashboard/api_repo_item_decision_test.go @@ -25,8 +25,10 @@ type repoItemDecisionMock struct { removed []string comments []string edits []map[string]any - // prForeign makes PR #8 look like a human opened it. + // prForeign makes PR #8 look like a human opened it; prLabels are the + // labels pulls/8 reports. prForeign bool + prLabels []string // prMergeState is PR #8's mergeable_state ("" = clean); prRedCI and // prNoCI shape the head's combined status when the state alone does not // settle CI (e.g. "blocked"). @@ -64,7 +66,11 @@ func newRepoItemDecisionServer(t *testing.T, m *repoItemDecisionMock) *Server { if mergeState == "" { mergeState = "clean" } - _ = json.NewEncoder(w).Encode(map[string]any{"number": 8, "state": "open", "labels": []any{}, "user": author, "mergeable": true, "mergeable_state": mergeState, "head": map[string]any{"sha": "feedfacefeedfacefeedfacefeedfacefeedface"}}) + prLabels := make([]map[string]string, 0, len(m.prLabels)) + for _, label := range m.prLabels { + prLabels = append(prLabels, map[string]string{"name": label}) + } + _ = json.NewEncoder(w).Encode(map[string]any{"number": 8, "state": "open", "labels": prLabels, "user": author, "mergeable": true, "mergeable_state": mergeState, "head": map[string]any{"sha": "feedfacefeedfacefeedfacefeedfacefeedface"}}) case r.Method == http.MethodGet && strings.HasSuffix(path, "/commits/feedfacefeedfacefeedfacefeedfacefeedface/status"): switch { case m.prRedCI: @@ -284,6 +290,51 @@ func TestRepoItemDecisionApprovePRPostsLgtmAndApproveComments(t *testing.T) { } } +// TestRepoItemDecisionApprovePRReleasesThePark: the owner's Approve on a +// parked PR is the human review it waited for — the approval is recorded +// against the head (the lanes and the stage engine read it as the answer to +// requires_human / decision-requested), `needs-human` and the sentinel label +// come off, and the tracker cache is dropped so the next read re-derives the +// stage (hivecommons/hive#14821, #14822, crux#30 stayed at 085 with only the +// command comments written). +func TestRepoItemDecisionApprovePRReleasesThePark(t *testing.T) { + mock := &repoItemDecisionMock{prForeign: true, prLabels: []string{"stage/085-needs-decision", "needs-human", "sentinel-alert", "role/trusted"}} + srv := newRepoItemDecisionServer(t, mock) + srv.stageTrackerCacheMu.Lock() + gen := srv.stageTrackerGen + srv.stageTrackerCacheMu.Unlock() + + w := postRepoItemDecision(t, srv, 8, "writer", `{"decision":"approve","type":"pr"}`) + if w.Code != http.StatusOK { + t.Fatalf("approve PR: code=%d body=%s", w.Code, w.Body.String()) + } + var resp repoItemDecisionResponse + _ = json.Unmarshal(w.Body.Bytes(), &resp) + if resp.Status != "approval-commented" || strings.Join(resp.Released, ",") != "approval-recorded,needs-human,sentinel-label" { + t.Fatalf("response = %+v", resp) + } + req, ok := repoItemDecisionChangeRequests().For("testorg/testrepo", 8, "feedfacefeedfacefeedfacefeedfacefeedface") + if !ok || !req.IsApproval() || req.Actor != "writer" { + t.Fatalf("approval must stand against the head: %+v ok=%v", req, ok) + } + if strings.Join(mock.removed, ",") != "needs-human,sentinel-alert" { + t.Fatalf("removed = %v", mock.removed) + } + if len(mock.comments) != 2 || len(mock.added)+len(mock.edits) != 0 { + t.Fatalf("approval still posts the two commands and nothing else: comments=%d added=%v edits=%v", len(mock.comments), mock.added, mock.edits) + } + srv.stageTrackerCacheMu.Lock() + stale, after := srv.stageTrackerCache.stale, srv.stageTrackerGen + srv.stageTrackerCacheMu.Unlock() + if !stale || after == gen { + t.Fatalf("tracker cache must be invalidated: stale=%v gen %d -> %d", stale, gen, after) + } + detail := srv.GetAudit().Recent(1)[0].Detail + if !strings.Contains(detail, "released=approval-recorded,needs-human,sentinel-label") { + t.Fatalf("audit detail = %q", detail) + } +} + func TestRepoItemDecisionDirectionPRRecordsChangeRequest(t *testing.T) { mock := &repoItemDecisionMock{} srv := newRepoItemDecisionServer(t, mock) diff --git a/src/pkg/dashboard/stage_tracker.go b/src/pkg/dashboard/stage_tracker.go index c07319a62b..0669220079 100644 --- a/src/pkg/dashboard/stage_tracker.go +++ b/src/pkg/dashboard/stage_tracker.go @@ -669,7 +669,12 @@ const stageTrackerSentinelMoreFormat = " (+%d more)" // label is gone is reported as cleared — findings and reason still fill // the tooltip, alert does not. One file read per PR with a known head, // ENOENT when the sentinel never wrote one; the tracker payload is memoised -// so this runs once per snapshot, not per request. +// so this runs once per snapshot, not per request. A person's sentinel +// acknowledgment on the bundle (evidence.ActionSentinelAcknowledged — the +// owner's Approve decision on a flagged PR) is the human review a +// notice-only alert asked for, so it clears the bundle-promoted alert (the +// label, while still on, still stands); the reason then names who +// acknowledged it. func (s *Server) stageTrackerSentinel(verifier *github.ReviewEvidenceVerifier, repo string, number int, head string, labels []string) (alert bool, findings int, reason string) { label := s.sentinelLabel() for _, l := range labels { @@ -693,6 +698,11 @@ func (s *Server) stageTrackerSentinel(verifier *github.ReviewEvidenceVerifier, r if findings > 1 { reason += fmt.Sprintf(stageTrackerSentinelMoreFormat, findings-1) } + if by := b.SentinelAcknowledgedBy(); by != "" { + // The label, while still on, is the sweep's live block; only the + // bundle-promoted alert is answered by the acknowledgment. + return alert, findings, reason + stageTrackerSentinelAckSuffix + by + } for _, f := range b.Sentinel { if f.Notice { alert = true @@ -702,6 +712,10 @@ func (s *Server) stageTrackerSentinel(verifier *github.ReviewEvidenceVerifier, r return alert, findings, reason } +// stageTrackerSentinelAckSuffix precedes the login of the person whose +// approval acknowledged the bundle's sentinel findings. +const stageTrackerSentinelAckSuffix = " — acknowledged by @" + // stageTrackerModifierOrder is the modifier precedence the payload carries. var stageTrackerModifierOrder = []string{modStalled, modRegressed, modHold, modUnauthorized, modNeedsHuman, modNeedsDecision, modNeedsTriage, modPossibleDupe, modNeedsRebase, modBlocked, modDraft} diff --git a/src/pkg/dashboard/stage_tracker_sentinel_lane_test.go b/src/pkg/dashboard/stage_tracker_sentinel_lane_test.go index 8db8740e63..405eedfc2c 100644 --- a/src/pkg/dashboard/stage_tracker_sentinel_lane_test.go +++ b/src/pkg/dashboard/stage_tracker_sentinel_lane_test.go @@ -51,13 +51,13 @@ func stageTrackerManualMergeJS(t *testing.T, html string) string { }, "\n") } -func writeSentinelBundle(t *testing.T, root, repo string, number int, head string, findings []evidence.SentinelFinding) { +func writeSentinelBundle(t *testing.T, root, repo string, number int, head string, findings []evidence.SentinelFinding, actions ...evidence.Action) { t.Helper() path := github.ReviewEvidencePath(root, repo, number, head) if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { t.Fatal(err) } - b := evidence.Bundle{SchemaVersion: evidence.SchemaVersion, Repo: repo, Number: number, HeadSHA: head, Sentinel: findings} + b := evidence.Bundle{SchemaVersion: evidence.SchemaVersion, Repo: repo, Number: number, HeadSHA: head, Sentinel: findings, HumanActions: actions} if err := evidence.Seal(&b, nil); err != nil { t.Fatal(err) } @@ -203,15 +203,24 @@ func TestStageTrackerSentinelLabelClearsBlockingBundle(t *testing.T) { notice := []evidence.SentinelFinding{{Rule: "sensitive_path", Summary: "touches OWNERS", Notice: true}} mixed := []evidence.SentinelFinding{blocking[0], notice[0]} + ack := evidence.Action{Actor: "clubanderson", Kind: evidence.ActionSentinelAcknowledged, Detail: "approved from the Hive dashboard", At: time.Date(2026, 10, 28, 12, 50, 0, 0, time.UTC)} + other := evidence.Action{Actor: "clubanderson", Kind: "label_removed", At: ack.At} + tests := []struct { name string number int findings []evidence.SentinelFinding + actions []evidence.Action labels []string wantAlert bool wantFindings int wantReason string }{ + // The owner's Approve acknowledged the findings on this head + // (hivecommons/crux#30 had no label, so nothing else could clear it). + {name: "notice-only bundle acknowledged by owner approval", number: 406, findings: notice, actions: []evidence.Action{other, ack}, labels: []string{"stage/085-needs-decision"}, wantAlert: false, wantFindings: 1, wantReason: "touches OWNERS — acknowledged by @clubanderson"}, + {name: "blocking bundle acknowledged, label still on", number: 407, findings: blocking, actions: []evidence.Action{ack}, labels: []string{config.DefaultSentinelLabel}, wantAlert: true, wantFindings: 2, wantReason: "changes 1 sensitive path(s) (+1 more) — acknowledged by @clubanderson"}, + {name: "unrelated action does not acknowledge", number: 408, findings: notice, actions: []evidence.Action{other}, labels: nil, wantAlert: true, wantFindings: 1, wantReason: "touches OWNERS"}, {name: "blocking bundle, label still on", number: 401, findings: blocking, labels: []string{"lgtm", config.DefaultSentinelLabel}, wantAlert: true, wantFindings: 2, wantReason: "changes 1 sensitive path(s) (+1 more)"}, {name: "blocking bundle, label removed by maintainer", number: 402, findings: blocking, labels: []string{"lgtm", "stage/085-needs-decision"}, wantAlert: false, wantFindings: 2, wantReason: "changes 1 sensitive path(s) (+1 more)"}, {name: "notice-only bundle, never labelled", number: 403, findings: notice, labels: []string{"stage/050-review-pending"}, wantAlert: true, wantFindings: 1, wantReason: "touches OWNERS"}, @@ -221,7 +230,7 @@ func TestStageTrackerSentinelLabelClearsBlockingBundle(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if tt.findings != nil { - writeSentinelBundle(t, root, "acme/console", tt.number, head, tt.findings) + writeSentinelBundle(t, root, "acme/console", tt.number, head, tt.findings, tt.actions...) } alert, findings, reason := s.stageTrackerSentinel(verifier, "acme/console", tt.number, head, tt.labels) if alert != tt.wantAlert || findings != tt.wantFindings || reason != tt.wantReason { diff --git a/src/pkg/dashboard/stage_tracker_ui_test.go b/src/pkg/dashboard/stage_tracker_ui_test.go index b056463918..13aae68ffe 100644 --- a/src/pkg/dashboard/stage_tracker_ui_test.go +++ b/src/pkg/dashboard/stage_tracker_ui_test.go @@ -490,6 +490,15 @@ assert.strictEqual(stageTrackerHeadline({ kind: 'pr', stage: 70, modifiers: ['re row = stageTrackerRowHtml({ repo: 'acme/console', number: 356, kind: 'issue', stage: 40, linked_prs: [{ number: 109, author_kind: 'hive', stage: 85 }] }, stages, ctx); assert.deepStrictEqual(segStates(row), [D, D, D, D, D, 'active detoured', 'todo cap'], row); assert.ok(tooltip(row).includes('Needs a human decision (its PR)'), row); +// A PR parked at 085 lights the 080 column as a detour; its chevron hover +// names the parking stage, not the column it rides on — the owner read +// "Awaiting merge admission … Next move: human" on hivecommons/hive#14821 +// and #14822 while the engine still said 085. +row = stageTrackerRowHtml({ repo: 'acme/console', number: 14821, kind: 'pr', stage: 85, caption: 'decision requested' }, stages, ctx); +const chevronTip = (r) => (/
  • ]*title="([^"]*)" aria-current="step"/.exec(r) || [])[1] || ''; +assert.ok(chevronTip(row).startsWith('Needs human decision') && !chevronTip(row).includes('Awaiting merge admission') && !chevronTip(row).includes('not yet admitted') && chevronTip(row).includes('Next move: human'), 'detour chevron names its own stage: ' + chevronTip(row)); +row = stageTrackerRowHtml({ repo: 'acme/console', number: 14830, kind: 'pr', stage: 80, caption: 'CI green' }, stages, ctx); +assert.ok(chevronTip(row).startsWith('Awaiting merge admission — not yet admitted') && chevronTip(row).includes('Next move: hive'), '080 keeps its own hover: ' + chevronTip(row)); row = stageTrackerRowHtml({ repo: 'acme/console', number: 107, kind: 'pr', stage: 50, modifiers: ['needs-decision'] }, stages, ctx); assert.ok(row.includes('ham-mod-needs-decision">needs human decision') && tooltip(row).includes('Flags: needs human decision'), row); // Whose move it is, as an ink-coloured icon after the word: Review = hive, diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index e9d25f520d..6fc8a3c664 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -14054,8 +14054,12 @@

    Where to get help

    let state = 'todo'; if (terminal || n < anchor) state = 'done'; else if (n === anchor) state = 'active'; - // The lit column's tooltip names the real stage (030 vs 040, 060 vs 080). - const tipStage = (state === 'active' && !detour && curStage.label) ? curStage : st; + // The lit column's tooltip names the real stage (030 vs 040, 060 vs + // 080) — for a detour too: a 085 row lights the 080 column, and its + // hover must say "Needs human decision", not borrow the column's + // "Awaiting merge admission" text (hivecommons/hive#14821, #14822 + // read as 080 with "Next move: human"). + const tipStage = (state === 'active' && curStage.label) ? curStage : st; let word = state === 'active' && STAGE_TRACKER_ACTIVE_WORD[cur] ? STAGE_TRACKER_ACTIVE_WORD[cur] : (st.short || st.label || String(n)); const mods = Array.isArray(item.modifiers) ? item.modifiers : []; const openHold = n === 0 && state === 'active' && mods.indexOf('hold') >= 0; diff --git a/src/pkg/evidence/evidence.go b/src/pkg/evidence/evidence.go index 2556be4e32..8818e39c44 100644 --- a/src/pkg/evidence/evidence.go +++ b/src/pkg/evidence/evidence.go @@ -297,6 +297,32 @@ type Outcome struct { ClosedAt time.Time `json:"closed_at,omitzero"` } +// ActionSentinelAcknowledged is the HumanActions kind recorded when a person +// approved the head knowing the sentinel's findings on it: the bundle keeps +// the findings, and readers that would alert on them read the acknowledgment +// as the human review the alert was asking for. It is scoped to this bundle, +// so a new head carries no acknowledgment until a person gives one. +const ActionSentinelAcknowledged = "sentinel_acknowledged" + +// SentinelAcknowledgedBy returns the actor of the newest sentinel +// acknowledgment recorded on the bundle, or "" when none stands. +func (b *Bundle) SentinelAcknowledgedBy() string { + if b == nil { + return "" + } + actor := "" + var at time.Time + for _, a := range b.HumanActions { + if a.Kind != ActionSentinelAcknowledged || a.Actor == "" { + continue + } + if actor == "" || !a.At.Before(at) { + actor, at = a.Actor, a.At + } + } + return actor +} + // BundleID returns the canonical bundle identifier owner/repo#number@head. func BundleID(repo string, number int, head string) string { return fmt.Sprintf("%s#%d@%s", repo, number, head) diff --git a/src/pkg/github/pr_decision_operator.go b/src/pkg/github/pr_decision_operator.go index ee53c7bfd9..46b52ab6f1 100644 --- a/src/pkg/github/pr_decision_operator.go +++ b/src/pkg/github/pr_decision_operator.go @@ -6,6 +6,7 @@ import ( "fmt" "net/http" "strings" + "time" "github.com/hivecommons/hive/pkg/authorkind" "github.com/hivecommons/hive/pkg/review" @@ -18,7 +19,12 @@ import ( // // - approval posts the `/lgtm` and `/approve` commands as two comments — // the merge gate (Prow / tide, then the hive's own queue) decides from -// there, exactly as when the maintainer types them; +// there, exactly as when the maintainer types them. A person's approval +// (PullRequestApprovalOptions) is also recorded against the head as the +// answer to a requires_human verdict, lifts the `needs-human` park and +// the sentinel alert, and is submitted to the stage engine — the +// comments alone were read by no lane (#14821, #14822, crux#30 stayed +// at stage/085 after the owner approved); // - a direction is the `/hive decision ` lane of // tryUnparkPullRequest: recorded against the head so the review // planner kicks the author agent, then acknowledged in a reply. @@ -48,6 +54,49 @@ type PullRequestApprovalEvent struct { Number int HeadSHA string Actor string + // Recorded is true when the approval was written to the human change + // request store as the head-scoped answer the merge lanes and the stage + // engine honour (PullRequestApprovalOptions.HumanChangeRequests). + Recorded bool + // NeedsHumanLifted is true when the PR's `needs-human` label was taken + // off by this approval. + NeedsHumanLifted bool + // SentinelLabelCleared is true when the sentinel alert label was taken + // off by this approval; SentinelAcknowledged when the review evidence + // bundle for the head now records the person's acknowledgment of its + // sentinel findings. + SentinelLabelCleared bool + SentinelAcknowledged bool + // Stage is the stage label the engine derived when the approval was + // submitted to it, or "" when the stage write was deferred to the sweep. + Stage string +} + +// PullRequestApprovalOptions is what a person's Approve decision releases +// beyond posting the commands (hivecommons/hive: #14821, #14822, crux#30 +// sat at stage/085 after the owner approved from the dashboard — the +// comments were read by nobody but the workflow-path fence). The zero value +// posts the commands only, which is what the delegated "Let hive decide" +// path keeps: a recommendation must not clear a person's gate. +type PullRequestApprovalOptions struct { + // HumanChangeRequests, when set, records the approval against the head + // as a bare `approve` decision — the fact withRecordedDecision and the + // stage engine read as "the requires_human verdict on this head has + // been answered", for every lane, whoever authored the PR. + HumanChangeRequests review.HumanChangeRequestStore + // LiftNeedsHuman takes `needs-human` off the PR. The hive's own park + // (a supersession or adoption ask) is what the person just answered; a + // person's label is lifted on the same reasoning as an issue decision + // (stageengine.DecisionLiftsNeedsHuman). + LiftNeedsHuman bool + // SentinelLabel, when non-empty, is the alert label to take off: the + // Decide dialog showed the sentinel reason and styled Approve as + // dangerous, so the approval is the human review the alert asked for. + // The acknowledgment is also recorded in the head's evidence bundle so + // a bundle-only alert (no label) clears too. + SentinelLabel string + // Now stamps the acknowledgment; time.Now when nil. + Now func() time.Time } // prApprovalCommentMarkerPrefix opens the hidden marker a dashboard approval @@ -121,21 +170,29 @@ func ParsePRApprovalCommandComment(body string) (command, actor, head string, ok // 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. +func (c *Client) openPullRequestHeadLabels(ctx context.Context, owner, name string, number int) (head string, selfAuthored bool, labels []string, err error) { pr, resp, err := c.client.PullRequests.Get(ctx, owner, name, number) if err != nil { if resp != nil && resp.StatusCode == http.StatusNotFound { - return "", false, fmt.Errorf("pull request %s/%s#%d: %w", owner, name, number, ErrPullRequestNotFound) + return "", false, nil, fmt.Errorf("pull request %s/%s#%d: %w", owner, name, number, ErrPullRequestNotFound) } - return "", false, fmt.Errorf("fetching pull request %s/%s#%d: %w", owner, name, number, err) + return "", false, nil, fmt.Errorf("fetching pull request %s/%s#%d: %w", owner, name, number, err) } if strings.EqualFold(pr.GetState(), "closed") { - return "", false, ErrPullRequestClosed + return "", false, nil, ErrPullRequestClosed } if pr.GetHead() != nil { head = strings.TrimSpace(pr.GetHead().GetSHA()) } - selfAuthored = c.isHiveAccount(pr.GetUser()) || labelPresent(issueLabelNames(pr.Labels), authorkind.Hive.Label()) - return head, selfAuthored, nil + labels = issueLabelNames(pr.Labels) + selfAuthored = c.isHiveAccount(pr.GetUser()) || labelPresent(labels, authorkind.Hive.Label()) + return head, selfAuthored, labels, nil } func (c *Client) operatorPRTarget(repo string, number int, actor, what string) (owner, name string, err error) { @@ -161,27 +218,92 @@ func (c *Client) operatorPRTarget(repo string, number int, actor, what string) ( // the commands exactly as it would had the maintainer typed them. The // caller is responsible for having verified actor's write access. func (c *Client) RecordOperatorPullRequestApproval(ctx context.Context, repo string, number int, actor string) (PullRequestApprovalEvent, error) { + return c.RecordOperatorPullRequestApprovalWith(ctx, repo, number, actor, PullRequestApprovalOptions{}) +} + +// RecordOperatorPullRequestApprovalWith is RecordOperatorPullRequestApproval +// plus what opts asks the person's approval to release, in this order: the +// commands are posted first (the durable, visible record), then the +// approval is recorded against the head, the park labels the person just +// answered come off, the sentinel acknowledgment is written, and the stage +// engine is given the decision so the row moves now rather than on the +// next sweep. A failed label or stage write after the record is logged and +// reported on the event, not returned: the record stands, and the lanes +// derive the same answer from it on their next pass. +func (c *Client) RecordOperatorPullRequestApprovalWith(ctx context.Context, repo string, number int, actor string, opts PullRequestApprovalOptions) (PullRequestApprovalEvent, error) { owner, name, err := c.operatorPRTarget(repo, number, actor, "RecordOperatorPullRequestApproval") if err != nil { return PullRequestApprovalEvent{}, err } actor = strings.TrimSpace(actor) - head, _, err := c.openPullRequestHead(ctx, owner, name, number) + head, selfAuthored, labels, err := c.openPullRequestHeadLabels(ctx, owner, name, number) if err != nil { return PullRequestApprovalEvent{}, err } + full := owner + "/" + name for _, command := range PRApprovalCommands { - if err := c.CreateIssueComment(ctx, owner+"/"+name, number, renderPRApprovalCommandComment(command, actor, head)); err != nil { + if err := c.CreateIssueComment(ctx, full, number, renderPRApprovalCommandComment(command, actor, head)); err != nil { return PullRequestApprovalEvent{}, fmt.Errorf("posting %s on %s/%s#%d: %w", command, owner, name, number, err) } } - event := PullRequestApprovalEvent{Repo: owner + "/" + name, Number: number, HeadSHA: head, Actor: actor} + event := PullRequestApprovalEvent{Repo: full, Number: number, HeadSHA: head, Actor: actor} if c.logger != nil { c.logger.Info("pull request approval commands posted by dashboard decision", "repo", event.Repo, "pr", number, "actor", actor, "head", head) } + if opts.HumanChangeRequests != nil && head != "" { + req := review.HumanChangeRequest{ + Repo: full, + Number: number, + HeadSHA: head, + Source: review.HumanChangeRequestSourceDecision, + SourceID: operatorDecisionMarkerID, + Actor: actor, + Body: prDecisionApproveBody, + Kind: review.HumanChangeRequestKindApprove, + } + if err := opts.HumanChangeRequests.Record(req); err != nil { + return event, fmt.Errorf("recording dashboard approval on %s#%d: %w", full, number, err) + } + event.Recorded = true + } + if opts.LiftNeedsHuman && labelPresent(labels, issueNeedsHumanLabel) { + if err := c.RemoveLabel(ctx, full, number, issueNeedsHumanLabel); err != nil { + c.warnOperatorApproval("needs-human not lifted", full, number, head, err) + } else { + event.NeedsHumanLifted = true + } + } + if label := strings.TrimSpace(opts.SentinelLabel); label != "" { + if labelPresent(labels, label) { + if err := c.RemoveLabel(ctx, full, number, label); err != nil { + c.warnOperatorApproval("sentinel label not cleared", full, number, head, err) + } else { + event.SentinelLabelCleared = true + } + } + now := time.Now + if opts.Now != nil { + now = opts.Now + } + event.SentinelAcknowledged = c.RecordReviewEvidenceSentinelAck(full, number, head, actor, now()) + } + if event.Recorded { + event.Stage = c.applyPRDecisionStage(ctx, owner, name, number, head, actor, prDecisionApprove, selfAuthored) + c.logPRDecision(full, number, head, actor, prDecisionApprove, event.Stage, false) + } return event, nil } +// prDecisionApproveBody is the decision text a dashboard approval records, +// the bare form `/hive decision approve` carries. +const prDecisionApproveBody = "approve" + +func (c *Client) warnOperatorApproval(what, repo string, number int, head string, err error) { + if c.logger != nil { + c.logger.Warn("dashboard approval: "+what, "repo", repo, "pr", number, "head", head, "error", err) + } +} + // 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 diff --git a/src/pkg/github/pr_decision_operator_test.go b/src/pkg/github/pr_decision_operator_test.go index 4fa0bbf2f1..d1aa13a8f6 100644 --- a/src/pkg/github/pr_decision_operator_test.go +++ b/src/pkg/github/pr_decision_operator_test.go @@ -5,8 +5,12 @@ import ( "errors" "strings" "testing" + "time" + + gh "github.com/google/go-github/v72/github" "github.com/hivecommons/hive/pkg/review" + "github.com/hivecommons/hive/pkg/sentinel" ) func TestRecordOperatorPullRequestApprovalPostsCommandsOnly(t *testing.T) { @@ -122,3 +126,95 @@ func TestRecordOperatorPullRequestDecisionRefusesForeignEmptyAndUnstored(t *test t.Fatalf("refusals must post nothing, got %v / %v", rec.posted[77], rec.posted[liveDecisionPR]) } } + +// TestRecordOperatorPullRequestApprovalWithReleasesThePark: a person's +// Approve from the dashboard is the human review the row was parked for +// (hivecommons/hive#14821, #14822, crux#30 stayed at stage/085 after the +// owner approved because only the two command comments were written). With +// options it records the head-scoped approval the lanes and the stage engine +// honour, lifts `needs-human`, clears the sentinel label, acknowledges the +// bundle's sentinel findings and submits the approve decision to the stage +// engine — while the bare call stays comments-only for the delegated path. +func TestRecordOperatorPullRequestApprovalWithReleasesThePark(t *testing.T) { + now := time.Date(2026, 10, 28, 12, 50, 0, 0, time.UTC) + flagged := parkedPR(liveDecisionPR, "thatguywob", []string{PRNeedsDecisionStageLabel, issueNeedsHumanLabel, "sentinel-alert", "role/trusted"}) + c, rec := newUnparkPRClient(t, []unparkWireIssue{flagged}, map[string]string{"clubanderson": "admin"}) + root := withEvidenceRoot(t) + c.SetReviewEvidence(func(string) ReviewEvidenceSettings { return ReviewEvidenceSettings{Enabled: true} }) + pr := &gh.PullRequest{Number: gh.Ptr(liveDecisionPR), User: &gh.User{Login: gh.Ptr("thatguywob"), Type: gh.Ptr("User")}, + Base: &gh.PullRequestBranch{SHA: gh.Ptr("base000")}, Head: &gh.PullRequestBranch{SHA: gh.Ptr(liveDecisionHead)}} + c.recordReviewEvidenceSentinel("org/repo", pr, []sentinel.Finding{{Rule: sentinel.RuleSensitivePath, Summary: "workflow timeout 10→45", Paths: []string{".github/workflows/v2-ci.yml"}}}, false, now.Add(-time.Hour)) + store := review.NewHumanChangeRequests("") + + event, err := c.RecordOperatorPullRequestApprovalWith(context.Background(), "org/repo", liveDecisionPR, "clubanderson", PullRequestApprovalOptions{ + HumanChangeRequests: store, LiftNeedsHuman: true, SentinelLabel: "sentinel-alert", Now: func() time.Time { return now }, + }) + if err != nil { + t.Fatalf("approval: %v", err) + } + if !event.Recorded || !event.NeedsHumanLifted || !event.SentinelLabelCleared || !event.SentinelAcknowledged || event.HeadSHA != liveDecisionHead { + t.Fatalf("event = %+v", event) + } + if posted := rec.posted[liveDecisionPR]; len(posted) != len(PRApprovalCommands) { + t.Fatalf("the command comments are still posted, got %v", posted) + } + req, ok := review.DecisionAnswerFor(store, "org/repo", liveDecisionPR, liveDecisionHead) + if !ok || !req.IsApproval() || req.Actor != "clubanderson" || req.Directive() != review.DecisionDirectiveApprove || req.SourceID != operatorDecisionMarkerID { + t.Fatalf("recorded approval = %+v, ok=%v", req, ok) + } + if got := review.HumanApprovalFor(store, "org/repo", liveDecisionPR, liveDecisionHead); got == nil { + t.Fatal("a bare approval must stand against the head for the lanes") + } + removed := strings.Join(rec.removed[liveDecisionPR], ",") + if !strings.Contains(removed, issueNeedsHumanLabel) || !strings.Contains(removed, "sentinel-alert") { + t.Fatalf("needs-human and the sentinel label must be lifted, removed=%v", rec.removed[liveDecisionPR]) + } + if len(rec.added[liveDecisionPR]) != 0 { + t.Fatalf("approval adds no labels, added=%v", rec.added[liveDecisionPR]) + } + b, err := LoadReviewEvidence(ReviewEvidencePath(root, "org/repo", liveDecisionPR, liveDecisionHead)) + if err != nil { + t.Fatalf("bundle: %v", err) + } + if b.SentinelAcknowledgedBy() != "clubanderson" || len(b.Sentinel) != 1 { + t.Fatalf("bundle must carry the acknowledgment and keep the finding: actions=%+v sentinel=%+v", b.HumanActions, b.Sentinel) + } + facts := prDecisionFacts(t, c) + if len(facts) != 1 || facts[0].Head != liveDecisionHead || facts[0].Instruction || facts[0].By != "clubanderson" || facts[0].SelfAuthored { + t.Fatalf("stage engine must see one approve decision on the head, got %+v", facts) + } + + // The same approval twice is idempotent: the record is replaced, no + // label is removed twice, the acknowledgment is not duplicated. + again, err := c.RecordOperatorPullRequestApprovalWith(context.Background(), "org/repo", liveDecisionPR, "clubanderson", PullRequestApprovalOptions{ + HumanChangeRequests: store, LiftNeedsHuman: true, SentinelLabel: "sentinel-alert", Now: func() time.Time { return now.Add(time.Minute) }, + }) + if err != nil { + t.Fatalf("second approval: %v", err) + } + if !again.Recorded || !again.SentinelAcknowledged || again.NeedsHumanLifted || again.SentinelLabelCleared { + t.Fatalf("second event = %+v", again) + } + if b, _ = LoadReviewEvidence(ReviewEvidencePath(root, "org/repo", liveDecisionPR, liveDecisionHead)); len(b.HumanActions) != 1 { + t.Fatalf("acknowledgment duplicated: %+v", b.HumanActions) + } +} + +// TestRecordOperatorPullRequestApprovalWithoutOptionsStaysCommentsOnly pins +// the delegated "Let hive decide" path: it recommends, it does not clear a +// sentinel alert or record a human decision. +func TestRecordOperatorPullRequestApprovalWithoutOptionsStaysCommentsOnly(t *testing.T) { + flagged := parkedPR(liveDecisionPR, "thatguywob", []string{PRNeedsDecisionStageLabel, issueNeedsHumanLabel, "sentinel-alert"}) + c, rec := newUnparkPRClient(t, []unparkWireIssue{flagged}, nil) + + event, err := c.RecordOperatorPullRequestApproval(context.Background(), "org/repo", liveDecisionPR, "maintainer") + if err != nil { + t.Fatalf("approval: %v", err) + } + if event.Recorded || event.NeedsHumanLifted || event.SentinelLabelCleared || event.SentinelAcknowledged || event.Stage != "" { + t.Fatalf("bare approval must release nothing: %+v", event) + } + if len(rec.removed[liveDecisionPR]) != 0 || len(prDecisionFacts(t, c)) != 0 { + t.Fatalf("bare approval touched labels or the stage engine: removed=%v", rec.removed[liveDecisionPR]) + } +} diff --git a/src/pkg/github/review_evidence.go b/src/pkg/github/review_evidence.go index 9e3abc2bb2..5b4574be5c 100644 --- a/src/pkg/github/review_evidence.go +++ b/src/pkg/github/review_evidence.go @@ -129,6 +129,7 @@ type reviewEvidenceUpdate struct { verdicts []evidence.Verdict posted []evidence.PostedReview sentinel []evidence.SentinelFinding + actions []evidence.Action ci *evidence.CI signals review.ConfidenceSignals } @@ -335,6 +336,12 @@ func (c *Client) upsertReviewEvidence(repo string, number int, head string, u re changed = true } } + for _, a := range u.actions { + if !containsEvidenceAction(b.HumanActions, a) { + b.HumanActions = append(b.HumanActions, a) + changed = true + } + } if u.ci != nil && b.Merge == nil && (b.CI.CapturedAt.IsZero() || b.CI.Status != u.ci.Status || !sameEvidenceChecks(b.CI.Checks, u.ci.Checks)) { b.CI = *u.ci @@ -489,6 +496,46 @@ func (c *Client) recordReviewEvidenceSentinel(repo string, pr *gh.PullRequest, f func() *gh.PullRequest { return pr }, now.UTC()) } +// RecordReviewEvidenceSentinelAck records that actor approved head knowing +// the sentinel findings the bundle holds for it (hivecommons/hive: owner +// Approve on a sentinel-flagged PR). Readers that alert on bundle findings +// (the stage tracker's sentinel_alert) read the acknowledgment as the human +// review the alert asked for; the findings themselves stay on record. It +// returns true when an acknowledgment was written or already stood, and +// false when the head has no bundle or no sentinel findings — there is then +// nothing to acknowledge. Like every evidence write, failures are logged and +// swallowed: the approval that prompted it is already on GitHub. +func (c *Client) RecordReviewEvidenceSentinelAck(repo string, number int, head, actor string, now time.Time) bool { + settings, ok := c.reviewEvidenceSettings(repo) + head, actor = strings.TrimSpace(head), strings.TrimSpace(actor) + if !ok || head == "" || actor == "" || number <= 0 { + return false + } + owner, name := c.splitRepo(strings.TrimSpace(repo)) + full := owner + "/" + name + b, err := LoadReviewEvidence(ReviewEvidencePath("", full, number, head)) + if err != nil || b == nil || len(b.Sentinel) == 0 { + return false + } + if b.SentinelAcknowledgedBy() != "" { + return true + } + key, err := evidence.LoadSigningKey(settings.SigningKeyFile) + if err != nil { + c.logger.Warn("review evidence: signing key unusable, writing unsigned", + slog.String("error", err.Error())) + key = nil + } + u := reviewEvidenceUpdate{actions: []evidence.Action{{ + Actor: actor, + Kind: evidence.ActionSentinelAcknowledged, + Detail: "approved from the Hive dashboard with the sentinel findings shown", + At: now.UTC(), + }}} + c.upsertReviewEvidence(full, number, head, u, settings.Policy, key, func() *gh.PullRequest { return nil }, now.UTC()) + return true +} + // evidenceSentinelFinding maps a sentinel finding onto the bundle schema. // Paths are sorted so the same finding re-flagged always compares equal. func evidenceSentinelFinding(f sentinel.Finding) (evidence.SentinelFinding, bool) { diff --git a/src/pkg/github/review_evidence_complete_test.go b/src/pkg/github/review_evidence_complete_test.go index 6f808b1d0b..1551e3603e 100644 --- a/src/pkg/github/review_evidence_complete_test.go +++ b/src/pkg/github/review_evidence_complete_test.go @@ -500,3 +500,71 @@ func TestEvidenceCIVerdict(t *testing.T) { }) } } + +// TestRecordReviewEvidenceSentinelAck: the owner's Approve on a +// sentinel-flagged head records a head-keyed acknowledgment in the bundle +// (hivecommons/crux#30 carried findings but no label, so nothing could clear +// its alert); a head with no bundle or no findings has nothing to +// acknowledge, and a second approval does not duplicate the action. +func TestRecordReviewEvidenceSentinelAck(t *testing.T) { + t0 := time.Date(2026, 10, 28, 12, 0, 0, 0, time.UTC) + findings := []sentinel.Finding{{Rule: sentinel.RuleSensitivePath, Summary: "touches workflows", Paths: []string{".github/workflows/ci.yml"}}} + enabled := &ReviewEvidenceSettings{Enabled: true} + + t.Run("not wired", func(t *testing.T) { + withEvidenceRoot(t) + c := evidenceTestClient(t, &evidencePRFixture{head: "h1"}, nil) + if c.RecordReviewEvidenceSentinelAck("o/r", 7, "h1", "clubanderson", t0) { + t.Fatal("no evidence wiring must acknowledge nothing") + } + }) + t.Run("no bundle", func(t *testing.T) { + root := withEvidenceRoot(t) + c := evidenceTestClient(t, &evidencePRFixture{head: "h1"}, enabled) + if c.RecordReviewEvidenceSentinelAck("o/r", 7, "h1", "clubanderson", t0) { + t.Fatal("a head without a bundle has nothing to acknowledge") + } + if _, err := os.Stat(ReviewEvidencePath(root, "o/r", 7, "h1")); !os.IsNotExist(err) { + t.Fatalf("acknowledging must not start a bundle: %v", err) + } + }) + t.Run("bundle without findings", func(t *testing.T) { + root := withEvidenceRoot(t) + writeTestEvidence(t, root, "h1", "", t0) + c := evidenceTestClient(t, &evidencePRFixture{head: "h1"}, enabled) + if c.RecordReviewEvidenceSentinelAck("o/r", 7, "h1", "clubanderson", t0) { + t.Fatal("a bundle without sentinel findings has nothing to acknowledge") + } + if b := mustLoadBundle(t, root, "h1"); b.SentinelAcknowledgedBy() != "" || len(b.HumanActions) != 0 { + t.Fatalf("actions written without findings: %+v", b.HumanActions) + } + }) + t.Run("acknowledges once", func(t *testing.T) { + root := withEvidenceRoot(t) + c := evidenceTestClient(t, &evidencePRFixture{head: "h1"}, enabled) + c.recordReviewEvidenceSentinel("o/r", evidenceSentinelPR("h1"), findings, false, t0) + if b := mustLoadBundle(t, root, "h1"); b.SentinelAcknowledgedBy() != "" { + t.Fatalf("fresh findings must not read as acknowledged: %+v", b.HumanActions) + } + if !c.RecordReviewEvidenceSentinelAck("o/r", 7, "h1", "clubanderson", t0.Add(time.Hour)) { + t.Fatal("findings on the head must be acknowledgeable") + } + if !c.RecordReviewEvidenceSentinelAck("o/r", 7, "h1", "clubanderson", t0.Add(2*time.Hour)) { + t.Fatal("a standing acknowledgment reports true") + } + b := mustLoadBundle(t, root, "h1") + if got := b.SentinelAcknowledgedBy(); got != "clubanderson" { + t.Fatalf("SentinelAcknowledgedBy = %q, want clubanderson", got) + } + if len(b.HumanActions) != 1 || b.HumanActions[0].Kind != evidence.ActionSentinelAcknowledged || !b.HumanActions[0].At.Equal(t0.Add(time.Hour)) { + t.Fatalf("one acknowledgment expected, got %+v", b.HumanActions) + } + if len(b.Sentinel) != 1 { + t.Fatalf("findings must stay on record, got %+v", b.Sentinel) + } + // A new head carries no acknowledgment. + if c.RecordReviewEvidenceSentinelAck("o/r", 7, "h2", "clubanderson", t0) { + t.Fatal("another head has no bundle to acknowledge") + } + }) +}