diff --git a/changelog.d/added-adopt-now-reroute.md b/changelog.d/added-adopt-now-reroute.md new file mode 100644 index 0000000000..522a056976 --- /dev/null +++ b/changelog.d/added-adopt-now-reroute.md @@ -0,0 +1 @@ +- Activity Monitor: a PR waiting on a contributor's clanker (stage 072/071) now offers **Adopt now — hive takes it over** (decision API `adopt` + `force: true`: forced supersede adoption bypassing presence, grace and `maintainer_policy`, marker `hive:adopted reason=operator-forced by=@login`) and **Reroute to another clanker** (decision API `reroute` + `to`: the follow-up work is dispatched to an online clanker's fix queue as a `fix-pr` interrupt, `hive:rerouted` note, `rerouted → @X` pill; falls back to Adopt now after `governor.reroute.pickup_timeout`, default 30m), in the row menu, the Needs-human popover and the delegated "Let hive decide" rules (hivecommons/hive#15038). diff --git a/src/cmd/hive/forgestate_wire.go b/src/cmd/hive/forgestate_wire.go index 8744c4a4aa..057388247b 100644 --- a/src/cmd/hive/forgestate_wire.go +++ b/src/cmd/hive/forgestate_wire.go @@ -2,6 +2,7 @@ package main import ( "context" + "fmt" "log/slog" "github.com/hivecommons/hive/pkg/forgestate" @@ -47,6 +48,22 @@ func (b *boot) webhookDeliveryFunc() func(event, deliveryID string, payload []by } } +// sweepNudgeFunc is the dashboard.Dependencies.SweepNudge hook: schedule +// an automerge pass for one PR. The trigger is resolved per call because +// it is wired before the App client exists; without the forgestate cache +// the governor loop is woken instead, whose eval cycle runs the lanes. +func (b *boot) sweepNudgeFunc() func(repo string, number int) { + return func(repo string, number int) { + if trigger := b.sweepTrigger; trigger != nil { + trigger.NotifyPullRequests(repo, number) + return + } + if wake := b.webhookWakeFunc(); wake != nil { + wake(fmt.Sprintf("operator-action %s#%d", repo, number)) + } + } +} + // automergeTriggerEvents are the deliveries that can change whether a PR is // mergeable: its checks, commit statuses, reviews and the PR itself. var automergeTriggerEvents = map[string]bool{ diff --git a/src/cmd/hive/main.go b/src/cmd/hive/main.go index efa2bcb315..7b68daacce 100644 --- a/src/cmd/hive/main.go +++ b/src/cmd/hive/main.go @@ -1475,6 +1475,7 @@ func (b *boot) wireBootClosures() { ReviewerAutoscaleStatus: func() autoscale.Status { return reviewerAutoscaler.Status() }, ReviewEvents: b.reviewEvents, WebhookWake: b.webhookWakeFunc(), + SweepNudge: b.sweepNudgeFunc(), ApplyWebhookItems: b.applyWebhookItemsFunc(), WebhookDelivery: b.webhookDeliveryFunc(), EvalLoop: b.evalLoopStatusFunc(), diff --git a/src/docs/api-reference.md b/src/docs/api-reference.md index 8384d1ffda..f60d744b9f 100644 --- a/src/docs/api-reference.md +++ b/src/docs/api-reference.md @@ -13,17 +13,17 @@ History point limits, timestamp cutoffs, incremental cost reads and ETag/304 beh | `GET` | `/api/version` | Dashboard auth/session | Build/version metadata; includes `upgradeMarker` (`target`, `current`, `attempts`, `maxAttempts`, `failed`, `requestedAt`, `lastError`) while a self-upgrade is in flight or has failed ([#6765](https://github.com/hivecommons/hive/issues/6765)), the hub-delivered `upgradePolicy` (`hub_managed`, `spoke_managed`, `schedule`, `schedule_hour`, `schedule_timezone`, `schedule_weekday`, `paused`, `branch`, `channel`, `target_sha`, `target_resolved`, `armed_target`, and `next_update_at` — the hub's RFC3339 ETA for the next promotion into the `stable` channel, omitted when unknown ([#10256](https://github.com/hivecommons/hive/issues/10256))) when available, and an `autoUpdate` object (`enabled`, `state` — one of `disabled`/`up_to_date`/`behind`/`retrying`/`failed`/`unknown` — `healthy`, `period`, `targetBranch`, `targetCommit`, `currentCommit`, `commitsBehind`, `lastAttemptAt`, `lastError`, `detail`, and `nextUpdateAt` — the hub's RFC3339 ETA for the next update, omitted when unknown, disabled or paused ([#10257](https://github.com/hivecommons/hive/issues/10257))) that never reports a failed or unknown update as healthy ([#6962](https://github.com/hivecommons/hive/issues/6962), [#6963](https://github.com/hivecommons/hive/issues/6963)) | `pkg/dashboard/api.go:43` | | `GET` | `/api/version/release-notes` | Dashboard auth/session | Changelog gap between two revisions: `?from=&to=` returns `{from:{sha,version?}, to:{sha,ref,version?}, sections:[{version,date,categories:{added,changed,fixed,security,deprecated}}], unreleased?, truncated, source, error?}` — the `CHANGELOG.md` release sections present at `to` and absent at `from`, newest first, plus (when `to` is not a release tag) the `changelog.d/` fragments new at `to` under an `Unreleased (in this build)` section. Fetch failures return `source: "unavailable"` with `error` rather than an error status; results are cached per (from, to) for an hour ([#11065](https://github.com/hivecommons/hive/issues/11065)) | `pkg/dashboard/api.go:44` | | `POST` | `/api/release-channel` | Owner only | Hosted spoke self-service release-channel selector; relays `stable`/`candidate`/`edge` to the hub's existing switch-branch endpoint with the spoke dashboard-token proof, and reports the requested channel as pending until the Deployment image lands | `pkg/dashboard/api.go:65` | -| `GET` | `/api/health` | Public | Basic health probe | `pkg/dashboard/server.go:1557` | -| `GET` | `/api/health/deep` | Public | Deep health probe | `pkg/dashboard/server.go:1558` | -| `GET` | `/api/livez` | Public | Kubernetes liveness probe | `pkg/dashboard/server.go:1559` | -| `GET` | `/metrics` | Registered only when `HIVE_METRICS_ENABLED`; requires `Authorization: ****** (403 if the token is unset) | Prometheus metrics | `pkg/dashboard/server.go:1565` | -| `GET` | `/api/status` | Dashboard auth/session | Dashboard aggregate status; `labelPresets[]` (`{key,label,description,labels[],states[]}`) lists the built-in label-filter presets for the Projects cards, led by `needs-human` whose `labels[]` are the effective hard-suppress labels plus `needs-signal`, the hold labels, `stage/071-needs-author` and the reporter-trust awaiting label (#12172); accepts `?fields=a,b` for top-level selection and `?omit=repos` to drop heavy sections, and honors `Accept-Encoding: gzip`; `agents[]` includes busy-pane visibility fields (`kicksUndeliverable`, `busySince`, `lastTranscriptActivity`, `condition`, `conditionMessage`) when a Working pane cannot accept kicks; a working agent also carries `agents[].run` — the live per-run line (#14576): `{since, elapsedS, costUSD, tokens, priced, tests, filesChanged}`, the estimated spend/tokens since the kick was delivered (`lastKickAt`, falling back to `busySince`) (delta of the token collector's per-agent cumulative figure; `priced:false` when the agent has none yet), the last visible test-runner result (`pass`/`fail`/empty) and the last `N files changed` git summary (`-1` when none) parsed from the captured pane; top-level `fleetRun` `{running, hourUSD, hourPriced}` is the governor strip's `running N · $X this hour` figure; `sla` (fleet) and `repos[].sla` (per repo) carry the Delivery SLA block derived from the lifecycle timeline with no extra GitHub calls: `windows.{7d,30d}.{open_to_triage,triage_to_start,start_to_pr,pr_to_merge,open_to_merge}` as `{p50_h,p95_h,n}` (hours, nearest-rank), `history[]` of up to 30 daily buckets `{day,start_to_pr_p50,pr_to_merge_p50,open_to_merge_p50,n_started,n_pr,n_merged}` persisted under `/data/sla-history.json`, `stale_in_progress[]` (`{number,repo,started_at,age_h,agent}` — issues carrying `hive/in-progress` longer than the agent claim TTL with no linked PR), `stale_count`, `merged_7d`, `claim_ttl_s` and, on the fleet block, the effective `targets` (`start_to_pr_h`, `pr_to_merge_h`, `open_to_merge_h`); `staleSince` and `repos[].countsStale` / `countsStaleSince` mark totals served from last-good figures — the previous enumeration (#13382) or the ForgeState cache's last-good counts (#13376) | `pkg/dashboard/server.go:1570` | -| `GET` | `/api/status/summary` | Dashboard auth/session | Compact agent/governor/budget status summary for pollers; honors `Accept-Encoding: gzip` | `pkg/dashboard/server.go:1571` | -| `GET` | `/api/overview/issues.csv` | Dashboard auth/session | Cached Overview issue-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1572` | -| `GET` | `/api/overview/issues.json` | Dashboard auth/session | Cached Overview issue-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1573` | -| `GET` | `/api/overview/prs.csv` | Dashboard auth/session | Cached Overview PR-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1574` | -| `GET` | `/api/overview/prs.json` | Dashboard auth/session | Cached Overview PR-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1575` | -| `GET` | `/api/events` | Dashboard auth/session | Server-sent event stream | `pkg/dashboard/server.go:1576` | +| `GET` | `/api/health` | Public | Basic health probe | `pkg/dashboard/server.go:1565` | +| `GET` | `/api/health/deep` | Public | Deep health probe | `pkg/dashboard/server.go:1566` | +| `GET` | `/api/livez` | Public | Kubernetes liveness probe | `pkg/dashboard/server.go:1567` | +| `GET` | `/metrics` | Registered only when `HIVE_METRICS_ENABLED`; requires `Authorization: ****** (403 if the token is unset) | Prometheus metrics | `pkg/dashboard/server.go:1573` | +| `GET` | `/api/status` | Dashboard auth/session | Dashboard aggregate status; `labelPresets[]` (`{key,label,description,labels[],states[]}`) lists the built-in label-filter presets for the Projects cards, led by `needs-human` whose `labels[]` are the effective hard-suppress labels plus `needs-signal`, the hold labels, `stage/071-needs-author` and the reporter-trust awaiting label (#12172); accepts `?fields=a,b` for top-level selection and `?omit=repos` to drop heavy sections, and honors `Accept-Encoding: gzip`; `agents[]` includes busy-pane visibility fields (`kicksUndeliverable`, `busySince`, `lastTranscriptActivity`, `condition`, `conditionMessage`) when a Working pane cannot accept kicks; a working agent also carries `agents[].run` — the live per-run line (#14576): `{since, elapsedS, costUSD, tokens, priced, tests, filesChanged}`, the estimated spend/tokens since the kick was delivered (`lastKickAt`, falling back to `busySince`) (delta of the token collector's per-agent cumulative figure; `priced:false` when the agent has none yet), the last visible test-runner result (`pass`/`fail`/empty) and the last `N files changed` git summary (`-1` when none) parsed from the captured pane; top-level `fleetRun` `{running, hourUSD, hourPriced}` is the governor strip's `running N · $X this hour` figure; `sla` (fleet) and `repos[].sla` (per repo) carry the Delivery SLA block derived from the lifecycle timeline with no extra GitHub calls: `windows.{7d,30d}.{open_to_triage,triage_to_start,start_to_pr,pr_to_merge,open_to_merge}` as `{p50_h,p95_h,n}` (hours, nearest-rank), `history[]` of up to 30 daily buckets `{day,start_to_pr_p50,pr_to_merge_p50,open_to_merge_p50,n_started,n_pr,n_merged}` persisted under `/data/sla-history.json`, `stale_in_progress[]` (`{number,repo,started_at,age_h,agent}` — issues carrying `hive/in-progress` longer than the agent claim TTL with no linked PR), `stale_count`, `merged_7d`, `claim_ttl_s` and, on the fleet block, the effective `targets` (`start_to_pr_h`, `pr_to_merge_h`, `open_to_merge_h`); `staleSince` and `repos[].countsStale` / `countsStaleSince` mark totals served from last-good figures — the previous enumeration (#13382) or the ForgeState cache's last-good counts (#13376) | `pkg/dashboard/server.go:1578` | +| `GET` | `/api/status/summary` | Dashboard auth/session | Compact agent/governor/budget status summary for pollers; honors `Accept-Encoding: gzip` | `pkg/dashboard/server.go:1579` | +| `GET` | `/api/overview/issues.csv` | Dashboard auth/session | Cached Overview issue-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1580` | +| `GET` | `/api/overview/issues.json` | Dashboard auth/session | Cached Overview issue-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1581` | +| `GET` | `/api/overview/prs.csv` | Dashboard auth/session | Cached Overview PR-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1582` | +| `GET` | `/api/overview/prs.json` | Dashboard auth/session | Cached Overview PR-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1583` | +| `GET` | `/api/events` | Dashboard auth/session | Server-sent event stream | `pkg/dashboard/server.go:1584` | | `GET` | `/api/swarm` | Dashboard auth/session | Current swarm status: display name, duration, active repo, expiry, persisted prep metrics when available, and idle-unlock fields. | `pkg/dashboard/swarm.go:310` | | `POST` | `/api/swarm` | Owner only | Start a 24h repo swarm for a configured repo, returning 409 when another swarm is active and 423 when a previous swarm keeps the next swarm locked until enough agents are idle unless body `{"repo":"owner/name","force":true}` is used; saves the active record before repo prep, persists prep metrics, and announces the start to Discord when configured. | `pkg/dashboard/swarm.go:311` | | `DELETE` | `/api/swarm` | Owner only | End the active swarm, score issues closed and PRs merged in the window, append it to history, and announce the result to Discord when configured. | `pkg/dashboard/swarm.go:312` | @@ -66,7 +66,7 @@ History point limits, timestamp cutoffs, incremental cost reads and ETag/304 beh | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| | `GET` | `/api/style` | Public | Sanitized custom dashboard CSS | `pkg/dashboard/api.go:45` | -| `GET` | `/branding/custom.css` | Dashboard auth/session | Operator branding stylesheet override, read per request (see [branding](branding.md)) | `pkg/dashboard/server.go:1637` | +| `GET` | `/branding/custom.css` | Dashboard auth/session | Operator branding stylesheet override, read per request (see [branding](branding.md)) | `pkg/dashboard/server.go:1645` | | `GET` | `/api/snapshot/frame-ancestors` | Public | Snapshot framing allowlist | `pkg/dashboard/api.go:78` | | `GET` | `/api/snapshot` | Public | Snapshot data | `pkg/dashboard/api.go:79` | | `GET` | `/snapshot` | Public | Public read-only snapshot page | `pkg/dashboard/api.go:80` | @@ -94,9 +94,9 @@ History point limits, timestamp cutoffs, incremental cost reads and ETag/304 beh | `GET` | `/api/openrouter/models` | Dashboard auth/session | Open Router Models | `pkg/dashboard/openrouter.go:47` | | `GET` | `/api/openrouter/credit` | Dashboard auth/session | Open Router Credit | `pkg/dashboard/openrouter.go:48` | | `GET` | `/openrouter/callback` | Public | Open Router Callback | `pkg/dashboard/openrouter.go:49` | -| `POST` | `/api/github-app/recheck` | Dashboard auth/session | GitHub App Recheck | `pkg/dashboard/server.go:1577` | -| `POST` | `/api/github-app/install-clicked` | Dashboard auth/session | GitHub App Install Clicked | `pkg/dashboard/server.go:1578` | -| `GET` | `/gh-setup` | Public | GitHub App Setup Callback | `pkg/dashboard/server.go:1579` | +| `POST` | `/api/github-app/recheck` | Dashboard auth/session | GitHub App Recheck | `pkg/dashboard/server.go:1585` | +| `POST` | `/api/github-app/install-clicked` | Dashboard auth/session | GitHub App Install Clicked | `pkg/dashboard/server.go:1586` | +| `GET` | `/gh-setup` | Public | GitHub App Setup Callback | `pkg/dashboard/server.go:1587` | ## Configuration @@ -595,7 +595,7 @@ always resolved server-side from the validated token. | `POST` | `/api/hives/{id}/heartbeat` | Dashboard auth/session | Hives Heartbeat | `pkg/dashboard/api_contribute.go:275` | | `DELETE` | `/api/hives/{id}` | Owner only | Hives Delete | `pkg/dashboard/api_contribute.go:276` | | `POST` | `/api/hives/onboard` | Dashboard auth/session | Hives Onboard | `pkg/dashboard/api_contribute.go:277` | -| `GET` | `/sso` | Public | SSO | `pkg/dashboard/server.go:1584` | +| `GET` | `/sso` | Public | SSO | `pkg/dashboard/server.go:1592` | ## Hub SaaS diff --git a/src/docs/dashboard-sections.md b/src/docs/dashboard-sections.md index 9d27087d46..b5a48a94b2 100644 --- a/src/docs/dashboard-sections.md +++ b/src/docs/dashboard-sections.md @@ -688,6 +688,8 @@ Fed by `GET /api/stage-tracker`. Every issue and pull request follows the same p **Presence indicator on the waiting-on pill.** Every PR row that waits on a named person — `stage/071-needs-author`, `stage/072-returned-to-contributor` (before and after the nudge), `stage/017-possibly-existing` on a PR — carries `presence{login, state: online|offline|unknown, kind: clanker|human, since, last_seen, next: wait|adopt, adopt_at}`, read from the contributor hub's live presence (registered profile + relay heartbeat: the same lookup adoption consults, so the indicator and the adoption text never disagree) and projected through adoption's own clock ([hivecommons/hive#15051](https://github.com/hivecommons/hive/issues/15051)). The pill draws it just before the `@login`: a filled **dot** (`--cue-decision`, a soft breathe; none under `prefers-reduced-motion`) when the person's clanker — their connected contributor agent — is online, tooltip "@Danathar's clanker: online, last seen 2 min ago — hive is waiting for them"; a filled **square** (`--status-error`) when it is offline, "@hanthor's clanker: offline 26h — hive will adopt at 15:10 (in 38m)" (or "— hive is waiting for them" when `ask`/`never`/adoption-off holds the clock); a **hollow ring** when no clanker is registered here, "@zoe: no clanker registered — waiting for a human reply" with the pill reading `waiting on @zoe (human · no clanker)`. Shape, not colour alone, carries the state; the indicator has its own `aria-label` ("@hanthor: clanker offline — hive will adopt at …"). A row with presence but no adoption line (071, a 072 not yet nudged, a human's PR) gets a muted `waiting on @login` pill carrying the indicator; a nudged 072 row keeps its single amber adoption pill with the indicator inside it. The Needs-human popover shows the same line under the question when the waiting person is named, a per-PR sub-row under an issue mirrors it, and the row tooltip adds a `Presence:` line. It refreshes with the tracker like every other pill. +**Adopt now / Reroute (072, 071).** Every `author/clanker` pull request waiting on its author's hive — `stage/072-returned-to-contributor` or `stage/071-needs-author`, not yet adopted — also carries `takeover{author, author_online, adopt_now, adopt_now_reason, reroute, reroute_reason, clankers[], rerouted, forced_by, forced_at, fallback_at, grace_elapsed}`, and the ⋯ row menu (and the nested per-PR row under an issue) gains two operator actions beyond Hold / Re-evaluate / Mark needs-human / Open / Copy ([hivecommons/hive#15038](https://github.com/hivecommons/hive/pull/15038): "Returned to contributor · waiting on @Danathar" offered nothing to end the wait). **Adopt now — hive takes it over** (`decide:adopt-now`) carries the consequence line *closes the contributor's PR after hive opens its copy; their commits + sign-off are preserved* under the label, asks an in-app confirm (don't-ask-again supported, keyed `hive.tracker.confirm.decide:adopt-now`; the confirm adds "its hive is online right now" when it is) and POSTs `{"decision":"adopt","force":true}`: the hive posts an attributed `` note, sets `adoption/supersede`, marks the stage record forced and nudges the sweep, which runs the existing supersede adoption at once — presence, the grace windows and `maintainer_policy` are all bypassed (`hold` still stops it; the menu says *release the hold first*). The persistent result toast reads `Adopted → #N (hive's copy), contributor PR will close when #N merges` when the sweep lands inside the handler's wait, else `Adoption forced: hive opens its copy on the pass now running`; the audit entry is `repo_item_decision_adopt_now` with `action=adopt-now`. **Reroute to another clanker** (`decide:reroute`) opens a submenu of the currently-online registered contributor clankers from the contributor fleet (`@login · hive · online 12m ago · 1 in hand` / `idle`, via `clankers[]` — the same facts as `/api/contribute/fleet`) plus *any available (N online)*; in the Needs-human popover it is a required choice list. The pick (after a confirm keyed `hive.tracker.confirm.decide:reroute`) POSTs `{"decision":"reroute","to":"|any"}`: the hive enqueues the PR's follow-up work (the stage record's return reason — the failing check or the reviewer's requested changes — plus the operator's comment) on the target's contributor fix queue and dispatches it as a `fix-pr` `task_assign` interrupt, the same path the 072 nudge takes to the author's own relay; the task's instruction says whose PR it is and that the target either pushes the fix (if the branch allows) or opens a replacement PR carrying the author's commits and sign-off. The author is told by ``, the row shows a `rerouted → @X` pill with a presence dot (green while the target's relay is on the hub), and the toast reads `Rerouted → @X (dispatched now, preempt)` / `(queued; N ahead)`. If the target's relay has not taken the task within `governor.reroute.pickup_timeout` (default 30m) the hive falls back to Adopt now by itself: the queued item is withdrawn, the record marks the forced adoption, a `lapsed=true` note goes on the PR, a warning system alert and a `repo_item_reroute_fallback` audit entry are raised, and the sweep is nudged. With no clanker online the item is disabled with the reason *no clankers online — use Adopt now*. Both actions appear in the Needs-human popover's options when the blocker is a waiting-on-contributor condition — once the nudge grace has elapsed and the engine is not adopting on its own, the row carries `decision_needed` (`blocker_reason: adoption:`, options Adopt now, Reroute, Hold) — and **Let hive decide** picks Adopt now (`grace-elapsed-adopt-now`) when the grace has already run out. Write access required. + **Blocked pill.** An issue wearing `blocked` because the hive parked it on a pull request — its body carries `` (the review backlog's spin-off issues, `hive-open-issue comment --blocked-on-pr`) — names that PR: the payload carries `blocked_on_pr: {repo, number, url, state}`, the pill reads `blocked on #N` and links to the PR, its tooltip says `Blocked on PR owner/repo#N (open) — lifts when it merges; re-triage if closed unmerged`, the caption reads `Blocked on PR #N — lifts when it merges` instead of `No stage recorded yet`, and the row's title and chevron tooltip carry the blocker too ([#14952](https://github.com/hivecommons/hive/issues/14952): #14863 showed a bare grey pill and "blocked · since 7h" with nothing to say what it waited on). The state (`open`, `merged`, `closed`, or absent when nothing knows) comes only from what the hive already holds — the status snapshot's open PRs, the ForgeState cache, the recent-merge ring — never a GitHub call from the tracker build; a merged or closed-unmerged blocker says so (`merged; the blocked sweep lifts the label next` / `closed unmerged; the blocked sweep re-triages it next`). The server reads the marker from the issue body when it has one, else from the enumeration's `blocked on owner/repo#N` reason, so sidelined rows (which carry only the reason) name it too. A `blocked` issue with neither (a human-applied label) keeps the bare pill. This is distinct from `blocked_on`, the open GitHub "blocked by" dependencies of a sequenced sub-issue ([#14765](https://github.com/hivecommons/hive/issues/14765)); when a row has both, the chevron tooltip lists them together. **New row (`000-new`, the pre-stage state).** Every open issue and pull request in `project.repos` is on the list from the moment GitHub reports it — there is no gap between "opened" and "the hive has an opinion about it" ([#15094](https://github.com/hivecommons/hive/issues/15094)). The `issues.opened` / `pull_request.opened` webhook re-read inserts the item into the status payload straight away (`insertFrontendRepoItem`; the governor side keeps the same row in its cached snapshot so a republish does not drop it), the per-item replay re-applies that insert after a governor republish, and the enumeration poll is the fallback for a missed delivery. Until something places the item — a stage record, a `stage/*` label, a hold, a blocked marker, a bucket other than *reporter triage* / *unclassified* — the row is anchored in the **Open** column with the lit chevron reading **New** (`ham-open-new`, blue ✦ rather than amber) and a caption that names who moves it next and when: `New · waiting for the stage-label pass (→ 010 actionable), then the scanner (next pass in 7m)` for an issue the reporter gate has already admitted, `New · waiting for a maintainer's triage (add `triage/accepted`); the hive's next pass in 7m` for a human contributor's issue the reporter-trust gate is still holding (the label names come from `issues.filter.reporter_trust.untrusted_require_labels`), and `New · waiting for the stage-label pass (→ 050 review pending)` for a pull request. The *since* time is the item's `created_at`; "next pass" is the governor's next kick (`governor.nextKickAt`, so it counts down with the Governor tile and reads *due now* once it has passed). The payload carries it all as `new{since, next_mover (maintainer|hive), next_mover_text, next_pass_at, next_pass_in_seconds, gates[], text}`; the chevron tooltip lists the gates ahead — **triage** (the reporter gate: done when admitted, next when a triage label is still needed), **actionable** (the stage-label pass marks it 010), **claimed** (the scanner claims it, 020) — each marked ✓ done, → next or · later, and the row's actor icon reads *human* while the next mover is a maintainer and *hive* otherwise. A row that already wears a hold, `blocked`, a draft marker or any stage record is never *New*; neither is an issue at `015` once the stage-label pass has written it. diff --git a/src/docs/labels-and-control-signals.md b/src/docs/labels-and-control-signals.md index d8e2908c50..71946a6cbd 100644 --- a/src/docs/labels-and-control-signals.md +++ b/src/docs/labels-and-control-signals.md @@ -941,6 +941,24 @@ When a clanker-authored contributor PR goes red the hive does not just relabel i unregistered clock). A held adoption (`ask` / `never`, or `adoption.enabled: false`) keeps `next: wait` with no `adopt_at`, so the indicator never promises an adoption the pill text denies. + An operator can end the wait early from the activity monitor + row (hivecommons/hive#15038): **Adopt now** (decision API `adopt` with + `force: true`) posts ``, sets `adoption/supersede` and marks the stage record + forced, so the next sweep adopts at once in supersede mode whatever the + author's presence, the grace windows or `maintainer_policy` say (`hold` + still blocks it); the marker that follows reads `reason=operator-forced + by=@` and, when the author's hive is online, the adoption comment + says the maintainer took it over. **Reroute** (decision API `reroute` + with `to: |any`) hands the follow-up work to another online + clanker's fix queue and posts `` on the PR; if that relay has not picked the task up within + `governor.reroute.pickup_timeout` (default 30m) the hive posts + `` and falls back to + Adopt now on its own. + - `reason=operator-forced by=@` — an operator's Adopt now (or the + reroute pickup fallback acting for them); presence, grace and + `maintainer_policy` were not consulted; - `reason=contributor-offline` — the author has a contributor profile here and no relay heartbeat within `governor.labels.stage.presence_window`: adopted `governor.labels.stage.adoption.after_offline` (default 15m) diff --git a/src/docs/operator-reference.md b/src/docs/operator-reference.md index 1e8eba4cd9..281dfbc57a 100644 --- a/src/docs/operator-reference.md +++ b/src/docs/operator-reference.md @@ -726,7 +726,22 @@ hive's to stand in for when that hive disconnects, maintainer or not). `never` keeps the earlier hands-off rule and releases any existing adoption of a maintainer's head. Human-authored PRs stay unadopted under all three. Dashboard: Settings → Labels → "When the PR author maintains the -repository". When the +repository". Whatever the policy and the clocks say, the row's ⋯ menu on a +072 / 071 clanker PR offers the operator **Adopt now — hive takes it over** +(decision API `adopt` + `force: true`: supersede adoption on the next nudged +sweep, bypassing presence, grace and `maintainer_policy`; `hold` still +stops it; marker `hive:adopted reason=operator-forced by=@login`) and +**Reroute to another clanker** (decision API `reroute` + `to: |any`: +the follow-up work goes to an online contributor clanker's fix queue as a +`fix-pr` interrupt — the same mechanism as the 072 nudge — with a +`hive:rerouted` note on the PR). A rerouted task the target relay has not +taken within `governor.reroute.pickup_timeout` (default `30m`) falls back to +Adopt now by itself, with a system alert and a `repo_item_reroute_fallback` +audit entry; with no clanker online the Reroute item is disabled ("no +clankers online — use Adopt now"). Both are also options in the +Needs-human popover once the nudge grace has elapsed, and "Let hive decide" +picks Adopt now then (hivecommons/hive#15038; +[dashboard-sections.md](dashboard-sections.md#hive-activity-monitor)). When the PR allows maintainer edits (`adoption.in_place`, default on) the hive adopts it in place: `stage/074-adopted-by-hive`, the PR's own branch filed in `ci-failing.json` as the hive's (`adopted: true`) for the scanner's red-PR diff --git a/src/pkg/config/config.go b/src/pkg/config/config.go index b5601d0a03..bbdee6b36f 100644 --- a/src/pkg/config/config.go +++ b/src/pkg/config/config.go @@ -1586,6 +1586,10 @@ type GovernorConfig struct { // (governor) config surface rather than only through HIVE_BACKUP_KEY. Backup BackupConfig `yaml:"backup,omitempty" json:"backup,omitempty"` Replan ReplanConfig `yaml:"replan"` + // Reroute is governor.reroute: the operator's "Reroute to another + // clanker" row action (re-dispatching a returned PR's follow-up work to + // another online contributor clanker). + Reroute RerouteConfig `yaml:"reroute,omitempty" json:"reroute,omitempty"` // AttributionTrailer controls the VISIBLE invocation-attribution line // ("— hive: agent=… backend=… model=…") appended at creation time to the // body of PRs the hive opens for agents (the PR-request watcher) and issues @@ -2916,6 +2920,22 @@ func (c StageAdoptionConfig) EffectiveAfterUnregistered() time.Duration { return parseDurationOr(c.AfterUnregistered, DefaultAdoptAfterUnregistered) } +// RerouteConfig is governor.reroute. +type RerouteConfig struct { + // PickupTimeout is how long a rerouted PR's work may sit in the target + // clanker's queue before the hive gives up on the reroute and falls + // back to Adopt now (default 30m). Go duration syntax ("30m", "1h"). + PickupTimeout string `yaml:"pickup_timeout,omitempty" json:"pickup_timeout,omitempty"` +} + +// DefaultReroutePickupTimeout is governor.reroute.pickup_timeout's default. +const DefaultReroutePickupTimeout = 30 * time.Minute + +// EffectivePickupTimeout parses PickupTimeout (default 30m). +func (c RerouteConfig) EffectivePickupTimeout() time.Duration { + return parseDurationOr(c.PickupTimeout, DefaultReroutePickupTimeout) +} + // Default graces before a red contributor PR is adopted (stage 074). const ( DefaultContributorGraceOnline = 2 * time.Hour diff --git a/src/pkg/config/testdata/agent_runtime_golden.json b/src/pkg/config/testdata/agent_runtime_golden.json index fafe0fe21b..32914d3a0b 100644 --- a/src/pkg/config/testdata/agent_runtime_golden.json +++ b/src/pkg/config/testdata/agent_runtime_golden.json @@ -383,6 +383,7 @@ "StallThresholdS": 0, "MaxReplans": 0 }, + "reroute": {}, "AttributionTrailer": null, "first_timer_welcome": {}, "advisory": { diff --git a/src/pkg/dashboard/api_repo_item_decide_delegated.go b/src/pkg/dashboard/api_repo_item_decide_delegated.go index 8e533da4d4..96b78f59cc 100644 --- a/src/pkg/dashboard/api_repo_item_decide_delegated.go +++ b/src/pkg/dashboard/api_repo_item_decide_delegated.go @@ -634,11 +634,24 @@ func (s *Server) gatherDelegatedInput(ctx context.Context, repoFull string, numb in.SentinelReason = strings.TrimSpace(req.SentinelReason) lowerReason := strings.ToLower(reason) in.AdoptionStalled = strings.HasPrefix(lowerReason, stagelabels.LaneReasonAdoptionStalledPrefix) + if in.Kind == delegatedecision.KindPR && !in.HiveAuthored { + in.AdoptionGraceElapsed = s.delegatedAdoptionGraceElapsed(repoFull, number) + } in.ReporterTrustHold = strings.Contains(lowerReason, "reporter-trust") || strings.Contains(lowerReason, "reporter trust") in.DCOMissing = strings.Contains(lowerReason, "dco") return in, nil } +// delegatedAdoptionGraceElapsed reads the stage store: adoption at the PR's +// nudged head came due and the engine held it (hivecommons/hive#15038). +func (s *Server) delegatedAdoptionGraceElapsed(repoFull string, number int) bool { + rec, ok := s.stageStoreOrShared().Get(stagelabels.Key(repoFull, number)) + if !ok || rec.NudgeHead == "" { + return false + } + return rec.AdoptionBlocked(rec.NudgeHead) != "" +} + // delegatedHeadCIGreen decides Input.CIGreen for the PR under decision. // mergeable_state alone cannot carry it: GitHub reports "blocked" both for a // missing required review and for red required checks, and "unknown" / @@ -790,6 +803,21 @@ func (s *Server) executeDelegatedDecision(ctx context.Context, in delegatedecisi if err := client.AddLabels(ctx, repoFull, number, []string{delegatedecision.LabelAdoptSupersede}); err != nil { return notes, fmt.Errorf("queuing supersede adoption: %w", err) } + if d.Rule == delegatedecision.RuleAdoptNow { + // Grace already elapsed: run it as Adopt now — the forced + // mark bypasses presence and maintainer_policy and the + // sweep is nudged (api_repo_item_decision_reroute.go). + store := s.stageStoreOrShared() + key := stagelabels.Key(repoFull, number) + ensureStageRecord(store, key) + store.NoteAdoptionForced(key, user, time.Now()) + if superseding := s.nudgeSweepAndAwaitAdoption(ctx, store, key, repoFull, number); superseding > 0 { + notes = append(notes, fmt.Sprintf("adopted now → #%d (hive's copy)", superseding)) + } else { + notes = append(notes, "adoption forced (adopt-now): the hive opens its copy on the pass now running") + } + break + } notes = append(notes, "supersede adoption queued for the adoption engine's next pass") case delegatedecision.ActionRecommendOnly: if err := client.CreateIssueComment(ctx, repoFull, number, comment); err != nil { diff --git a/src/pkg/dashboard/api_repo_item_decision.go b/src/pkg/dashboard/api_repo_item_decision.go index 4d25aad032..36533506cd 100644 --- a/src/pkg/dashboard/api_repo_item_decision.go +++ b/src/pkg/dashboard/api_repo_item_decision.go @@ -108,6 +108,12 @@ type repoItemDecisionRequest struct { // SupersededBy names the pull request that replaces a close-superseded // item: "458", "#458", "owner/repo#458" or a GitHub URL. Optional. SupersededBy string `json:"superseded_by"` + // Force with decision "adopt" is the operator's Adopt now: adopt at + // once, bypassing the author's presence, the grace window and + // maintainer_policy (api_repo_item_decision_reroute.go). + Force bool `json:"force,omitempty"` + // To with decision "reroute" is the target clanker's login, or "any". + To string `json:"to,omitempty"` } // parseRepoItemSupersededBy resolves a "superseded by" reference the way an @@ -399,6 +405,12 @@ func (s *Server) handleRepoItemDecision(w http.ResponseWriter, r *http.Request) s.audit.LogRecord(user, auditRepoItemDecisionClose, auditDetail("repo", repoFull, "number", numStr, "type", itemType, "reason", verb, "superseded_by", supersededBy), "", repoFull, number) jsonResponse(w, repoItemDecisionResponse{OK: true, Repo: repoFull, Number: number, Decision: decision, Status: "closed", Label: label, Result: repoItemDecisionResult(repoFull, number, itemType, decision, comment, supersededBy, label, nil)}) + case repoItemDecisionReroute: + if itemType != "pr" { + jsonError(w, "reroute applies to pull requests", http.StatusBadRequest) + return + } + s.handleRepoItemReroute(ctx, w, repoFull, number, user, comment, body.To) case repoItemDecisionAdopt, repoItemDecisionReauthor: if itemType != "pr" { jsonError(w, decision+" applies to pull requests", http.StatusBadRequest) @@ -408,6 +420,10 @@ func (s *Server) handleRepoItemDecision(w http.ResponseWriter, r *http.Request) jsonError(w, "adoption requires governor.labels.stage.adoption to be enabled on this hive", http.StatusConflict) return } + if body.Force && decision == repoItemDecisionAdopt { + s.handleRepoItemAdoptNow(ctx, w, repoFull, number, user, comment) + return + } note := renderRepoItemDecisionAdoptComment(user, comment) if decision == repoItemDecisionReauthor { note = renderRepoItemDecisionReauthorComment(user, comment) @@ -438,7 +454,7 @@ func (s *Server) handleRepoItemDecision(w http.ResponseWriter, r *http.Request) } s.handlePullRequestMergeDecision(ctx, w, repoFull, number, user, decision, comment) default: - jsonError(w, "unknown decision; want approve, direction, close-superseded, close-wontfix, adopt, re-author, merge-now or queue-merge", http.StatusBadRequest) + jsonError(w, "unknown decision; want approve, direction, close-superseded, close-wontfix, adopt, reroute, re-author, merge-now or queue-merge", http.StatusBadRequest) } } diff --git a/src/pkg/dashboard/api_repo_item_decision_reroute.go b/src/pkg/dashboard/api_repo_item_decision_reroute.go new file mode 100644 index 0000000000..41e63c33c8 --- /dev/null +++ b/src/pkg/dashboard/api_repo_item_decision_reroute.go @@ -0,0 +1,365 @@ +package dashboard + +import ( + "context" + "errors" + "fmt" + "net/http" + "strconv" + "strings" + "time" + + "github.com/hivecommons/hive/pkg/delegatedecision" + "github.com/hivecommons/hive/pkg/stagelabels" +) + +// Operator row actions for a PR waiting on a contributor's clanker +// (hivecommons/hive#15038): "Adopt now" and "Reroute to another clanker". +// +// Both ride POST /api/repos/{o}/{r}/items/{n}/decision: +// +// {"decision":"adopt","force":true,"type":"pr"} → Adopt now +// {"decision":"reroute","to":"|any","type":"pr"} → Reroute +// +// Adopt now leaves a durable mark for the automerge sweep (the stage +// record's AdoptForcedBy plus the adoption/supersede label) and nudges the +// sweep so the adoption engine's existing supersede path runs at once — +// with maintainer_policy, presence and the grace window bypassed +// (automerge_contributor_adopt.go). Reroute hands the PR's follow-up work +// to another online clanker through the contributor fix queue +// (contribute_reroute.go) and arms a pickup timer that falls back to Adopt +// now after governor.reroute.pickup_timeout. + +const ( + repoItemDecisionReroute = "reroute" + auditRepoItemDecisionAdoptNow = "repo_item_decision_adopt_now" + auditRepoItemDecisionReroute = "repo_item_decision_reroute" + auditRepoItemRerouteFallback = "repo_item_reroute_fallback" + rowActionRerouted = "rerouted" + repoItemDecisionAdoptNowAction = "adopt-now" + // repoItemRerouteMarker opens the note a reroute leaves on the PR. + repoItemRerouteMarker = "\n@%s asked the hive to adopt this pull request now, without waiting for its author's hive. The hive opens its own PR carrying the author's commits and sign-off unchanged on the pass now running; this PR closes when that copy merges.", repoItemDecisionAdoptMarker, user, user) + if comment != "" { + body += "\n\n> " + strings.ReplaceAll(comment, "\n", "\n> ") + } + return body +} + +// rerouteReason is the return reason shipped to the target clanker: the +// PR's stage record reason (the 072 cause) or the operator's comment. +func rerouteReason(rec stagelabels.Record, comment string) (reason, check string) { + reason = strings.TrimSpace(rec.Reason) + if c := strings.TrimSpace(comment); c != "" { + if reason == "" { + reason = c + } else { + reason = reason + " — " + c + } + } + if r := strings.TrimSpace(rec.Reason); strings.HasPrefix(r, "check-failing:") { + check = strings.TrimPrefix(r, "check-failing:") + } + return reason, check +} + +// handleRepoItemReroute is {"decision":"reroute","to":"|any"}. +func (s *Server) handleRepoItemReroute(ctx context.Context, w http.ResponseWriter, repoFull string, number int, user, comment, to string) { + if s.contributeHub == nil { + jsonError(w, RerouteNoneOnlineReason, http.StatusConflict) + return + } + if !s.stageAdoptionEnabled() { + jsonError(w, "reroute requires governor.labels.stage.adoption to be enabled on this hive (its fallback is Adopt now)", http.StatusConflict) + return + } + gh := s.deps.GHClient + facts, err := s.repoItemPRFacts(ctx, repoFull, number) + if err != nil { + jsonError(w, err.Error(), http.StatusBadGateway) + return + } + store := s.stageStoreOrShared() + key := stagelabels.Key(repoFull, number) + rec := ensureStageRecord(store, key) + reason, check := rerouteReason(rec, comment) + out, err := s.contributeHub.Reroute(RerouteRequest{ + Repo: repoFull, Number: number, HeadSHA: facts.HeadSHA, Title: facts.Title, URL: facts.URL, OpenedAt: facts.OpenedAt, + Author: facts.Author, To: to, By: user, Reason: reason, Check: check, + HumanChangesRequested: strings.Contains(rec.Reason, "changes_requested") || strings.Contains(rec.Reason, "changes-requested"), + }) + if err != nil { + code := http.StatusBadRequest + if errors.Is(err, ErrNoRerouteTarget) { + code = http.StatusConflict + } + jsonError(w, err.Error(), code) + return + } + now := time.Now() + store.NoteReroute(key, facts.HeadSHA, out.To, user, reason, now) + if err := gh.CreateIssueComment(ctx, repoFull, number, renderRepoItemRerouteComment(facts.Author, out.To, user, reason, s.reroutePickupTimeout())); err != nil { + jsonError(w, "posting reroute note: "+err.Error(), http.StatusBadGateway) + return + } + s.audit.LogRecord(user, auditRepoItemDecisionReroute, auditDetail("repo", repoFull, "number", strconv.Itoa(number), "type", "pr", "to", out.To, "mode", out.Mode, "relay_failed", strconv.FormatBool(out.RelayFailed)), "", repoFull, number) + s.armReroutePickup(repoFull, number, facts.HeadSHA, out.To, user) + jsonResponse(w, repoItemDecisionResponse{OK: true, Repo: repoFull, Number: number, Decision: repoItemDecisionReroute, Status: "rerouted", + Result: repoItemRerouteResult(repoFull, number, out, s.reroutePickupTimeout())}) +} + +func repoItemRerouteResult(repoFull string, number int, out RerouteOutcome, timeout time.Duration) *RowActionResult { + res := &RowActionResult{Target: rowActionTarget(repoFull, "pr", number), Action: rowActionRerouted} + switch { + case out.RelayFailed: + res.Outcome = fmt.Sprintf("Rerouted → @%s (queued; its relay refused the interrupt: %s).", out.To, nonEmptyString(out.RelayError, "busy")) + case out.Mode == "queued": + res.Outcome = fmt.Sprintf("Rerouted → @%s (queued; %d ahead).", out.To, maxInt(out.QueueDepth-1, 0)) + default: + res.Outcome = fmt.Sprintf("Rerouted → @%s (dispatched now, %s).", out.To, out.Mode) + } + res.Next = fmt.Sprintf("@%s's hive fixes the PR or opens a replacement carrying the author's commits and sign-off. If it has not picked the work up within %s the hive falls back to Adopt now.", out.To, formatRerouteWindow(timeout)) + return res +} + +func nonEmptyString(v, def string) string { + if strings.TrimSpace(v) == "" { + return def + } + return v +} + +func maxInt(a, b int) int { + if a > b { + return a + } + return b +} + +func formatRerouteWindow(d time.Duration) string { + if d%time.Hour == 0 { + return fmt.Sprintf("%dh", int(d/time.Hour)) + } + return strings.TrimSuffix(d.Round(time.Minute).String(), "0s") +} + +// renderRepoItemRerouteComment is the note the author (and the target) get. +func renderRepoItemRerouteComment(author, to, by, reason string, timeout time.Duration) string { + var b strings.Builder + fmt.Fprintf(&b, "%s to=@%s by=@%s reason=%s -->\n", repoItemRerouteMarker, to, by, strings.ReplaceAll(nonEmptyString(reason, "waiting-on-author"), "\n", " ")) + fmt.Fprintf(&b, "@%s — @%s has rerouted the follow-up work on this pull request to @%s's hive rather than wait for yours.", author, by, to) + if reason != "" { + fmt.Fprintf(&b, " Reason: %s.", reason) + } + fmt.Fprintf(&b, " @%s will either push the fix here (if your branch allows it) or open a replacement PR that carries your commits and sign-off unchanged and supersedes this one. ", to) + fmt.Fprintf(&b, "If @%s's hive has not picked the work up within %s, the hive adopts the PR itself (`hive:adopted`). Push a new head here if you would rather finish it yourself.", to, formatRerouteWindow(timeout)) + return b.String() +} + +func (s *Server) reroutePickupTimeout() time.Duration { + if s != nil && s.deps != nil && s.deps.Config != nil { + return s.deps.Config.Governor.Reroute.EffectivePickupTimeout() + } + return 30 * time.Minute +} + +// armReroutePickup starts the pickup window. When it lapses with the item +// still queued (not in flight on the target's relay and no new head), the +// hive falls back to Adopt now: the queued item is withdrawn, the stage +// record marks the forced adoption and the sweep is nudged. +func (s *Server) armReroutePickup(repoFull string, number int, head, to, by string) { + after := s.rerouteAfterFunc + if after == nil { + after = func(d time.Duration, f func()) { time.AfterFunc(d, f) } + } + after(s.reroutePickupTimeout(), func() { s.reroutePickupLapsed(repoFull, number, head, to, by) }) +} + +// reroutePickupLapsed is the fallback body; it reports whether it fell back. +func (s *Server) reroutePickupLapsed(repoFull string, number int, head, to, by string) bool { + store := s.stageStoreOrShared() + key := stagelabels.Key(repoFull, number) + rec, ok := store.Get(key) + if !ok || rec.Rerouted(head) == "" || !strings.EqualFold(rec.RerouteTo, to) { + // Re-rerouted, adopted, or the head moved: nothing to fall back from. + return false + } + hub := s.contributeHub + if hub != nil && hub.ReroutePickedUp(to, repoFull, number) { + return false + } + ctx := context.Background() + if s.deps != nil && s.deps.Ctx != nil { + ctx = s.deps.Ctx + } + now := time.Now() + if hub != nil && !hub.RerouteQueued(to, repoFull, number) && s.deps != nil && s.deps.GHClient != nil { + // Neither queued nor in flight: the relay finished it (a new head) + // or the dispatches failed out. A moved head ends the reroute. + if facts, err := s.repoItemPRFacts(ctx, repoFull, number); err == nil && facts.HeadSHA != "" && facts.HeadSHA != head { + store.ClearReroute(key, false, now) + return false + } + } + if hub != nil { + hub.CancelReroute(to, repoFull, number) + } + store.ClearReroute(key, true, now) + store.NoteAdoptionForced(key, by, now) + if gh := s.deps.GHClient; gh != nil { + msg := fmt.Sprintf("%s to=@%s by=@%s lapsed=true -->\n@%s's hive did not pick this up within %s; falling back to adoption — the hive takes it over now (asked by @%s). The author's commits and sign-off are preserved.", + repoItemRerouteMarker, to, by, to, formatRerouteWindow(s.reroutePickupTimeout()), by) + if err := gh.CreateIssueComment(ctx, repoFull, number, msg); err != nil { + s.logger.Warn("reroute fallback note failed", "repo", repoFull, "pr", number, "error", err) + } + if err := gh.EnsureIssueLabel(ctx, repoFull, delegatedecision.LabelAdoptSupersede, adoptRequestLabelColor, adoptRequestLabelDesc); err == nil { + if err := gh.AddLabels(ctx, repoFull, number, []string{delegatedecision.LabelAdoptSupersede}); err != nil { + s.logger.Warn("reroute fallback label failed", "repo", repoFull, "pr", number, "error", err) + } + } + } + s.audit.LogRecord(by, auditRepoItemRerouteFallback, auditDetail("repo", repoFull, "number", strconv.Itoa(number), "to", to, "action", repoItemDecisionAdoptNowAction), "", repoFull, number) + s.AddSystemAlert(repoItemRerouteFallbackAlert+repoFull+"#"+strconv.Itoa(number), "warning", + fmt.Sprintf("%s#%d: @%s did not pick up the rerouted work within %s — falling back to Adopt now (hive takes it over).", repoFull, number, to, formatRerouteWindow(s.reroutePickupTimeout()))) + if s.deps != nil && s.deps.SweepNudge != nil { + s.deps.SweepNudge(repoFull, number) + } else if s.deps != nil && s.deps.WebhookWake != nil { + s.deps.WebhookWake(fmt.Sprintf("reroute-fallback %s#%d", repoFull, number)) + } + return true +} diff --git a/src/pkg/dashboard/api_repo_item_takeover_test.go b/src/pkg/dashboard/api_repo_item_takeover_test.go new file mode 100644 index 0000000000..9aa8d18715 --- /dev/null +++ b/src/pkg/dashboard/api_repo_item_takeover_test.go @@ -0,0 +1,409 @@ +package dashboard + +import ( + "encoding/json" + "net/http" + "slices" + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/delegatedecision" + "github.com/hivecommons/hive/pkg/fixqueue" + "github.com/hivecommons/hive/pkg/stagelabels" +) + +// hivecommons/hive#15038: a PR waiting on a contributor's clanker offers +// the operator "Adopt now" (forced adoption, no grace / presence / policy +// wait) and "Reroute to another clanker" (the follow-up work goes to an +// online clanker's fix queue, falling back to Adopt now when it is not +// picked up within governor.reroute.pickup_timeout). + +func takeoverServer(t *testing.T, mock *repoItemDecisionMock) (*Server, *stagelabels.Store) { + t.Helper() + srv := newRepoItemDecisionServer(t, mock) + store := stagelabels.NewStore("", nil) + srv.stageStore = store + srv.adoptNowWait = 50 * time.Millisecond + srv.contributeHub.fixAckGrace = 10 * time.Millisecond + return srv, store +} + +func recForced(rec stagelabels.Record) bool { + _, ok := rec.AdoptionForced() + return ok +} + +func decodeDecision(t *testing.T, body string) repoItemDecisionResponse { + t.Helper() + var out repoItemDecisionResponse + if err := json.Unmarshal([]byte(body), &out); err != nil { + t.Fatalf("decode %s: %v", body, err) + } + return out +} + +func TestRepoItemAdoptNowForcesAdoptionAndAudits(t *testing.T) { + mock := &repoItemDecisionMock{prForeign: true} + srv, store := takeoverServer(t, mock) + key := stagelabels.Key("testorg/testrepo", 8) + var nudged []int + srv.deps.SweepNudge = func(repo string, number int) { + nudged = append(nudged, number) + // The nudged sweep adopts: the engine records hive's copy. + store.MarkAdopted(key, "feedfacefeedfacefeedfacefeedfacefeedface", 90, time.Now()) + } + + w := postRepoItemDecision(t, srv, 8, "writer", `{"decision":"adopt","force":true,"type":"pr","comment":"CI has been red for a day"}`) + if w.Code != http.StatusOK { + t.Fatalf("adopt now: code=%d body=%s", w.Code, w.Body.String()) + } + out := decodeDecision(t, w.Body.String()) + if out.Status != "adopted-now" || out.Result == nil || out.Result.Action != rowActionAdopted { + t.Fatalf("response = %+v", out) + } + if out.Result.Outcome != "Adopted → #90 (hive's copy), contributor PR will close when #90 merges." { + t.Fatalf("toast = %q", out.Result.Outcome) + } + if nudged == nil || nudged[0] != 8 { + t.Fatalf("sweep nudged = %v", nudged) + } + if len(mock.comments) != 1 || !strings.HasPrefix(mock.comments[0], "") || !strings.Contains(mock.comments[0], "> CI has been red for a day") { + t.Fatalf("comment = %q", mock.comments) + } + if !slices.Contains(mock.added, delegatedecision.LabelAdoptSupersede) { + t.Fatalf("labels added = %v", mock.added) + } + acts := decisionAuditActions(srv) + if !slices.Contains(acts, auditRepoItemDecisionAdoptNow) { + t.Fatalf("audit = %v", acts) + } + for _, e := range srv.GetAudit().Recent(20) { + if e.Action == auditRepoItemDecisionAdoptNow && !strings.Contains(e.Detail, "action=adopt-now") { + t.Fatalf("audit detail %q lacks action=adopt-now", e.Detail) + } + } + // MarkAdopted settles the forced mark once hive's copy exists. + rec, _ := store.Get(key) + if rec.AdoptedBy != 90 || recForced(rec) { + t.Fatalf("record = %+v", rec) + } + + // A second Adopt now on the adopted head is a no-op toast. + w = postRepoItemDecision(t, srv, 8, "writer", `{"decision":"adopt","force":true,"type":"pr"}`) + out = decodeDecision(t, w.Body.String()) + if w.Code != http.StatusOK || out.Status != "already-adopted" || out.Result.Action != rowActionNoop { + t.Fatalf("repeat = %d %+v", w.Code, out) + } +} + +func TestRepoItemAdoptNowWithoutSweepIsQueuedForm(t *testing.T) { + mock := &repoItemDecisionMock{prForeign: true} + srv, store := takeoverServer(t, mock) + srv.deps.SweepNudge, srv.deps.WebhookWake = nil, nil + + w := postRepoItemDecision(t, srv, 8, "writer", `{"decision":"adopt","force":true,"type":"pr"}`) + out := decodeDecision(t, w.Body.String()) + if w.Code != http.StatusOK || out.Status != "adoption-forced" || !strings.HasPrefix(out.Result.Outcome, "Adoption forced:") { + t.Fatalf("code=%d out=%+v", w.Code, out) + } + rec, _ := store.Get(stagelabels.Key("testorg/testrepo", 8)) + if rec.AdoptForcedBy != "writer" || !recForced(rec) { + t.Fatalf("forced mark missing: %+v", rec) + } +} + +func TestRepoItemAdoptNowGuards(t *testing.T) { + // A reader cannot force adoption. + srv, _ := takeoverServer(t, &repoItemDecisionMock{prForeign: true}) + if w := postRepoItemDecision(t, srv, 8, "reader", `{"decision":"adopt","force":true,"type":"pr"}`); w.Code != http.StatusForbidden { + t.Fatalf("reader: code=%d body=%s", w.Code, w.Body.String()) + } + // Hive's own PR is never adopted. + srv, _ = takeoverServer(t, &repoItemDecisionMock{}) + if w := postRepoItemDecision(t, srv, 8, "writer", `{"decision":"adopt","force":true,"type":"pr"}`); w.Code != http.StatusBadRequest { + t.Fatalf("hive-authored: code=%d body=%s", w.Code, w.Body.String()) + } +} + +func TestRepoItemRerouteNoneOnlineIsConflict(t *testing.T) { + srv, _ := takeoverServer(t, &repoItemDecisionMock{prForeign: true}) + w := postRepoItemDecision(t, srv, 8, "writer", `{"decision":"reroute","to":"any","type":"pr"}`) + if w.Code != http.StatusConflict || !strings.Contains(w.Body.String(), RerouteNoneOnlineReason) { + t.Fatalf("code=%d body=%s", w.Code, w.Body.String()) + } + // Naming an offline clanker says so too. + w = postRepoItemDecision(t, srv, 8, "writer", `{"decision":"reroute","to":"bee2","type":"pr"}`) + if w.Code != http.StatusBadRequest || !strings.Contains(w.Body.String(), "@bee2 is not online") { + t.Fatalf("named offline: code=%d body=%s", w.Code, w.Body.String()) + } +} + +func TestRepoItemRerouteDispatchesFixPRAndMarks(t *testing.T) { + mock := &repoItemDecisionMock{prForeign: true} + srv, store := takeoverServer(t, mock) + hub := srv.contributeHub + fixConn(hub, "bee2", fixCaps(capFixPRInterrupt), time.Now()) + got := captureFixDispatch(hub) + var fallback func() + srv.rerouteAfterFunc = func(d time.Duration, f func()) { + if d != config.DefaultReroutePickupTimeout { + t.Errorf("pickup window = %s, want %s", d, config.DefaultReroutePickupTimeout) + } + fallback = f + } + key := stagelabels.Key("testorg/testrepo", 8) + store.Observe(key, stagelabels.ReturnedToContributor, "check-failing:lint") + + w := postRepoItemDecision(t, srv, 8, "writer", `{"decision":"reroute","to":"any","type":"pr","comment":"please take it"}`) + if w.Code != http.StatusOK { + t.Fatalf("reroute: code=%d body=%s", w.Code, w.Body.String()) + } + out := decodeDecision(t, w.Body.String()) + if out.Status != "rerouted" || out.Result == nil || out.Result.Action != rowActionRerouted || !strings.HasPrefix(out.Result.Outcome, "Rerouted → @bee2 (dispatched now") { + t.Fatalf("response = %+v", out) + } + if !strings.Contains(out.Result.Next, "within 30m") { + t.Fatalf("next = %q", out.Result.Next) + } + // Dispatch rides the existing fix-pr task_assign to the target relay. + if len(*got) != 1 || (*got)[0].Kind != taskKindFixPR || len((*got)[0].FixPRs) != 1 { + t.Fatalf("dispatched = %+v", *got) + } + fp := (*got)[0].FixPRs[0] + if fp.Repo != "testorg/testrepo" || fp.Number != 8 || fp.RerouteFrom != "someone" || fp.RerouteBy != "writer" || !slices.Equal(fp.FailingChecks, []string{"lint"}) || !strings.Contains(fp.RerouteReason, "please take it") { + t.Fatalf("fix-pr = %+v", fp) + } + if len(mock.comments) != 1 || !strings.HasPrefix(mock.comments[0], "") || !strings.Contains(mock.comments[0], "@someone — @writer has rerouted") { + t.Fatalf("comment = %q", mock.comments) + } + rec, _ := store.Get(key) + if rec.Rerouted("feedfacefeedfacefeedfacefeedfacefeedface") != "bee2" || rec.RerouteBy != "writer" { + t.Fatalf("record = %+v", rec) + } + if !slices.Contains(decisionAuditActions(srv), auditRepoItemDecisionReroute) { + t.Fatalf("audit = %v", decisionAuditActions(srv)) + } + if fallback == nil { + t.Fatal("pickup timer not armed") + } + // The target's relay has the task in flight: the window lapsing does + // not fall back. + if hub.ReroutePickedUp("bee2", "testorg/testrepo", 8) != true { + t.Fatal("dispatched reroute not in flight") + } + if srv.reroutePickupLapsed("testorg/testrepo", 8, "feedfacefeedfacefeedfacefeedfacefeedface", "bee2", "writer") { + t.Fatal("fell back while the target held the task") + } + if rec, _ := store.Get(key); recForced(rec) { + t.Fatalf("forced after pickup: %+v", rec) + } +} + +func TestRepoItemReroutePickupLapseFallsBackToAdoptNow(t *testing.T) { + mock := &repoItemDecisionMock{prForeign: true} + srv, store := takeoverServer(t, mock) + hub := srv.contributeHub + hub.fixDispatched = func(_ *ContributorConnection, _ WSMessage) {} + // bee2 is online but already holds a task: the reroute queues behind it. + c := fixConn(hub, "bee2", fixCaps(capFixPRInterrupt), time.Now()) + c.mu.Lock() + c.currentTask = &WSTaskAssign{TaskID: "busy"} + c.mu.Unlock() + hub.fixQueue().Enqueue("bee2", fixqueue.Item{Repo: "org/other", Number: 1, HeadSHA: "x"}) + hub.rememberFixOwner("bee2", fixqueue.Key("org/other", 1)) + hub.dispatchFixes("bee2", []*ContributorConnection{c}, false) + var fallback func() + srv.rerouteAfterFunc = func(_ time.Duration, f func()) { fallback = f } + var nudged []int + srv.deps.SweepNudge = func(_ string, n int) { nudged = append(nudged, n) } + key := stagelabels.Key("testorg/testrepo", 8) + + w := postRepoItemDecision(t, srv, 8, "writer", `{"decision":"reroute","to":"bee2","type":"pr"}`) + out := decodeDecision(t, w.Body.String()) + if w.Code != http.StatusOK || !strings.Contains(out.Result.Outcome, "Rerouted → @bee2 (queued") { + t.Fatalf("code=%d out=%+v", w.Code, out) + } + if !hub.RerouteQueued("bee2", "testorg/testrepo", 8) || hub.ReroutePickedUp("bee2", "testorg/testrepo", 8) { + t.Fatalf("queue state: queued=%v inflight=%v", hub.RerouteQueued("bee2", "testorg/testrepo", 8), hub.ReroutePickedUp("bee2", "testorg/testrepo", 8)) + } + + mock.mu.Lock() + mock.comments = nil + mock.mu.Unlock() + fallback() + + rec, _ := store.Get(key) + if rec.RerouteTo != "" || rec.RerouteFallbackAt.IsZero() || rec.AdoptForcedBy != "writer" || !recForced(rec) { + t.Fatalf("record after lapse = %+v", rec) + } + if hub.RerouteQueued("bee2", "testorg/testrepo", 8) { + t.Fatal("lapsed item still queued on bee2") + } + if len(mock.comments) != 1 || !strings.HasPrefix(mock.comments[0], "") { + t.Fatalf("fallback comment = %q", mock.comments) + } + if !slices.Contains(mock.added, delegatedecision.LabelAdoptSupersede) { + t.Fatalf("labels = %v", mock.added) + } + if !slices.Contains(decisionAuditActions(srv), auditRepoItemRerouteFallback) { + t.Fatalf("audit = %v", decisionAuditActions(srv)) + } + if nudged == nil || nudged[0] != 8 { + t.Fatalf("sweep not nudged: %v", nudged) + } + found := false + srv.systemAlertsMu.Lock() + alerts := append([]SystemAlert(nil), srv.systemAlerts...) + srv.systemAlertsMu.Unlock() + for _, a := range alerts { + if strings.HasPrefix(a.ID, repoItemRerouteFallbackAlert) && strings.Contains(a.Message, "falling back to Adopt now") { + found = true + } + } + if !found { + t.Fatalf("no fallback alert: %+v", alerts) + } + // Running the lapse again finds nothing to fall back from. + if srv.reroutePickupLapsed("testorg/testrepo", 8, "feedfacefeedfacefeedfacefeedfacefeedface", "bee2", "writer") { + t.Fatal("second lapse fell back again") + } +} + +func TestRerouteCandidatesExcludeAuthorAndOffline(t *testing.T) { + hub, _ := covK2Hub(t) + now := time.Now() + fixConn(hub, "bee2", fixCaps(capFixPRInterrupt), now) + fixConn(hub, "someone", fixCaps(capFixPRInterrupt), now) + fixConn(hub, "stale", fixCaps(capFixPRInterrupt), now.Add(-2*time.Hour)) + cands := hub.RerouteCandidates(now, "someone") + if len(cands) != 1 || cands[0].Login != "bee2" || !cands[0].Capable { + t.Fatalf("candidates = %+v", cands) + } + if _, err := hub.Reroute(RerouteRequest{Repo: "o/r", Number: 1, Author: "someone", To: "someone"}); err == nil || !strings.Contains(err.Error(), "is the PR's author") { + t.Fatalf("reroute to author err = %v", err) + } +} + +// Tracker: the row carries takeover{} with the menu's facts. + +func TestStageTrackerTakeoverOffersAdoptNowAndReroute(t *testing.T) { + now := time.Date(2026, 10, 28, 16, 0, 0, 0, time.UTC) + s, store, status := adoptionFixture(t, now, config.AdoptionMaintainerPolicyNever, offlinePresence(now.Add(-26*time.Hour))) + since := now.Add(-time.Hour) + s.rerouteCandidates = func(author string) []RerouteCandidate { + if author != "hanthor" { + t.Errorf("candidates asked excluding %q", author) + } + return []RerouteCandidate{{Login: "bee2", HiveName: "bee2-hive", OnlineSince: &since, Load: 1, Capable: true}} + } + it := trackerItem(t, s.buildStageTracker(status, store, now), "pr", 14524) + tk := it.Takeover + if tk == nil || !tk.AdoptNow || !tk.Reroute || tk.Author != "hanthor" || tk.AuthorOnline || len(tk.Clankers) != 1 || tk.Clankers[0].Login != "bee2" { + t.Fatalf("takeover = %+v", tk) + } + if !tk.GraceElapsed { + t.Fatalf("26h past the nudge is past the offline grace: %+v", tk) + } + // Grace elapsed under never: the popover asks a person (Adopt now / + // Reroute lead; Hold closes). + d := it.DecisionNeeded + if d == nil || len(d.Options) != 3 || d.Options[0].Action != decisionActionAdoptNow || !d.Options[0].Enabled || d.Options[1].Action != decisionActionReroute || !d.Options[1].Enabled { + t.Fatalf("decision_needed = %+v", d) + } + if !strings.Contains(d.Question, "@hanthor has been offline for 26h") || !strings.Contains(d.Question, "reroute") { + t.Fatalf("question = %q", d.Question) + } + raw, _ := json.Marshal(it) + for _, want := range []string{`"takeover":{`, `"adopt_now":true`, `"reroute":true`, `"clankers":[{"login":"bee2"`, `"grace_elapsed":true`} { + if !strings.Contains(string(raw), want) { + t.Errorf("payload lacks %s: %s", want, raw) + } + } +} + +func TestStageTrackerTakeoverDisabledReasons(t *testing.T) { + now := time.Date(2026, 10, 28, 16, 0, 0, 0, time.UTC) + s, store, status := adoptionFixture(t, now, config.AdoptionMaintainerPolicyNever, offlinePresence(now.Add(-26*time.Hour))) + s.rerouteCandidates = func(string) []RerouteCandidate { return nil } + it := trackerItem(t, s.buildStageTracker(status, store, now), "pr", 14524) + if tk := it.Takeover; tk == nil || !tk.AdoptNow || tk.Reroute || tk.RerouteReason != RerouteNoneOnlineReason { + t.Fatalf("no clankers: %+v", it.Takeover) + } + if d := it.DecisionNeeded; d == nil || d.Options[1].Enabled || d.Options[1].ReasonIfDisabled != RerouteNoneOnlineReason { + t.Fatalf("reroute option = %+v", d) + } + + // A hold disables both with "release the hold first". + pr := status.Repos[0].OpenPrs[0].(FrontendPR) + pr.Labels = append(pr.Labels, "hold") + status.Repos[0].OpenPrs[0] = pr + s.UpdateStatus(status) + s.rerouteCandidates = func(string) []RerouteCandidate { return []RerouteCandidate{{Login: "bee2", Capable: true}} } + it = trackerItem(t, s.buildStageTracker(status, store, now), "pr", 14524) + if tk := it.Takeover; tk == nil || tk.AdoptNow || tk.Reroute || tk.AdoptNowReason != takeoverAdoptNowDisabledHold || tk.RerouteReason != takeoverAdoptNowDisabledHold { + t.Fatalf("held: %+v", it.Takeover) + } +} + +func TestStageTrackerTakeoverShowsReroutePill(t *testing.T) { + now := time.Date(2026, 10, 28, 16, 0, 0, 0, time.UTC) + s, store, status := adoptionFixture(t, now, config.AdoptionMaintainerPolicyNever, offlinePresence(now.Add(-26*time.Hour))) + s.rerouteCandidates = func(string) []RerouteCandidate { return []RerouteCandidate{{Login: "bee2", Capable: true}} } + store.NoteReroute(stagelabels.Key("hivecommons/hive", 14524), "feed", "bee2", "andan02", "check-failing:ratchet", now.Add(-5*time.Minute)) + it := trackerItem(t, s.buildStageTracker(status, store, now), "pr", 14524) + r := it.Takeover.Rerouted + if r == nil || r.To != "bee2" || r.By != "andan02" || !r.TargetOnline || r.Text != "Rerouted to @bee2 by @andan02 — check-failing:ratchet" { + t.Fatalf("rerouted = %+v", r) + } + if !strings.Contains(it.Caption, "Rerouted to @bee2") { + t.Fatalf("caption = %q", it.Caption) + } +} + +// Store: the marks the two actions leave. + +func TestStageStoreForcedAndRerouteMarks(t *testing.T) { + now := time.Date(2026, 10, 28, 16, 0, 0, 0, time.UTC) + store := stagelabels.NewStore("", func() time.Time { return now }) + key := stagelabels.Key("o/r", 1) + store.Observe(key, stagelabels.ReturnedToContributor, "x") + store.NoteReroute(key, "h1", "bee2", "op", "why", now) + rec, _ := store.Get(key) + if rec.Rerouted("h1") != "bee2" || rec.Rerouted("h2") != "" || rec.RerouteAt != now { + t.Fatalf("after reroute: %+v", rec) + } + // Adopt now supersedes a pending reroute. + store.NoteAdoptionForced(key, "op", now.Add(time.Minute)) + rec, _ = store.Get(key) + if rec.Rerouted("h1") != "" || !recForced(rec) || rec.AdoptForcedBy != "op" { + t.Fatalf("after force: %+v", rec) + } + store.ClearAdoptionForced(key) + if rec, _ = store.Get(key); recForced(rec) { + t.Fatalf("clear left %+v", rec) + } + store.NoteReroute(key, "h1", "bee2", "op", "why", now) + store.ClearReroute(key, true, now.Add(2*time.Minute)) + rec, _ = store.Get(key) + if rec.RerouteTo != "" || !rec.RerouteFallbackAt.Equal(now.Add(2*time.Minute)) { + t.Fatalf("after fallback clear: %+v", rec) + } + // Adoption settles everything. + store.NoteAdoptionForced(key, "op", now) + store.MarkAdopted(key, "h1", 9, now) + rec, _ = store.Get(key) + if recForced(rec) || rec.RerouteTo != "" || rec.AdoptedBy != 9 { + t.Fatalf("after adopted: %+v", rec) + } +} + +// Delegated "Let hive decide": grace elapsed → adopt now. + +func TestDelegatedDecisionGraceElapsedAdoptsNow(t *testing.T) { + d := delegatedecision.Decide(delegatedecision.Input{Kind: delegatedecision.KindPR, AdoptionGraceElapsed: true}) + if d.Rule != delegatedecision.RuleAdoptNow || d.Verdict != delegatedecision.VerdictAdoptSupersede || !slices.ContainsFunc(d.Actions, func(a delegatedecision.Action) bool { return a.Kind == delegatedecision.ActionAdoptSupersede }) { + t.Fatalf("decision = %+v", d) + } +} diff --git a/src/pkg/dashboard/contribute_fixqueue.go b/src/pkg/dashboard/contribute_fixqueue.go index 3128d7fa33..3490139746 100644 --- a/src/pkg/dashboard/contribute_fixqueue.go +++ b/src/pkg/dashboard/contribute_fixqueue.go @@ -67,6 +67,11 @@ type WSFixPR struct { FailingChecks []string `json:"failing_checks,omitempty"` ReviewAsks []string `json:"review_asks,omitempty"` Reason string `json:"reason,omitempty"` + // RerouteFrom / RerouteBy / RerouteReason are set when this is another + // contributor's PR an operator rerouted to this relay (contribute_reroute.go). + RerouteFrom string `json:"rerouted_from,omitempty"` + RerouteBy string `json:"rerouted_by,omitempty"` + RerouteReason string `json:"reroute_reason,omitempty"` } // fixPRInstruction is the prompt shipped with a fix-pr task. @@ -90,8 +95,12 @@ func fixPRInstruction(prs []WSFixPR, mode fixqueue.Mode) string { fmt.Fprintf(&b, " - review ask: %s\n", a) } } - b.WriteString("\nWork on the EXISTING PR branch: check it out, fix the cause, and push a new head to the same branch with the same DCO sign-off. ") - b.WriteString("Do not open a new PR. When the new head is green the PR returns to the normal review → merge path automatically.\n") + if len(prs) > 0 && prs[0].RerouteFrom != "" { + b.WriteString(fixPRRerouteInstruction(prs[0])) + } else { + b.WriteString("\nWork on the EXISTING PR branch: check it out, fix the cause, and push a new head to the same branch with the same DCO sign-off. ") + b.WriteString("Do not open a new PR. When the new head is green the PR returns to the normal review → merge path automatically.\n") + } switch mode { case fixqueue.ModeSpawn: b.WriteString("\nThis task runs in a parallel fix session; your primary session keeps its current task.\n") @@ -101,6 +110,26 @@ func fixPRInstruction(prs []WSFixPR, mode fixqueue.Mode) string { return b.String() } +// fixPRRerouteInstruction is the work paragraph of a rerouted fix: the PR +// is another contributor's, whose fork branch this relay most likely cannot +// push to, so the fix lands as a replacement PR that carries the original +// commits and sign-off. +func fixPRRerouteInstruction(pr WSFixPR) string { + var b strings.Builder + fmt.Fprintf(&b, "\nThis PR is NOT yours: it belongs to @%s, whose hive has not acted on it", pr.RerouteFrom) + if pr.RerouteBy != "" { + fmt.Fprintf(&b, ", and @%s rerouted the follow-up work to you", pr.RerouteBy) + } + b.WriteString(".") + if pr.RerouteReason != "" { + fmt.Fprintf(&b, " Return reason: %s.", pr.RerouteReason) + } + b.WriteString("\n\nFetch the PR's head and work from it. If you can push to its branch (same-repo head, or maintainer_can_modify), fix the cause there and push a new head with your DCO sign-off added to your commits only. ") + fmt.Fprintf(&b, "Otherwise open a replacement PR from a branch that carries @%s's commits UNCHANGED (their authorship and Signed-off-by stay), add your fix commits with your own sign-off on top, and put `Supersedes %s#%d` in the body so the hive links and closes the original when yours merges. ", pr.RerouteFrom, pr.Repo, pr.Number) + b.WriteString("Do not rewrite or squash the original author's commits.\n") + return b.String() +} + func shortSHA(sha string) string { if len(sha) > 12 { return sha[:12] @@ -391,7 +420,8 @@ func (h *ContributeWSHub) dispatchFixes(user string, conns []*ContributorConnect func (h *ContributeWSHub) sendFixTask(c *ContributorConnection, user string, d *fixqueue.Dispatch) WSMessage { prs := make([]WSFixPR, 0, len(d.Items)) for _, it := range d.Items { - pr := WSFixPR{Repo: it.Repo, Number: it.Number, URL: it.URL, HeadSHA: it.HeadSHA, Title: it.Title, Reason: it.Cause.Signature} + pr := WSFixPR{Repo: it.Repo, Number: it.Number, URL: it.URL, HeadSHA: it.HeadSHA, Title: it.Title, Reason: it.Cause.Signature, + RerouteFrom: it.RerouteFrom, RerouteBy: it.RerouteBy, RerouteReason: it.RerouteReason} if it.Cause.Check != "" { pr.FailingChecks = []string{it.Cause.Check} } diff --git a/src/pkg/dashboard/contribute_reroute.go b/src/pkg/dashboard/contribute_reroute.go new file mode 100644 index 0000000000..b7fd2cd494 --- /dev/null +++ b/src/pkg/dashboard/contribute_reroute.go @@ -0,0 +1,247 @@ +package dashboard + +import ( + "errors" + "sort" + "strings" + "time" + + "github.com/hivecommons/hive/pkg/fixqueue" +) + +// Operator "Reroute to another clanker" (hivecommons/hive#15038). +// +// A PR returned to its contributor (stage 072 / 071) may sit while that +// contributor's hive is away. Instead of waiting out the offline grace +// window, an operator can hand the PR's follow-up work to another online +// registered contributor clanker. The hand-off reuses the stage-072 fix +// machinery (contribute_fixqueue.go): the PR is enqueued as a fixqueue.Item +// on the TARGET contributor's queue, flagged RerouteFrom so the fix-pr +// task_assign prompt tells the relay the PR is someone else's and how to +// carry the original commits + sign-off, and dispatched at once when the +// relay has a free slot (else at its next task boundary, ahead of new +// issues). If the target has not picked it up within +// governor.reroute.pickup_timeout the decision handler falls back to Adopt +// now (api_repo_item_decision_reroute.go). + +// RerouteAny is the `to` value meaning "any online clanker". +const RerouteAny = "any" + +// ErrNoRerouteTarget is returned when no online clanker can take the work. +var ErrNoRerouteTarget = errors.New("no clankers online — use Adopt now") + +// RerouteNoneOnlineReason is the menu item's disabled reason when no +// contributor clanker is online. +const RerouteNoneOnlineReason = "no clankers online — use Adopt now" + +// RerouteCandidate is one online registered contributor clanker that can +// take rerouted work (the Reroute submenu's rows). +type RerouteCandidate struct { + Login string `json:"login"` + // HiveName is the contributor's hive (its ContributorID, with the + // relay's session label when it declared one). + HiveName string `json:"hive_name,omitempty"` + OnlineSince *time.Time `json:"online_since,omitempty"` + // Load is the clanker's current work: its primary task (1 when set) + // plus fix tasks in flight plus fixes queued for it. + Load int `json:"load"` + // Capable reports whether the relay advertised fix-pr tasks; a relay + // without the capability is listed but cannot take a reroute. + Capable bool `json:"capable"` +} + +// RerouteCandidates lists the online, fix-pr-capable contributor clankers +// other than exclude (the PR's own author), least loaded first. +func (h *ContributeWSHub) RerouteCandidates(now time.Time, exclude string) []RerouteCandidate { + if h == nil { + return nil + } + window := h.presenceWindow() + sched := h.fixQueue() + byLogin := map[string]*RerouteCandidate{} + h.mu.RLock() + for _, c := range h.connections { + c.mu.Lock() + login := "" + hive := "" + if c.profile != nil { + login = strings.TrimSpace(c.profile.GitHubUsername) + hive = c.profile.ContributorID + } + if c.session != "" { + hive += "#" + c.session + } + pong := c.lastPong + since := c.connectedAt + busy := 0 + if c.currentTask != nil { + busy++ + } + busy += len(c.fixTasks) + capable := relaySupportsFixPR(c) + c.mu.Unlock() + if login == "" || strings.EqualFold(login, exclude) || pong.IsZero() || now.Sub(pong) > window { + continue + } + cand, ok := byLogin[strings.ToLower(login)] + if !ok { + cand = &RerouteCandidate{Login: login, HiveName: hive} + byLogin[strings.ToLower(login)] = cand + } + if !since.IsZero() && (cand.OnlineSince == nil || since.Before(*cand.OnlineSince)) { + t := since.UTC() + cand.OnlineSince = &t + } + cand.Load += busy + cand.Capable = cand.Capable || capable + } + h.mu.RUnlock() + out := make([]RerouteCandidate, 0, len(byLogin)) + for _, cand := range byLogin { + if !cand.Capable { + continue + } + cand.Load += len(sched.Queued(cand.Login)) + out = append(out, *cand) + } + sort.Slice(out, func(i, j int) bool { + if out[i].Load != out[j].Load { + return out[i].Load < out[j].Load + } + return strings.ToLower(out[i].Login) < strings.ToLower(out[j].Login) + }) + return out +} + +// RerouteRequest is one PR's follow-up work to hand to another clanker. +type RerouteRequest struct { + Repo string // owner/name + Number int + HeadSHA string + Title string + URL string + // Author is the PR's author (excluded from the candidates); To is the + // requested target login or RerouteAny; By is the operator. + Author, To, By string + // Reason is the stage-072 return reason / the reviewer's ask, shipped + // in the prompt; Check is the failing check when the cause is CI. + Reason, Check string + HumanChangesRequested bool + OpenedAt time.Time +} + +// RerouteOutcome says where the work went. +type RerouteOutcome struct { + To string `json:"to"` + // Mode is the dispatch mode ("spawn", "preempt") when the relay took + // the task at once, else "queued". + Mode string `json:"mode"` + QueueDepth int `json:"queue_depth"` + // RelayFailed is set when the relay refused the interrupt; the item + // stays queued for its next task boundary. + RelayFailed bool `json:"relay_failed,omitempty"` + RelayError string `json:"relay_error,omitempty"` +} + +// Reroute enqueues req on the target's fix queue and dispatches it when the +// relay has a slot. ErrNoRerouteTarget when the named clanker (or, for +// RerouteAny, every clanker) is offline or cannot take fix-pr tasks. +func (h *ContributeWSHub) Reroute(req RerouteRequest) (RerouteOutcome, error) { + now := time.Now() + target := strings.TrimPrefix(strings.TrimSpace(req.To), "@") + cands := h.RerouteCandidates(now, req.Author) + if target == "" || strings.EqualFold(target, RerouteAny) { + if len(cands) == 0 { + return RerouteOutcome{}, ErrNoRerouteTarget + } + target = cands[0].Login + } else { + found := false + for _, c := range cands { + if strings.EqualFold(c.Login, target) { + target, found = c.Login, true + break + } + } + if !found { + if strings.EqualFold(target, req.Author) { + return RerouteOutcome{}, errors.New("@" + target + " is the PR's author; reroute to another clanker or use Adopt now") + } + return RerouteOutcome{}, errors.New("@" + target + " is not online (or its relay cannot take fix-pr tasks) — " + RerouteNoneOnlineReason) + } + } + item := fixqueue.Item{ + Repo: req.Repo, Number: req.Number, HeadSHA: req.HeadSHA, Title: req.Title, URL: req.URL, + OpenedAt: req.OpenedAt, HumanChangesRequested: req.HumanChangesRequested, + Cause: fixqueue.Cause{Check: req.Check, Signature: req.Reason}, + Summary: req.Reason, + RerouteFrom: req.Author, RerouteBy: req.By, RerouteReason: req.Reason, + } + // The author's own queue no longer owns the PR: a hive that comes back + // must not race the target on the same head. + h.CancelReroute(req.Author, req.Repo, req.Number) + sched := h.fixQueue() + sched.Enqueue(target, item) + h.rememberFixOwner(target, item.Key()) + out := RerouteOutcome{To: target, Mode: "queued"} + conns, online := h.liveConnectionsFor(target, now) + if online { + failed := h.beginFixWait() + defer h.endFixWait() + if msg := h.dispatchFixes(target, conns, false); msg != nil { + out.Mode = msg.Mode + if reason, refused := h.awaitFixTaskRefusal(msg.TaskID, failed); refused { + out.Mode = "queued" + out.RelayFailed = true + out.RelayError = reason + } + } + } + out.QueueDepth = sched.Status(target, fixqueue.Capacity{Max: 1}).Queued + h.logger.Info("[contribute-ws] PR rerouted", "repo", req.Repo, "pr", req.Number, "from", req.Author, "to", target, "by", req.By, "mode", out.Mode, "queued", out.QueueDepth) + return out, nil +} + +// ReroutePickedUp reports whether user's relay has taken repo#number: the +// item is in flight on a dispatch (or already completed: neither queued +// nor in flight after a dispatch happened). +func (h *ContributeWSHub) ReroutePickedUp(user, repo string, number int) bool { + if h == nil { + return false + } + sched := h.fixQueue() + key := fixqueue.Key(repo, number) + for _, d := range sched.InFlight(user) { + for _, it := range d.Items { + if it.Key() == key { + return true + } + } + } + return false +} + +// RerouteQueued reports whether repo#number still waits in user's queue. +func (h *ContributeWSHub) RerouteQueued(user, repo string, number int) bool { + if h == nil { + return false + } + key := fixqueue.Key(repo, number) + for _, it := range h.fixQueue().Queued(user) { + if it.Key() == key { + return true + } + } + return false +} + +// CancelReroute removes repo#number from user's fix queue (the pickup window +// lapsed, or the work went elsewhere). It does not recall a task already in +// flight. +func (h *ContributeWSHub) CancelReroute(user, repo string, number int) { + if h == nil || strings.TrimSpace(user) == "" { + return + } + h.fixQueue().Remove(user, repo, number) + h.forgetFixOwner(user, fixqueue.Key(repo, number)) +} diff --git a/src/pkg/dashboard/deps.go b/src/pkg/dashboard/deps.go index eafe570706..0b65cec71c 100644 --- a/src/pkg/dashboard/deps.go +++ b/src/pkg/dashboard/deps.go @@ -277,6 +277,11 @@ type Dependencies struct { // reason names the delivery ("pull_request_review org/repo#12"). Nil // leaves invalidated items waiting for the next cadence tick. WebhookWake func(reason string) + // SweepNudge asks the automerge lanes for an early pass over one PR + // (repo is "owner/name"). The operator row actions that leave a + // durable mark for the sweep (Adopt now) call it so the pass runs now + // rather than on cadence. Nil leaves the mark for the next sweep. + SweepNudge func(repo string, number int) // ApplyWebhookItems hands the targeted re-reads a webhook delivery // caused (webhook_tracker_refresh.go) to the governor so its cached // actionable snapshot is patched for those items only; the wake cycle diff --git a/src/pkg/dashboard/operator_actions.go b/src/pkg/dashboard/operator_actions.go index 983c1fbaf8..1358421987 100644 --- a/src/pkg/dashboard/operator_actions.go +++ b/src/pkg/dashboard/operator_actions.go @@ -47,6 +47,11 @@ const ( // The operator's explicit re-authoring of a head that cannot merge // as-is (hivecommons/hive#15136). operatorActionReauthor = "re-author" + // operatorActionAdopt / AdoptNow / Reroute are the 072 takeover + // decisions (hivecommons/hive#15038): adopt-now is adopt with force. + operatorActionAdopt = "adopt" + operatorActionAdoptNow = "adopt-now" + operatorActionReroute = "reroute" // Stored outcomes: what the endpoint answered when the action was // submitted. `pending` is a delegated decision still running; the job's @@ -260,6 +265,8 @@ func operatorActionFromBody(endpoint string, body []byte) (operatorActionRequest Held *bool `json:"held"` Reason string `json:"reason"` Head string `json:"head"` + Force bool `json:"force"` + To string `json:"to"` } if len(bytes.TrimSpace(body)) > 0 { _ = json.Unmarshal(body, &raw) @@ -283,6 +290,14 @@ func operatorActionFromBody(endpoint string, body []byte) (operatorActionRequest out.Action = operatorActionQueueMerge case repoItemDecisionReauthor: out.Action = operatorActionReauthor + case repoItemDecisionAdopt: + out.Action = operatorActionAdopt + if raw.Force { + out.Action = operatorActionAdoptNow + } + case repoItemDecisionReroute: + out.Action = operatorActionReroute + out.Target = strings.TrimPrefix(strings.TrimSpace(raw.To), "@") default: return out, false } diff --git a/src/pkg/dashboard/operator_actions_test.go b/src/pkg/dashboard/operator_actions_test.go index 2089429077..22475ad1c3 100644 --- a/src/pkg/dashboard/operator_actions_test.go +++ b/src/pkg/dashboard/operator_actions_test.go @@ -62,6 +62,9 @@ func TestOperatorActionFromBody(t *testing.T) { {"decision", `{"decision":"merge-now","head":"abc"}`, operatorActionRequest{Action: operatorActionMergeNow, Head: "abc"}, true}, {"decision", `{"decision":"queue-merge"}`, operatorActionRequest{Action: operatorActionQueueMerge}, true}, {"decision", `{"decision":"re-author"}`, operatorActionRequest{Action: operatorActionReauthor}, true}, + {"decision", `{"decision":"adopt"}`, operatorActionRequest{Action: operatorActionAdopt}, true}, + {"decision", `{"decision":"adopt","force":true,"comment":"now"}`, operatorActionRequest{Action: operatorActionAdoptNow, Note: "now"}, true}, + {"decision", `{"decision":"reroute","to":"@bee2"}`, operatorActionRequest{Action: operatorActionReroute, Target: "bee2"}, true}, {"decision", `{"decision":"bogus"}`, operatorActionRequest{}, false}, {"decide-delegated", ``, operatorActionRequest{Action: operatorActionLetHiveDecide}, true}, {"hold", `{"held":true}`, operatorActionRequest{Action: operatorActionHold}, true}, diff --git a/src/pkg/dashboard/server.go b/src/pkg/dashboard/server.go index d25f9af47a..ec9e97d89f 100644 --- a/src/pkg/dashboard/server.go +++ b/src/pkg/dashboard/server.go @@ -126,6 +126,14 @@ type Server struct { // sweepState overrides the automerge lanes' live sweep state for the // tracker's merge-gate rows (stage_tracker_merge_gate.go); tests only. sweepState func() automerge.SweepState + // adoptNowWait / rerouteAfterFunc let tests shorten the Adopt now + // sweep wait and run the reroute pickup timer by hand + // (api_repo_item_decision_reroute.go); zero/nil use the real clock. + adoptNowWait time.Duration + rerouteAfterFunc func(time.Duration, func()) + // rerouteCandidates overrides the contribute hub as the tracker's + // online-clanker source for the Reroute submenu; tests only. + rerouteCandidates func(author string) []RerouteCandidate // stageTrackerCache is the last /api/stage-tracker payload built from // the status snapshot, served until its TTL lapses (stage_tracker.go). stageTrackerCache stageTrackerCache diff --git a/src/pkg/dashboard/stage_tracker.go b/src/pkg/dashboard/stage_tracker.go index 9a3b44f7f6..c185ef64bb 100644 --- a/src/pkg/dashboard/stage_tracker.go +++ b/src/pkg/dashboard/stage_tracker.go @@ -447,6 +447,10 @@ type StageTrackerItem struct { // hive's likely next move (wait or adopt, with the adopt-at time), so // the waiting-on pill can carry an indicator (hivecommons/hive#15051). Presence *StageTrackerPresence `json:"presence,omitempty"` + // Takeover is, on a 072 / 071 clanker PR, the operator's Adopt now / + // Reroute offer and any pending reroute or forced adoption + // (hivecommons/hive#15038, stage_tracker_takeover.go). + Takeover *StageTrackerTakeover `json:"takeover,omitempty"` // ClaimantKind is the author kind of whoever holds the live claim on a // claimed issue (human / clanker / hive), from the worker-claim ledger. ClaimantKind string `json:"claimant_kind,omitempty"` @@ -575,6 +579,8 @@ type StageTrackerLinkedPR struct { DrawnUnder int `json:"drawn_under,omitempty"` // Presence mirrors the nested PR's own row field (hivecommons/hive#15051). Presence *StageTrackerPresence `json:"presence,omitempty"` + // Takeover mirrors the nested PR's own row field (hivecommons/hive#15038). + Takeover *StageTrackerTakeover `json:"takeover,omitempty"` } // StageTrackerHold is the row's hold provenance (stagelabels.HoldProvenance @@ -1765,6 +1771,7 @@ func (s *Server) buildStageTracker(status *StatusPayload, store *stagelabels.Sto sweep := s.stageTrackerSweepState() workers := stageTrackerWorkersFromStatus(status) adoptionClock := s.stageTrackerAdoptionClock() + rerouteCandidates, adoptionEnabled, takeoverGrace := s.stageTrackerRerouteCandidates(), s.stageAdoptionEnabled(), s.takeoverGrace() finish := func(it *StageTrackerItem, labels []string, stage stagelabels.Stage, rec stagelabels.Record, hasRec bool, draft bool) { // "Needs human decision" is read from the item's current labels, not // a store record that outlived them: once the park label is gone @@ -1844,6 +1851,9 @@ func (s *Server) buildStageTracker(status *StatusPayload, store *stagelabels.Sto if login := stageTrackerWaitingOn(*it, stage); login != "" { it.Presence = stageTrackerPresenceFor(*it, login, stage, rec, hasRec, presence, adoptionClock, now) } + if it.Takeover = stageTrackerTakeover(*it, rec, hasRec, presence, rerouteCandidates, adoptionEnabled, takeoverGrace, now); it.Takeover != nil { + it.Caption = stageTrackerTakeoverCaption(it.Caption, it.Takeover) + } base, approver := stagelabels.HumanApprovedReason(it.Reason) it.HumanApprover = approver it.ManualMerge = stageTrackerManualMergeReason(base) @@ -2766,6 +2776,7 @@ func stageTrackerResolveLinkedPRs(items []StageTrackerItem) { lp.SentinelAlert, lp.SentinelReason, lp.Head = pr.SentinelAlert, pr.SentinelReason, pr.Head lp.Adoption = pr.Adoption lp.Presence = pr.Presence + lp.Takeover = pr.Takeover lp.HumanApprover, lp.ManualMerge = pr.HumanApprover, pr.ManualMerge lp.HumanMergeReason, lp.HumanMergeReasonText = pr.HumanMergeReason, pr.HumanMergeReasonText lp.AdmittedBy, lp.DCOUnsigned, lp.DCOTotal = pr.AdmittedBy, pr.DCOUnsigned, pr.DCOTotal diff --git a/src/pkg/dashboard/stage_tracker_adoption.go b/src/pkg/dashboard/stage_tracker_adoption.go index 44a8582150..a6198caf5c 100644 --- a/src/pkg/dashboard/stage_tracker_adoption.go +++ b/src/pkg/dashboard/stage_tracker_adoption.go @@ -56,6 +56,14 @@ type StageTrackerAdoption struct { Text string `json:"text"` } +// BlockerReason is the hold reason, or "policy" when the engine recorded none. +func (a StageTrackerAdoption) BlockerReason() string { + if a.BlockedBy != "" { + return a.BlockedBy + } + return "policy" +} + // decisionActionAdopt is the row action id for the owner's Adopt, in the // context menu's "decide:" vocabulary (POST …/decision adopt). const decisionActionAdopt = "decide:adopt" diff --git a/src/pkg/dashboard/stage_tracker_decision.go b/src/pkg/dashboard/stage_tracker_decision.go index 8b919b2996..908ce9179f 100644 --- a/src/pkg/dashboard/stage_tracker_decision.go +++ b/src/pkg/dashboard/stage_tracker_decision.go @@ -169,6 +169,11 @@ func stageTrackerDecisionNeededAt(it StageTrackerItem, verdict *review.Aggregate return decisionForUnauthorized(it, held) case it.Kind == "pr" && it.Adoption != nil && it.Adoption.Action == decisionActionAdopt: return decisionForAdoption(it, held, now) + case it.Kind == "pr" && it.Takeover != nil && it.Takeover.GraceElapsed && it.Adoption != nil && it.Adoption.BlockedBy != stagelabels.AdoptBlockedAuthorMaintainer: + // The nudge grace ran out and the engine has not adopted (ask is + // the case above; never stays the policy's word): the wait is a + // person's to end (Adopt now / Reroute) — hivecommons/hive#15038. + return decisionForWaitingOnContributor(it, held, now) case it.Kind == "pr" && it.AuthorKind == authorKindHuman && slices.Contains(stageTrackerNeedsHumanAuthorStages, it.Stage): return decisionForWaitingOnAuthor(it, held) case stageTrackerNeedsHuman(it) || (held && stageTrackerNeedsHuman(stageTrackerWithoutHold(it))): @@ -405,6 +410,31 @@ func decisionForWaitingOnAuthor(it StageTrackerItem, held bool) *StageTrackerDec return d } +// decisionForWaitingOnContributor: a 072 clanker PR whose adoption came due +// and is held (hivecommons/hive#15038). The options are the takeover's. +func decisionForWaitingOnContributor(it StageTrackerItem, held bool, now time.Time) *StageTrackerDecision { + a := it.Adoption + who := "the author" + if a.Author != "" { + who = "@" + a.Author + } + d := &StageTrackerDecision{Since: a.Since, AskedBy: decisionAskedByLane, BlockerReason: "adoption:" + a.BlockerReason()} + gone := "has been offline since the nudge" + if off := strings.TrimSpace(stageTrackerAdoptionOfflineFor(*a, now)); off != "" { + gone = "has been offline for " + off + } + if a.AuthorOnline { + gone = "is online but has not answered " + plural(a.Nudges, "nudge") + } + d.Question = who + " " + gone + " and the hive is not adopting on its own; take the PR over now, or reroute its follow-up work to another clanker?" + d.Blocker = "The PR waits on " + who + "'s hive; adoption is held (" + a.BlockerReason() + ")." + if held { + d.Blocker += " " + decisionHeldBlocker(it.Hold) + } + d.Options = append(takeoverDecisionOptions(it.Takeover, held), decisionHoldOption(held)) + return d +} + // decisionForAdoption: a nudged 072 PR whose author maintains the // repository, held for an owner under // governor.labels.stage.adoption.maintainer_policy: ask @@ -431,8 +461,9 @@ func decisionForAdoption(it StageTrackerItem, held bool, now time.Time) *StageTr } d.Options = []StageTrackerDecisionOption{ decisionOption(decisionActionAdopt, "Adopt (hive takes over)", !held, "Release the hold first"), - decisionHoldOption(held), } + d.Options = append(d.Options, takeoverDecisionOptions(it.Takeover, held)...) + d.Options = append(d.Options, decisionHoldOption(held)) return d } @@ -744,7 +775,11 @@ func decisionForNeedsHuman(it StageTrackerItem, held bool) *StageTrackerDecision } else { resolve.Consequence = "lifts needs-human and records /hive approve as you; the hive carries on" } - d.Options = []StageTrackerDecisionOption{resolve, decisionDelegateOption(held, "the hive reviews it as the owner's delegate and either lifts needs-human or says in plain words why it kept it"), decisionHoldOption(held)} + d.Options = []StageTrackerDecisionOption{resolve} + // A needs-human PR still waiting on its contributor's clanker offers + // the takeover actions too (hivecommons/hive#15038). + d.Options = append(d.Options, takeoverDecisionOptions(it.Takeover, held)...) + d.Options = append(d.Options, decisionDelegateOption(held, "the hive reviews it as the owner's delegate and either lifts needs-human or says in plain words why it kept it"), decisionHoldOption(held)) return d } diff --git a/src/pkg/dashboard/stage_tracker_row_actions_test.go b/src/pkg/dashboard/stage_tracker_row_actions_test.go index c16588db3b..c3a2107b02 100644 --- a/src/pkg/dashboard/stage_tracker_row_actions_test.go +++ b/src/pkg/dashboard/stage_tracker_row_actions_test.go @@ -64,7 +64,23 @@ func stageTrackerRowActionsPreamble(t *testing.T, html string) string { jsFunc(t, html, "stageTrackerDecisionOf"), jsFunc(t, html, "stageTrackerActionAllowed"), jsFunc(t, html, "stageTrackerLeadActions"), + // Takeover: Adopt now / Reroute (hivecommons/hive#15038). + jsConstLine(t, html, "STAGE_TRACKER_ADOPT_NOW_CONSEQUENCE"), + jsConstLine(t, html, "STAGE_TRACKER_REROUTE_ANY"), + jsConstLine(t, html, "STAGE_TRACKER_REROUTE_PREFIX"), + jsFunc(t, html, "stageTrackerTakeoverOf"), + jsFunc(t, html, "stageTrackerActionBase"), + jsFunc(t, html, "stageTrackerRerouteTargetOf"), + jsFunc(t, html, "stageTrackerClankerLabel"), + jsFunc(t, html, "stageTrackerRerouteOptions"), + jsFunc(t, html, "stageTrackerTakeoverActions"), + jsFunc(t, html, "stageTrackerReroutePillHtml"), + jsFunc(t, html, "stageTrackerTakeoverTarget"), + jsFunc(t, html, "stageTrackerAdoptNowConfirm"), + jsFunc(t, html, "stageTrackerRerouteConfirm"), + jsFunc(t, html, "stageTrackerRerouteTargetValid"), jsFunc(t, html, "stageTrackerRowActions"), + jsFunc(t, html, "stageTrackerMenuTextHtml"), jsFunc(t, html, "stageTrackerFlatActions"), jsFunc(t, html, "stageTrackerSelectionActions"), jsFunc(t, html, "stageTrackerMenuItemHtml"), diff --git a/src/pkg/dashboard/stage_tracker_takeover.go b/src/pkg/dashboard/stage_tracker_takeover.go new file mode 100644 index 0000000000..e9db9ac12b --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_takeover.go @@ -0,0 +1,228 @@ +package dashboard + +import ( + "github.com/hivecommons/hive/pkg/config" + "slices" + "strings" + "time" + + "github.com/hivecommons/hive/pkg/github/automerge" + "github.com/hivecommons/hive/pkg/stagelabels" +) + +// The operator's takeover actions on a PR waiting on a contributor's +// clanker (hivecommons/hive#15038): a 072 / 071 clanker PR carries +// `takeover` — whether Adopt now and Reroute are offered (and why not), the +// online clankers a reroute can target, a pending reroute ("rerouted → +// @X") and a pending forced adoption. The SPA builds the ⋯ menu items, the +// consequence lines and the pills from it; the needs-human popover lists +// the same two options when the blocker is waiting on the contributor. + +// StageTrackerTakeover is the `takeover` field of a 072 / 071 clanker PR row. +type StageTrackerTakeover struct { + Author string `json:"author,omitempty"` + AuthorOnline bool `json:"author_online"` + // AdoptNow is true when "Adopt now" is offered; AdoptNowReason says why + // not when it is not (adoption disabled, hold label). + AdoptNow bool `json:"adopt_now"` + AdoptNowReason string `json:"adopt_now_reason,omitempty"` + // Reroute is true when at least one other clanker is online and can + // take fix-pr work; RerouteReason is the disabled reason otherwise. + Reroute bool `json:"reroute"` + RerouteReason string `json:"reroute_reason,omitempty"` + Clankers []RerouteCandidate `json:"clankers,omitempty"` + // Rerouted is the live reroute, when one is pending. + Rerouted *StageTrackerRerouted `json:"rerouted,omitempty"` + // ForcedBy / ForcedAt is a pending Adopt now the sweep has not run yet. + ForcedBy string `json:"forced_by,omitempty"` + ForcedAt *time.Time `json:"forced_at,omitempty"` + // FallbackAt is when a reroute's pickup window lapsed and the hive fell + // back to Adopt now. + FallbackAt *time.Time `json:"fallback_at,omitempty"` + // GraceElapsed is true once the author's offline grace has run out + // (adoption is due but something holds it): the delegated "Let hive + // decide" picks Adopt now then. + GraceElapsed bool `json:"grace_elapsed,omitempty"` +} + +// StageTrackerRerouted is a pending reroute on the row. +type StageTrackerRerouted struct { + To string `json:"to"` + By string `json:"by,omitempty"` + Since *time.Time `json:"since,omitempty"` + Reason string `json:"reason,omitempty"` + TargetOnline bool `json:"target_online"` + // Text is the pill: "rerouted → @X". + Text string `json:"text"` +} + +// Row action ids for the takeover actions, in the context menu's +// "decide:" vocabulary. +const ( + decisionActionAdoptNow = "decide:adopt-now" + decisionActionReroute = "decide:reroute" +) + +// takeoverAdoptNowDisabledHold is the Adopt now disabled reason under a hold label. +const takeoverAdoptNowDisabledHold = "release the hold first" + +// takeoverAdoptNowDisabledOff is the reason when adoption is off on this hive. +const takeoverAdoptNowDisabledOff = "adoption is disabled (governor.labels.stage.adoption.enabled)" + +// stageTrackerRerouteCandidates returns the lookup for the online clankers a +// reroute may target, excluding the PR's author. Tests inject +// rerouteCandidates. +func (s *Server) stageTrackerRerouteCandidates() func(author string) []RerouteCandidate { + if s == nil { + return nil + } + if s.rerouteCandidates != nil { + return s.rerouteCandidates + } + if s.contributeHub == nil { + return nil + } + hub := s.contributeHub + return func(author string) []RerouteCandidate { return hub.RerouteCandidates(time.Now(), author) } +} + +// stageTrackerTakeover builds the `takeover` field for a clanker PR row at +// 072 / 071; nil for other rows and for an adopted head. +func stageTrackerTakeover(it StageTrackerItem, rec stagelabels.Record, hasRec bool, presence func(string) (automerge.ContributorPresence, bool), candidates func(string) []RerouteCandidate, adoptionEnabled bool, grace takeoverGrace, now time.Time) *StageTrackerTakeover { + if it.Kind != "pr" || it.AuthorKind == authorKindHuman || (it.Stage != trackerNumberReturned && it.Stage != trackerNumberNeedsAuthor) { + return nil + } + if hasRec && rec.AdoptedHead != "" && (it.Head == "" || rec.Adopted(it.Head) || rec.AdoptedInPlace()) { + return nil + } + out := &StageTrackerTakeover{Author: it.Author} + if presence != nil && it.Author != "" { + if p, ok := presence(it.Author); ok { + out.AuthorOnline = p.Online + } + } + held := slices.Contains(it.Modifiers, modHold) + switch { + case !adoptionEnabled: + out.AdoptNowReason = takeoverAdoptNowDisabledOff + case held: + out.AdoptNowReason = takeoverAdoptNowDisabledHold + default: + out.AdoptNow = true + } + var cands []RerouteCandidate + if candidates != nil { + cands = candidates(it.Author) + } + out.Clankers = cands + switch { + case len(cands) == 0: + out.RerouteReason = RerouteNoneOnlineReason + case held: + out.RerouteReason = takeoverAdoptNowDisabledHold + default: + out.Reroute = true + } + if hasRec { + if to := rec.Rerouted(it.Head); to != "" { + text := "Rerouted to @" + to + if rec.RerouteBy != "" { + text += " by @" + rec.RerouteBy + } + if rec.RerouteReason != "" { + text += " — " + rec.RerouteReason + } + r := &StageTrackerRerouted{To: to, By: rec.RerouteBy, Reason: rec.RerouteReason, Text: text} + if !rec.RerouteAt.IsZero() { + t := rec.RerouteAt + r.Since = &t + } + if presence != nil { + if p, ok := presence(to); ok { + r.TargetOnline = p.Online + } + } + // A live connection on the contribute hub is presence too. + for _, c := range cands { + if strings.EqualFold(c.Login, to) { + r.TargetOnline = true + } + } + out.Rerouted = r + } + if by, ok := rec.AdoptionForced(); ok { + out.ForcedBy = by + if !rec.AdoptForcedAt.IsZero() { + t := rec.AdoptForcedAt + out.ForcedAt = &t + } + } + if !rec.RerouteFallbackAt.IsZero() && out.Rerouted == nil { + t := rec.RerouteFallbackAt + out.FallbackAt = &t + } + out.GraceElapsed = rec.AdoptionBlocked(it.Head) != "" || (it.Adoption != nil && it.Adoption.Due) || grace.elapsed(it.Adoption, now) + } + return out +} + +// takeoverGrace is the configured nudge grace (online / offline) the +// tracker measures the wait against; zero values mean "unknown". +type takeoverGrace struct { + Online, Offline time.Duration +} + +func (s *Server) takeoverGrace() takeoverGrace { + if s == nil || s.deps == nil || s.deps.Config == nil { + return takeoverGrace{Online: config.DefaultContributorGraceOnline, Offline: config.DefaultContributorGraceOffline} + } + stage := s.deps.Config.Governor.Labels.Stage + return takeoverGrace{Online: stage.EffectiveContributorGraceOnline(), Offline: stage.EffectiveContributorGraceOffline()} +} + +// elapsed: the nudge grace that applies to the author's presence has run +// out since the first nudge at this head. +func (g takeoverGrace) elapsed(a *StageTrackerAdoption, now time.Time) bool { + if a == nil || a.Since == nil || a.Since.IsZero() { + return false + } + window := g.Offline + if a.AuthorOnline { + window = g.Online + } + if window <= 0 { + return false + } + return now.Sub(*a.Since) >= window +} + +// takeoverDecisionOptions are the popover options the takeover adds to a +// waiting-on-contributor decision: Adopt now (lead) and Reroute. +func takeoverDecisionOptions(t *StageTrackerTakeover, held bool) []StageTrackerDecisionOption { + if t == nil { + return nil + } + adoptWhy := t.AdoptNowReason + if held && adoptWhy == "" { + adoptWhy = "Release the hold first" + } + rerouteWhy := t.RerouteReason + if held && rerouteWhy == "" { + rerouteWhy = "Release the hold first" + } + return []StageTrackerDecisionOption{ + decisionOption(decisionActionAdoptNow, "Adopt now — hive takes it over", t.AdoptNow && !held, adoptWhy), + decisionOption(decisionActionReroute, "Reroute to another clanker", t.Reroute && !held, rerouteWhy), + } +} + +// stageTrackerTakeoverCaption appends the reroute pill text to the caption. +func stageTrackerTakeoverCaption(caption string, t *StageTrackerTakeover) string { + if t == nil || t.Rerouted == nil { + return caption + } + if strings.Contains(caption, t.Rerouted.Text) { + return caption + } + return caption + " — " + t.Rerouted.Text +} diff --git a/src/pkg/dashboard/stage_tracker_takeover_ui_test.go b/src/pkg/dashboard/stage_tracker_takeover_ui_test.go new file mode 100644 index 0000000000..fc9ae1f2bd --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_takeover_ui_test.go @@ -0,0 +1,247 @@ +package dashboard + +import ( + "strings" + "testing" +) + +// Adopt now / Reroute (hivecommons/hive#15038): a PR waiting on a +// contributor's clanker offers, in its ⋯ menu and in the Needs-human +// popover, "Adopt now — hive takes it over" with its consequence line and +// "Reroute to another clanker" with the online clankers as a submenu (plus +// "any available"); each is disabled with the server's reason; the confirms +// honour the don't-ask-again key; the requests hit the decision API +// (`adopt` + force / `reroute` + to); the toast reads the server's result; +// a rerouted row shows the "rerouted → @x" pill with the presence dot. + +const stageTrackerTakeoverFixture = ` +const clankers = [ + { login: 'Danathar', hive_name: 'danathar-hive', online_since: '2026-10-29T08:00:00Z', load: 1 }, + { login: 'bee2', hive_name: 'bee2#2', online_since: '2026-10-29T09:30:00Z', load: 0 }, +]; +const takeover = { author: 'Danathar', author_online: false, adopt_now: true, reroute: true, clankers, grace_elapsed: true }; +const waiting = { repo: 'hivecommons/hive', kind: 'pr', number: 15038, title: 'Fix the thing', url: 'u15038', stage: 72, stage_slug: 'returned-to-contributor', caption: 'Returned to contributor · waiting on @Danathar', author: 'Danathar', modifiers: [], takeover }; +const nobody = Object.assign({}, waiting, { number: 15039, url: 'u15039', takeover: { author: 'Danathar', adopt_now: true, reroute: false, reroute_reason: 'no clankers online — use Adopt now', clankers: [] } }); +const held = Object.assign({}, waiting, { number: 15040, url: 'u15040', modifiers: ['hold'], takeover: { author: 'Danathar', adopt_now: false, adopt_now_reason: 'release the hold first', reroute: false, reroute_reason: 'release the hold first' } }); +const rerouted = Object.assign({}, waiting, { number: 15041, url: 'u15041', takeover: Object.assign({}, takeover, { rerouted: { to: 'bee2', by: 'clubanderson', since: '2026-10-29T10:00:00Z', reason: 'reviewer requested changes', target_online: true, text: 'Rerouted to @bee2 by @clubanderson 5m ago — reviewer requested changes' } }) }); +const hivePR = { repo: 'hivecommons/hive', kind: 'pr', number: 15042, url: 'u15042', stage: 72, modifiers: [] }; +const issue = { repo: 'hivecommons/hive', kind: 'issue', number: 15000, url: 'u15000', stage: 72, mirrored: true, modifiers: [], linked_prs: [ { number: 15038, title: 'Fix the thing', url: 'u15038', stage: 72, modifiers: [], author: 'Danathar', takeover } ] }; +const ctx = { user: true, canHold: true, canHuman: true, nowMs: Date.parse('2026-10-29T10:00:00Z') }; +const ids = acts => acts.map(a => a.id); +` + +func TestStageTrackerTakeoverMenu(t *testing.T) { + html := indexHTML(t) + for _, want := range []string{ + `'decide:adopt-now': 'Adopt now — hive takes it over', 'decide:reroute': 'Reroute to another clanker',`, + `.ham-badge-reroute {`, `.ham-badge-reroute .ham-presence-dot {`, `.ham-badge-reroute.ham-reroute-online .ham-presence-dot {`, + `.ham-menu-text {`, `.ham-menu-note {`, + `stageTrackerReroutePillHtml(item)`, + `'decide:adopt-now': 'Adopting now…', 'decide:reroute': 'Rerouting…',`, + } { + if !strings.Contains(html, want) { + t.Errorf("index.html missing takeover wiring %q", want) + } + } + runStageTrackerRowActionsScript(t, stageTrackerRowActionsPreamble(t, html)+` +function agentNowAgo(ms) { return Math.round(ms / 60000) + 'm ago'; } +`+stageTrackerTakeoverFixture+` +// The waiting PR's menu: Adopt now (with the consequence line) and Reroute (submenu) sit after Hold. +let acts = stageTrackerRowActions(waiting, ctx); +assert.deepStrictEqual(ids(acts), ['decide:adopt-now', 'decide:reroute', 'hold', 'retry', 'needs-human', 'open', 'copy']); +const adoptNow = acts[0]; +assert.strictEqual(adoptNow.label, 'Adopt now — hive takes it over…'); +assert.strictEqual(adoptNow.note, STAGE_TRACKER_ADOPT_NOW_CONSEQUENCE); +assert.ok(adoptNow.note.indexOf("closes the contributor's PR after hive opens its copy") === 0, adoptNow.note); +assert.ok(adoptNow.note.indexOf('their commits + sign-off are preserved') > 0, adoptNow.note); +assert.strictEqual(adoptNow.enabled, true); assert.strictEqual(adoptNow.danger, true); +const reroute = acts[1]; +assert.strictEqual(reroute.label, 'Reroute to another clanker'); +assert.strictEqual(reroute.enabled, true); +assert.deepStrictEqual(ids(reroute.submenu), ['decide:reroute:Danathar', 'decide:reroute:bee2', 'decide:reroute:any']); +assert.strictEqual(reroute.submenu[0].label, '@Danathar · danathar-hive · online 120m ago · 1 in hand'); +assert.strictEqual(reroute.submenu[1].label, '@bee2 · bee2#2 · online 30m ago · idle'); +assert.strictEqual(reroute.submenu[2].label, 'any available (2 online)'); +assert.ok(reroute.submenu.every(o => o.enabled)); +// The menu markup: the consequence line under the label, the submenu nested. +const menu = stageTrackerMenuHtml(acts, 'hivecommons/hive#15038'); +assert.ok(menu.indexOf('Adopt now — hive takes it over…closes the contributor') >= 0, menu); +assert.ok(menu.indexOf('data-ham-act="decide:reroute" aria-haspopup="menu"') >= 0, menu); +assert.ok(menu.indexOf('data-ham-act="decide:reroute:bee2"') >= 0, menu); +assert.ok(menu.indexOf('data-ham-act="decide:reroute:any"') >= 0, menu); +assert.ok(menu.indexOf('style=') < 0, 'no inline styles'); + +// No clanker online: Reroute is disabled with the server's reason; Adopt now still offered. +acts = stageTrackerRowActions(nobody, ctx); +const noReroute = acts.find(a => a.id === 'decide:reroute'); +assert.strictEqual(noReroute.enabled, false); +assert.strictEqual(noReroute.why, 'no clankers online — use Adopt now'); +assert.ok(noReroute.submenu.every(o => !o.enabled && o.why === 'no clankers online — use Adopt now')); +assert.deepStrictEqual(ids(noReroute.submenu), ['decide:reroute:any']); +assert.strictEqual(acts.find(a => a.id === 'decide:adopt-now').enabled, true); +const noMenu = stageTrackerMenuHtml(acts, ''); +assert.ok(noMenu.indexOf('data-ham-act="decide:reroute" aria-haspopup="menu" aria-expanded="false" tabindex="-1" aria-disabled="true" title="no clankers online — use Adopt now"') >= 0, noMenu); + +// Held: both disabled with "release the hold first". +acts = stageTrackerRowActions(held, ctx); +assert.strictEqual(acts.find(a => a.id === 'decide:adopt-now').why, 'release the hold first'); +assert.strictEqual(acts.find(a => a.id === 'decide:reroute').why, 'release the hold first'); + +// A read-only viewer sees both greyed with the sign-in reason. +acts = stageTrackerRowActions(waiting, { user: false, canHold: false, canHuman: false }); +assert.strictEqual(acts.find(a => a.id === 'decide:adopt-now').why, STAGE_TRACKER_WHY_WRITE); +assert.strictEqual(acts.find(a => a.id === 'decide:reroute').why, STAGE_TRACKER_WHY_WRITE); + +// A hive-authored 072 PR (no takeover) and an issue row offer neither. +assert.deepStrictEqual(ids(stageTrackerRowActions(hivePR, ctx)).filter(id => id.indexOf('decide:adopt-now') === 0 || id.indexOf('decide:reroute') === 0), []); +assert.deepStrictEqual(ids(stageTrackerRowActions(issue, ctx)).filter(id => id.indexOf('decide:adopt-now') === 0 || id.indexOf('decide:reroute') === 0), []); + +// The takeover target: the PR row itself, or the issue's nested PR. +assert.strictEqual(stageTrackerTakeoverTarget(waiting), waiting); +assert.strictEqual(stageTrackerTakeoverTarget(hivePR), null); +_stageTracker = { items: [issue] }; +assert.strictEqual(stageTrackerTakeoverTarget(issue).number, 15038); +assert.strictEqual(stageTrackerTakeoverTarget(issue).takeover, takeover); + +// Action ids: "decide:reroute:" acts as "decide:reroute". +assert.strictEqual(stageTrackerActionBase('decide:reroute:bee2'), 'decide:reroute'); +assert.strictEqual(stageTrackerActionBase('decide:adopt-now'), 'decide:adopt-now'); +assert.strictEqual(stageTrackerRerouteTargetOf('decide:reroute:bee2'), 'bee2'); +assert.strictEqual(stageTrackerRerouteTargetOf('decide:reroute'), ''); +assert.strictEqual(stageTrackerActionLabel('decide:reroute:bee2'), 'Reroute to another clanker'); +assert.strictEqual(stageTrackerActingCaption('decide:reroute:bee2'), 'Rerouting…'); +assert.strictEqual(stageTrackerActingCaption('decide:adopt-now'), 'Adopting now…'); + +// Requests: the decision API, attributed to the operator. +let req = stageTrackerActionRequest(waiting, 'decide:adopt-now', {}); +assert.strictEqual(req.url, '/api/repos/hivecommons/hive/items/15038/decision'); +assert.deepStrictEqual(req.body, { decision: 'adopt', force: true, comment: '', type: 'pr' }); +req = stageTrackerActionRequest(waiting, 'decide:reroute:bee2', { to: 'bee2' }); +assert.deepStrictEqual(req.body, { decision: 'reroute', to: 'bee2', comment: '', type: 'pr' }); +req = stageTrackerActionRequest(waiting, 'decide:reroute:any', {}); +assert.strictEqual(req.body.to, 'any'); +req = stageTrackerActionRequest(waiting, 'decide:reroute', { to: 'Danathar' }); +assert.strictEqual(req.body.to, 'Danathar'); + +// The rerouted pill: target + presence dot; nothing on a plain row. +const pill = stageTrackerReroutePillHtml(rerouted); +assert.ok(pill.indexOf('class="ham-badge ham-badge-reroute ham-reroute-online"') >= 0, pill); +assert.ok(pill.indexOf('rerouted → @bee2') >= 0, pill); +assert.ok(pill.indexOf('title="Rerouted to @bee2 by @clubanderson 5m ago') >= 0, pill); +assert.ok(pill.indexOf('(@bee2 online)') >= 0, pill); +assert.strictEqual(stageTrackerReroutePillHtml(waiting), ''); +const offline = stageTrackerReroutePillHtml(Object.assign({}, rerouted, { takeover: Object.assign({}, rerouted.takeover, { rerouted: Object.assign({}, rerouted.takeover.rerouted, { target_online: false }) }) })); +assert.ok(offline.indexOf('ham-reroute-online') < 0 && offline.indexOf('(@bee2 offline)') >= 0, offline); +// A rerouted row's Reroute item says so. +assert.ok(stageTrackerRowActions(rerouted, ctx).find(a => a.id === 'decide:reroute').note.indexOf('rerouted → @bee2 already') === 0); + +// Toasts: the server's result, the operator's own action (not "Hive decided"). +const adoptedResult = { action: 'adopted', target: { repo: 'hivecommons/hive', kind: 'pr', number: 15038, url: 'u15038' }, outcome: "Adopted → #15050 (hive's copy), contributor PR will close when #15050 merges.", next: "The hive rebases and fixes CI on #15050; the author's commits and sign-off are preserved." }; +let text = stageTrackerResultText(adoptedResult, waiting, { id: 'decide:adopt-now' }); +assert.strictEqual(text.head, 'Adopt now — hive takes it over on hivecommons/hive#15038: adopted'); +assert.strictEqual(text.outcome, "Adopted → #15050 (hive's copy), contributor PR will close when #15050 merges."); +assert.strictEqual(text.type, 'success'); +text = stageTrackerResultText({ action: 'rerouted', target: adoptedResult.target, outcome: 'Rerouted → @bee2 (dispatched now, interrupt).', next: "@bee2's hive fixes the PR or opens a replacement carrying the author's commits and sign-off. If it has not picked the work up within 30m the hive falls back to Adopt now." }, waiting, { id: 'decide:reroute:bee2' }); +assert.strictEqual(text.head, 'Reroute to another clanker on hivecommons/hive#15038: rerouted'); +assert.ok(text.outcome.indexOf('Rerouted → @bee2') === 0, text.outcome); +assert.ok(text.next.indexOf('falls back to Adopt now') > 0, text.next); +// A delegated adoption still reads as the hive's decision. +assert.ok(stageTrackerResultText(Object.assign({ rule: 'grace-elapsed-adopt-now' }, adoptedResult), waiting, { id: 'decide:delegate' }).head.indexOf('Hive decided on') === 0); +console.log('takeover menu ok'); +`) +} + +func TestStageTrackerTakeoverConfirmsAndPopover(t *testing.T) { + html := indexHTML(t) + runStageTrackerRowActionsScript(t, stageTrackerDecisionPopPreamble(t, html)+stageTrackerConfirmOptOutJS(t, html)+stageTrackerTakeoverFixture+` +(async () => { + // Adopt now: a confirm carrying the consequence line and the don't-ask-again box; keyed hive.tracker.confirm.decide:adopt-now. + assert.deepStrictEqual(await stageTrackerActionPayload([waiting], 'decide:adopt-now'), {}); + let d = dialogs.pop(); + assert.strictEqual(d.kind, 'confirm'); assert.strictEqual(d.cfg.title, 'Adopt now'); assert.strictEqual(d.cfg.confirmLabel, 'Adopt now'); + assert.ok(d.cfg.message.indexOf(STAGE_TRACKER_ADOPT_NOW_CONSEQUENCE) > 0, d.cfg.message); + assert.ok(d.cfg.message.indexOf('without waiting for the offline grace window or the maintainer policy') > 0, d.cfg.message); + assert.ok(d.cfg.message.indexOf('clanker is online') < 0, 'offline author: no online line'); + assert.strictEqual(d.cfg.check.label, STAGE_TRACKER_CONFIRM_CHECK_LABEL); + // An online author: the dialog says the comment tells its clanker politely. + await stageTrackerActionPayload([Object.assign({}, waiting, { takeover: Object.assign({}, takeover, { author_online: true }) })], 'decide:adopt-now'); + assert.ok(dialogs.pop().cfg.message.indexOf("The author's clanker is online: the adoption comment tells it, politely") > 0); + // Ticked: the key is stored and the next Adopt now runs without a dialog. + dialogAnswer = { checked: true }; + await stageTrackerActionPayload([waiting], 'decide:adopt-now'); dialogs.length = 0; + assert.strictEqual(store['hive.tracker.confirm.decide:adopt-now'], 'skip'); + assert.deepStrictEqual(await stageTrackerActionPayload([waiting], 'decide:adopt-now'), {}); + assert.strictEqual(dialogs.length, 0, 'skipped confirm raises no dialog'); + dialogAnswer = true; + // Cancelled: null. + dialogAnswer = null; + assert.strictEqual(await stageTrackerActionPayload([waiting], 'decide:reroute:bee2'), null); + dialogAnswer = true; + + // Reroute from the submenu: one confirm (keyed decide:reroute for every target), payload carries the target. + assert.deepStrictEqual(await stageTrackerActionPayload([waiting], 'decide:reroute:bee2'), { to: 'bee2' }); + d = dialogs.pop(); + assert.strictEqual(d.kind, 'confirm'); assert.strictEqual(d.cfg.title, 'Reroute to another clanker'); assert.strictEqual(d.cfg.confirmLabel, 'Reroute'); + assert.ok(d.cfg.message.indexOf("to @bee2's clanker") > 0, d.cfg.message); + assert.ok(d.cfg.message.indexOf('@Danathar is told by comment') > 0, d.cfg.message); + assert.ok(d.cfg.message.indexOf('falls back to Adopt now') > 0, d.cfg.message); + assert.strictEqual(d.cfg.check.label, STAGE_TRACKER_CONFIRM_CHECK_LABEL); + assert.deepStrictEqual(await stageTrackerActionPayload([waiting], 'decide:reroute:any'), { to: 'any' }); + assert.ok(dialogs.pop().cfg.message.indexOf('to any available clanker') > 0); + dialogAnswer = { checked: true }; + await stageTrackerActionPayload([waiting], 'decide:reroute:Danathar'); dialogs.length = 0; + assert.strictEqual(store['hive.tracker.confirm.decide:reroute'], 'skip'); + dialogAnswer = true; + assert.deepStrictEqual(await stageTrackerActionPayload([waiting], 'decide:reroute:bee2'), { to: 'bee2' }); + assert.strictEqual(dialogs.length, 0); + assert.deepStrictEqual(stageTrackerSkippedConfirms().sort(), ['decide:adopt-now', 'decide:reroute']); + stageTrackerResetConfirms(); + + // Reroute from the popover (no target in the id): a required prompt listing the online clankers — never skipped — then the confirm. + dialogAnswer = 'bee2'; + assert.deepStrictEqual(await stageTrackerActionPayload([waiting], 'decide:reroute'), { to: 'bee2' }); + const confirm = dialogs.pop(), prompt = dialogs.pop(); + assert.strictEqual(prompt.kind, 'prompt'); + assert.deepStrictEqual(prompt.cfg.options.map(o => o.value), ['Danathar', 'bee2', 'any']); + assert.strictEqual(prompt.cfg.validate('@bee2'), true); + assert.strictEqual(prompt.cfg.validate('any'), true); + assert.strictEqual(prompt.cfg.validate(''), true); + assert.strictEqual(prompt.cfg.validate('stranger'), '@stranger is not online now — pick a listed clanker or "any"'); + assert.strictEqual(prompt.cfg.check, undefined, 'required input: no opt-out box'); + assert.strictEqual(confirm.kind, 'confirm'); + stageTrackerSetConfirmSkip('decide:reroute', true); + dialogAnswer = ''; + assert.deepStrictEqual(await stageTrackerActionPayload([waiting], 'decide:reroute'), { to: 'any' }, 'an empty answer means any'); + assert.strictEqual(dialogs.length, 1, 'the prompt still shows when the confirm is skipped'); + dialogs.length = 0; dialogAnswer = true; stageTrackerResetConfirms(); + + // The Needs-human popover: the server's waiting-on-contributor options resolve against the row's takeover. + const decision = { question: 'Waiting on @Danathar — adopt now, reroute, or wait?', asked_by: 'the hive', since: '2026-10-29T09:00:00Z', blocker: 'Returned to contributor; the offline grace has elapsed.', + options: [ + { action: 'decide:adopt-now', label: 'Adopt now — hive takes it over', enabled: true }, + { action: 'decide:reroute', label: 'Reroute to another clanker', enabled: true }, + { action: 'decide:delegate', label: 'Let hive decide', enabled: true }, + { action: 'hold', label: 'Hold', enabled: true }, + ] }; + const asked = Object.assign({}, waiting, { modifiers: ['needs-decision'], decision_needed: decision }); + let opts = stageTrackerDecisionOptions(asked, ctx); + assert.deepStrictEqual(opts.map(o => o.id), ['decide:delegate', 'decide:adopt-now', 'decide:reroute', 'hold']); + assert.ok(opts.every(o => o.enabled), JSON.stringify(opts)); + assert.strictEqual(opts[1].danger, true); + // No clanker online: the popover's Reroute is greyed with the reason the server gave. + const askedNobody = Object.assign({}, nobody, { modifiers: ['needs-decision'], decision_needed: Object.assign({}, decision, { options: decision.options.map(o => o.action === 'decide:reroute' ? Object.assign({}, o, { enabled: false, reason_if_disabled: 'no clankers online — use Adopt now' }) : o) }) }); + opts = stageTrackerDecisionOptions(askedNobody, ctx); + assert.strictEqual(opts.find(o => o.id === 'decide:reroute').enabled, false); + assert.strictEqual(opts.find(o => o.id === 'decide:reroute').why, 'no clankers online — use Adopt now'); + assert.strictEqual(opts.find(o => o.id === 'decide:adopt-now').enabled, true); + // The issue row's popover resolves the nested PR's takeover options. + const askedIssue = Object.assign({}, issue, { modifiers: ['needs-decision'], decision_needed: decision }); + _stageTracker = { items: [askedIssue] }; + opts = stageTrackerDecisionOptions(askedIssue, ctx); + assert.strictEqual(opts.find(o => o.id === 'decide:adopt-now').enabled, true, JSON.stringify(opts)); + const pop = stageTrackerDecisionPopHtml(asked, stageTrackerDecisionOptions(asked, ctx), Date.now(), ''); + assert.ok(pop.indexOf('data-ham-act="decide:adopt-now"') >= 0 && pop.indexOf('data-ham-act="decide:reroute"') >= 0, pop); + console.log('takeover confirms ok'); +})().catch(e => { console.error(e); process.exit(1); }); +`) +} diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 3a0ec9e28f..a0932602e2 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -1555,6 +1555,11 @@ @keyframes ham-presence-breathe { 0%, 100% { opacity: 1; } 50% { opacity: 0.55; } } @media (prefers-reduced-motion: reduce) { .ham-presence-online { animation: none; } } .ham-decision-presence { font-size: var(--fs-xs); color: var(--muted); } + /* Reroute pill (hive PR 15038): "● rerouted → @x"; the dot is + the target clanker's presence (online = the ready status token). */ + .ham-badge-reroute { color: var(--status-warn); border-color: color-mix(in srgb, var(--status-warn) 55%, transparent); font-weight: var(--fw-medium); display: inline-flex; align-items: center; gap: var(--sp-1); } + .ham-badge-reroute .ham-presence-dot { width: 0.5em; height: 0.5em; border-radius: var(--r-pill); background: var(--text-faint); flex: 0 0 auto; } + .ham-badge-reroute.ham-reroute-online .ham-presence-dot { background: var(--status-ok); } .ham-strip { list-style: none; margin: 0; padding: 0; display: flex; gap: var(--sp-1); min-height: 18px; flex: 1 1 auto; min-width: 0; --ham-notch: 8px; } .ham-seg { position: relative; flex: 1 1 0; min-width: 0; display: flex; align-items: center; justify-content: center; padding: 0 var(--sp-4) 0 var(--sp-5); font-size: var(--fs-xs); font-weight: var(--fw-medium); white-space: nowrap; overflow: hidden; clip-path: polygon(0 0, calc(100% - var(--ham-notch)) 0, 100% 50%, calc(100% - var(--ham-notch)) 100%, 0 100%, var(--ham-notch) 50%); } .ham-seg:first-child { clip-path: polygon(0 0, calc(100% - var(--ham-notch)) 0, 100% 50%, calc(100% - var(--ham-notch)) 100%, 0 100%); } @@ -1743,6 +1748,8 @@ .ham-menu.ham-menu-hinted { max-width: min(45em, calc(100vw - 2 * var(--sp-3))); } .ham-menu-item.ham-menu-item-hinted { flex-direction: column; align-items: flex-start; gap: var(--sp-1); white-space: normal; } .ham-menu-item .ham-menu-hint { display: block; color: var(--text-faint); font-size: var(--fs-xs); white-space: normal; overflow-wrap: anywhere; } + .ham-menu-text { display: flex; flex-direction: column; align-items: flex-start; min-width: 0; } + .ham-menu-note { font-size: var(--fs-xs); color: var(--text-faint); white-space: normal; } .ham-submenu { display: none; margin: 0 0 0 var(--sp-3); padding-left: var(--sp-2); border-left: var(--line-width) solid var(--line-subtle); } .ham-menu-item[aria-expanded="true"] + .ham-submenu { display: block; } /* tracker-cues: the Activity Monitor's shared cue vocabulary (owner, @@ -14707,6 +14714,68 @@

Where to get help

const tip = stageTrackerPresenceTip(item, Date.now()); return `${stageTrackerPresenceInPillHtml(item, stageTrackerPresenceChipText(item))}`; } + /* Takeover (hivecommons/hive#15038): a PR waiting on a contributor's + clanker (072 returned-to-contributor / 071 needs-author) carries + `takeover` {author, author_online, adopt_now, adopt_now_reason, + reroute, reroute_reason, clankers[], rerouted, grace_elapsed}. The + row menu then offers Adopt now (forced adoption, no grace wait) and + Reroute to another clanker (an online registered contributor hive, + or "any available"); the server disables each with a reason. */ + const STAGE_TRACKER_ADOPT_NOW_CONSEQUENCE = "closes the contributor's PR after hive opens its copy; their commits + sign-off are preserved"; + const STAGE_TRACKER_REROUTE_ANY = 'any'; + const STAGE_TRACKER_REROUTE_PREFIX = 'decide:reroute:'; + function stageTrackerTakeoverOf(item) { + return item && item.kind === 'pr' && item.takeover && typeof item.takeover === 'object' ? item.takeover : null; + } + // Pure: the base action id — "decide:reroute:" acts as "decide:reroute". + function stageTrackerActionBase(id) { + return String(id || '').indexOf(STAGE_TRACKER_REROUTE_PREFIX) === 0 ? 'decide:reroute' : String(id || ''); + } + function stageTrackerRerouteTargetOf(id) { + return String(id || '').indexOf(STAGE_TRACKER_REROUTE_PREFIX) === 0 ? String(id).slice(STAGE_TRACKER_REROUTE_PREFIX.length) : ''; + } + // Pure: one submenu line per online clanker — "@login · hive · online 2h · 1 in hand". + function stageTrackerClankerLabel(c, nowMs) { + const since = Date.parse(c.online_since || ''); + const parts = ['@' + (c.login || '?')]; + if (c.hive_name) parts.push(String(c.hive_name)); + if (since && typeof agentNowAgo === 'function') parts.push('online ' + agentNowAgo((typeof nowMs === 'number' ? nowMs : Date.now()) - since)); + const load = Number(c.load) || 0; + parts.push(load ? load + ' in hand' : 'idle'); + return parts.join(' · '); + } + // Pure: the Reroute submenu — the clankers online now, then "any available". + function stageTrackerRerouteOptions(tk, enabled, why, nowMs) { + const out = (tk && Array.isArray(tk.clankers) ? tk.clankers : []).map(c => ({ id: STAGE_TRACKER_REROUTE_PREFIX + (c.login || ''), label: stageTrackerClankerLabel(c, nowMs), enabled, why, clanker: c })); + out.push({ id: STAGE_TRACKER_REROUTE_PREFIX + STAGE_TRACKER_REROUTE_ANY, label: 'any available' + (out.length ? ' (' + out.length + ' online)' : ''), enabled, why }); + return out; + } + // Pure: the takeover items of a row menu; [] when the row has none. + function stageTrackerTakeoverActions(item, ctx, nowMs) { + const tk = stageTrackerTakeoverOf(item); + if (!tk) return []; + ctx = ctx || {}; + const write = ctx.canHold !== false && !!ctx.user; + const whyWrite = write ? '' : STAGE_TRACKER_WHY_WRITE; + const adoptOk = write && !!tk.adopt_now; + const adoptWhy = adoptOk ? '' : (whyWrite || tk.adopt_now_reason || 'Not available on this row'); + const rerouteOk = write && !!tk.reroute; + const rerouteWhy = rerouteOk ? '' : (whyWrite || tk.reroute_reason || 'Not available on this row'); + return [ + { id: 'decide:adopt-now', label: STAGE_TRACKER_ACTION_LABELS['decide:adopt-now'] + '…', note: STAGE_TRACKER_ADOPT_NOW_CONSEQUENCE, enabled: adoptOk, why: adoptWhy, danger: true }, + { id: 'decide:reroute', label: STAGE_TRACKER_ACTION_LABELS['decide:reroute'], note: tk.rerouted && tk.rerouted.to ? 'rerouted → @' + tk.rerouted.to + ' already; pick again to move it' : (rerouteOk ? 'hands the reviewer\'s requested changes to another online clanker' : ''), enabled: rerouteOk, why: rerouteWhy, submenu: stageTrackerRerouteOptions(tk, rerouteOk, rerouteWhy, nowMs) }, + ]; + } + // Pure: the "rerouted → @x" pill with the target's presence dot; '' when + // the row is not rerouted. + function stageTrackerReroutePillHtml(item) { + const tk = stageTrackerTakeoverOf(item); + const r = tk && tk.rerouted && tk.rerouted.to ? tk.rerouted : null; + if (!r) return ''; + const tip = r.text || ('Rerouted to @' + r.to + (r.by ? ' by @' + r.by : '')); + const presence = r.target_online ? 'online' : 'offline'; + return `rerouted → @${esc(r.to)}`; + } // "Sentinel flagged security-relevant changes at : // " — the sentinel wording for an item's tooltips and aria @@ -15176,7 +15245,7 @@

Where to get help

} function stageTrackerChipsHtml(item) { - const sentinel = stageTrackerSentinelChipHtml(item) + (typeof stageTrackerAdoptionChipHtml === 'function' ? stageTrackerAdoptionChipHtml(item) : '') + (typeof stageTrackerPresenceChipHtml === 'function' ? stageTrackerPresenceChipHtml(item) : ''); + const sentinel = stageTrackerSentinelChipHtml(item) + (typeof stageTrackerAdoptionChipHtml === 'function' ? stageTrackerAdoptionChipHtml(item) : '') + (typeof stageTrackerPresenceChipHtml === 'function' ? stageTrackerPresenceChipHtml(item) : '') + (typeof stageTrackerReroutePillHtml === 'function' ? stageTrackerReroutePillHtml(item) : ''); const mods = (Array.isArray(item.modifiers) ? item.modifiers.slice() : []) .sort((x, y) => STAGE_TRACKER_MOD_PRIORITY.indexOf(x) - STAGE_TRACKER_MOD_PRIORITY.indexOf(y)); if (!mods.length) return sentinel; @@ -15244,6 +15313,7 @@

Where to get help

approve: 'Approve', 'give-direction': 'Give direction', 'close-superseded': 'Close as superseded', wontfix: "Close as won't-fix", 'let-hive-decide': 'Let hive decide', hold: 'Hold', release: 'Release hold', 'accept-triage': 'Accept triage', 'mark-needs-human': 'Mark needs-human', 'merge-now': 'Approve & merge as maintainer', 'queue-merge': 'Approve — let hive merge', + adopt: 'Adopt', 'adopt-now': 'Adopt now', reroute: 'Reroute to another clanker', }; const STAGE_TRACKER_ACTED_STATES = ['waiting', 'addressed', 'stuck', 'pending', 'failed']; const STAGE_TRACKER_ACTED_FILTERS = ['any', 'awaiting', 'acted', 'stuck']; @@ -15327,7 +15397,7 @@

Where to get help

} // Row-menu action id each ledger action was submitted under, so the // option the owner just took is not offered back to them. - const STAGE_TRACKER_ACTED_OPTION_ID = { 'let-hive-decide': 'decide:delegate', approve: 'decide:approve', 'give-direction': 'decide:direction', 'close-superseded': 'decide:close-superseded', wontfix: 'decide:close-wontfix', 'accept-triage': 'accept-triage', hold: 'hold', 'merge-now': 'decide:merge-now', 'queue-merge': 'decide:queue-merge', 're-author': 'decide:re-author' }; + const STAGE_TRACKER_ACTED_OPTION_ID = { 'let-hive-decide': 'decide:delegate', approve: 'decide:approve', 'give-direction': 'decide:direction', 'close-superseded': 'decide:close-superseded', wontfix: 'decide:close-wontfix', 'accept-triage': 'accept-triage', hold: 'hold', 'merge-now': 'decide:merge-now', 'queue-merge': 'decide:queue-merge', 're-author': 'decide:re-author', adopt: 'decide:adopt', 'adopt-now': 'decide:adopt-now', reroute: 'decide:reroute' }; // Pure: what the owner can still do when their action changed nothing // (no-op) or the item has not moved (stuck): the enabled options from // the row's decision_needed payload, minus the one just taken. @@ -15463,7 +15533,7 @@

Where to get help

return { repo: issue.repo, number: lp.number, kind: 'pr', title: lp.title || '', url: lp.url || '', author: lp.author || '', author_kind: lp.author_kind || '', stage: lp.stage || 0, stage_since: lp.stage_since || '', stage_slug: lp.stage_slug || '', modifiers: lp.modifiers || [], deferred_modifiers: lp.deferred_modifiers || [], caption: lp.caption || '', reason: lp.reason || '', human_approver: lp.human_approver || '', manual_merge: !!lp.manual_merge, human_merge_reason: lp.human_merge_reason || '', human_merge_reason_text: lp.human_merge_reason_text || '', sentinel_alert: !!lp.sentinel_alert, sentinel_reason: lp.sentinel_reason || '', head: lp.head || '', base_ref: lp.base_ref || '', decision_needed: lp.decision_needed || null, - adoption: lp.adoption || null, superseded: !!lp.superseded, parent: Number(issue.number) || 0, siblings: open.map(x => Number(x.number) || 0), + adoption: lp.adoption || null, takeover: lp.takeover || null, superseded: !!lp.superseded, parent: Number(issue.number) || 0, siblings: open.map(x => Number(x.number) || 0), last_operator_action: lp.last_operator_action || null, operator_action_count: lp.operator_action_count || 0, hold: lp.hold || null, stage_actor: lp.stage_actor || null, presence: lp.presence || null, merge_gate: lp.merge_gate || null, merge_train: lp.merge_train || null }; } // Pure: whether a linked PR is still open (not merged / closed / superseded). @@ -17185,6 +17255,7 @@

All labels

'decide:adopt': 'Adopt (hive takes over)', 'decide:merge-now': 'Approve & merge as maintainer', 'decide:queue-merge': 'Approve — let hive merge', 'decide:re-author': 'Re-author as hive PR', + 'decide:adopt-now': 'Adopt now — hive takes it over', 'decide:reroute': 'Reroute to another clanker', hold: 'Hold', release: 'Release hold', retry: 'Re-evaluate now', 'accept-triage': 'Accept triage', 'needs-human': 'Mark needs-human', open: 'Open on GitHub', copy: 'Copy link', }; @@ -17471,6 +17542,9 @@

All labels

// A nudged contributor PR the engine would adopt but for the owner's // say-so (maintainer_policy: ask) offers Adopt (hivecommons/hive#14524). if (typeof stageTrackerAdoptOffered === 'function' && stageTrackerAdoptOffered(item)) out.push({ id: 'decide:adopt', label: STAGE_TRACKER_ACTION_LABELS['decide:adopt'] + '…', hint: 'adoption', enabled: write && !!ctx.user, why: write && ctx.user ? '' : STAGE_TRACKER_WHY_WRITE }); + // A PR waiting on a contributor's clanker offers Adopt now and Reroute + // (hivecommons/hive#15038); each disabled with the server's reason. + if (typeof stageTrackerTakeoverActions === 'function') for (const a of stageTrackerTakeoverActions(item, ctx, ctx.nowMs)) out.push(a); out.push(has('hold') ? { id: 'release', label: 'Release hold', enabled: write, why: write ? '' : STAGE_TRACKER_WHY_WRITE } : { id: 'hold', label: 'Hold', enabled: write, why: write ? '' : STAGE_TRACKER_WHY_WRITE }); @@ -17525,16 +17599,21 @@

All labels

function stageTrackerMenuItemHtml(a) { const dis = a.enabled ? '' : ` aria-disabled="true" title="${esc(a.why || '')}"`; if (a.submenu) { - return `${a.sep ? '' : ''}`; + return `${a.sep ? '' : ''}`; } // A hint stacks under the label (ham-menu-item-hinted) and wraps, so // the consequence line never overflows the menu (#15165). - return `${a.sep ? '' : ''}`; + return `${a.sep ? '' : ''}`; } // Pure: true when any action (or submenu action) carries a hint. function stageTrackerMenuHasHints(actions) { return (actions || []).some(a => !!a.hint || (a.submenu && stageTrackerMenuHasHints(a.submenu))); } + // Pure: the label, with its consequence line under it when the action has one. + function stageTrackerMenuTextHtml(a) { + if (!a.note) return esc(a.label); + return `${esc(a.label)}${esc(a.note)}`; + } // Pure: the menu markup (roles menu / menuitem, the Decide group as a // nested menu toggled by its item). A menu with hints is ham-menu-hinted // (wider, hints stacked and wrapping). @@ -17725,6 +17804,9 @@

All labels

const d = item && item.decision_needed; const server = d && Array.isArray(d.options) ? d.options : []; const flat = stageTrackerFlatActions(stageTrackerRowActions(item, ctx || { user: false, canHold: false, canHuman: false })); + // An issue row's popover may name its nested PR's takeover options. + const tkTarget = typeof stageTrackerTakeoverTarget === 'function' ? stageTrackerTakeoverTarget(item) : null; + if (tkTarget && tkTarget !== item) for (const a of stageTrackerTakeoverActions(tkTarget, ctx || { user: false, canHold: false, canHuman: false })) if (!flat[a.id]) flat[a.id] = a; const out = server.map(o => { const c = flat[o.action]; const enabled = !!o.enabled && !!(c && c.enabled); @@ -17929,7 +18011,10 @@

All labels

const html = stageTrackerSelBarHtml(items, stageTrackerSelectionActions(items, stageTrackerActionCtx)); if (bar.innerHTML !== html) bar.innerHTML = html; } - function stageTrackerActionLabel(id) { return STAGE_TRACKER_ACTION_LABELS[id] || id; } + function stageTrackerActionLabel(id) { + const base = typeof stageTrackerActionBase === 'function' ? stageTrackerActionBase(id) : id; + return STAGE_TRACKER_ACTION_LABELS[base] || id; + } // Pure: which endpoint an action hits for one item. `once` marks a // hive-wide call made one time per batch. function stageTrackerActionRequest(item, id, payload) { @@ -17959,6 +18044,13 @@

All labels

if (type !== 'issue' || prs.length < STAGE_TRACKER_DELEGATE_ALL_MIN) return null; return { url: '/api/repos/' + seg + '/items/' + n + '/decide-delegated', body: { type, prs, reason: item.reason || '', caption: item.caption || '', sentinel_reason: item.sentinel_reason || '' }, poll: true }; } + if (id === 'decide:adopt-now') { + return { url: '/api/repos/' + seg + '/items/' + n + '/decision', body: { decision: 'adopt', force: true, comment: payload.comment || '', type } }; + } + if (stageTrackerActionBase(id) === 'decide:reroute') { + const to = payload.to || stageTrackerRerouteTargetOf(id) || STAGE_TRACKER_REROUTE_ANY; + return { url: '/api/repos/' + seg + '/items/' + n + '/decision', body: { decision: 'reroute', to, comment: payload.comment || '', type } }; + } if (id.indexOf('decide:') === 0) { const body = { decision: id.slice('decide:'.length), comment: payload.comment || '', type }; if (payload.supersededBy) body.superseded_by = payload.supersededBy; @@ -18280,9 +18372,45 @@

All labels

const v = await stageTrackerAsk(id, 'prompt', { title: 'Mark needs-human', label: 'Why does ' + refs + ' need a human? (optional)', placeholder: 'Reason', confirmLabel: 'Mark' }); return v == null ? null : { comment: v }; } + case 'decide:adopt-now': { + const online = items.some(it => { const tk = stageTrackerTakeoverOf(it); return tk && tk.author_online; }); + return (await stageTrackerAsk(id, 'confirm', stageTrackerAdoptNowConfirm(refs, who, online, preface))) ? {} : null; + } + case 'decide:reroute': { + // No target yet (the Needs-human popover's option): ask for one — + // required, so this prompt is never skipped — then confirm. + const tk = stageTrackerTakeoverOf(items[0]) || {}; + const options = stageTrackerRerouteOptions(tk, true, '').map(o => ({ value: stageTrackerRerouteTargetOf(o.id), label: o.label })); + const to = await hivePrompt({ title: stageTrackerActionLabel(id), label: 'Which clanker takes ' + refs + ' over? (a login from the list, or "any")', placeholder: STAGE_TRACKER_REROUTE_ANY, defaultValue: STAGE_TRACKER_REROUTE_ANY, options, validate: v => stageTrackerRerouteTargetValid(v, tk), confirmLabel: 'Next' }); + if (to == null) return null; + const target = String(typeof to === 'object' ? to.value : to).replace(/^@/, '').trim() || STAGE_TRACKER_REROUTE_ANY; + return (await stageTrackerAsk(id, 'confirm', stageTrackerRerouteConfirm(refs, who, target, tk))) ? { to: target } : null; + } + } + if (stageTrackerActionBase(id) === 'decide:reroute') { + const target = stageTrackerRerouteTargetOf(id) || STAGE_TRACKER_REROUTE_ANY; + return (await stageTrackerAsk('decide:reroute', 'confirm', stageTrackerRerouteConfirm(refs, who, target, stageTrackerTakeoverOf(items[0])))) ? { to: target } : null; } return {}; } + // Pure: the Adopt now confirm — the consequence line is the message. + function stageTrackerAdoptNowConfirm(refs, who, authorOnline, preface) { + const tail = authorOnline ? ' The author\'s clanker is online: the adoption comment tells it, politely, that the maintainer took the PR over.' : ''; + return { title: 'Adopt now', message: (preface || '') + 'Have the hive adopt ' + refs + ' now as ' + who + ', without waiting for the offline grace window or the maintainer policy? This ' + STAGE_TRACKER_ADOPT_NOW_CONSEQUENCE + '.' + tail, confirmLabel: 'Adopt now', danger: true }; + } + function stageTrackerRerouteConfirm(refs, who, target, tk) { + const any = !target || target === STAGE_TRACKER_REROUTE_ANY; + const toWho = any ? 'any available clanker' : '@' + target + '\'s clanker'; + const author = tk && tk.author ? '@' + tk.author : 'the author'; + return { title: stageTrackerActionLabel('decide:reroute'), message: 'Hand the reviewer\'s requested changes on ' + refs + ' to ' + toWho + ' as ' + who + '? ' + author + ' is told by comment; the target fixes the PR or opens a replacement carrying ' + author + '\'s commits and sign-off. If nobody picks it up within the pickup window the hive falls back to Adopt now.', confirmLabel: 'Reroute' }; + } + // Pure: a reroute target is "any" or a clanker the row lists as online. + function stageTrackerRerouteTargetValid(v, tk) { + const t = String(v || '').replace(/^@/, '').trim(); + if (!t || t === STAGE_TRACKER_REROUTE_ANY) return true; + const list = tk && Array.isArray(tk.clankers) ? tk.clankers : []; + return list.some(c => String(c.login || '').toLowerCase() === t.toLowerCase()) ? true : '@' + t + ' is not online now — pick a listed clanker or "any"'; + } /* Every menu item goes through runRowAction(action, row): it asks what the action needs (in-app dialogs, each skippable per action), marks the affected row(s) as acting, runs the requests, and renders one @@ -18301,14 +18429,16 @@

All labels

'hold': 'Holding…', 'release': 'Releasing hold…', 'retry': 'Re-evaluating…', 'needs-human': 'Marking needs-human…', 'accept-triage': 'Accepting triage…', 'decide:delegate': 'Hive is deciding…', 'decide:delegate-all': 'Hive is deciding each PR…', 'decide:delegate:rerun': 'Hive is deciding again…', 'decide:approve': 'Approving…', 'decide:direction': 'Recording direction…', 'decide:close-superseded': 'Closing…', 'decide:close-wontfix': 'Closing…', 'decide:merge-now': 'Merging…', 'decide:queue-merge': 'Queuing for merge…', 'decide:re-author': 'Queuing re-authoring…', + 'decide:merge-now': 'Merging…', 'decide:queue-merge': 'Queuing for merge…', + 'decide:adopt': 'Adopting…', 'decide:adopt-now': 'Adopting now…', 'decide:reroute': 'Rerouting…', }; const STAGE_TRACKER_ACTION_WORDS = { adopted: 'adopted', approved: 'approved', recommended: 'recommendation only', closed: 'closed', directed: 'direction recorded', refused: 'refused', 'decided-each': 'decided per PR', merged: 'merged', 'queued-for-merge': 'queued for merge', - held: 'held', released: 'hold released', rescanned: 'rescanned', 'triage-accepted': 'triage accepted', 'needs-human': 'marked needs-human', [STAGE_TRACKER_ACTION_NOOP]: 'no change', + held: 'held', released: 'hold released', rescanned: 'rescanned', 'triage-accepted': 'triage accepted', 'needs-human': 'marked needs-human', rerouted: 'rerouted', [STAGE_TRACKER_ACTION_NOOP]: 'no change', [STAGE_TRACKER_ACTION_NO_EFFECT]: "decided, but it hasn't taken effect", }; - function stageTrackerActingCaption(id) { return STAGE_TRACKER_ACTING_CAPTIONS[id] || 'acting…'; } + function stageTrackerActingCaption(id) { return STAGE_TRACKER_ACTING_CAPTIONS[stageTrackerActionBase(id)] || 'acting…'; } // Pure: the state signature a toast / acting row waits to see change. function stageTrackerItemState(it) { if (!it) return ''; @@ -18349,7 +18479,7 @@

All labels

const error = result.action === 'error'; let head; if (error) head = stageTrackerActionLabel(ctx.id || '') + ' failed on ' + rowRef + toward; - else if (result.rule || result.action === 'adopted' || result.action === 'recommended') head = 'Hive decided on ' + rowRef + toward; + else if (result.rule || result.action === 'recommended' || (result.action === 'adopted' && ctx.id !== 'decide:adopt-now')) head = 'Hive decided on ' + rowRef + toward; else head = stageTrackerActionLabel(ctx.id || '') + ' on ' + rowRef + toward; const word = error ? '' : (STAGE_TRACKER_ACTION_WORDS[result.action] || result.action || ''); // The rule in plain words from the glossary, never the bare slug. @@ -18510,6 +18640,9 @@

All labels

} else if (id === 'decide:delegate-all') { // The issue row itself is the request; the server fans out per PR. items = items.filter(it => stageTrackerNestedOpenPRs(it).length >= STAGE_TRACKER_DELEGATE_ALL_MIN); + } else if (id === 'decide:adopt-now' || stageTrackerActionBase(id) === 'decide:reroute') { + // Adopt now / Reroute act on the PR waiting on its contributor (072 / 071). + items = items.map(stageTrackerTakeoverTarget).filter(Boolean); if (!items.length) return { toasts: [], pending: [] }; } else if (id.indexOf('decide:') === 0) { // A row decides its parked PR when it has one (the issue's stage is @@ -18529,6 +18662,16 @@

All labels

const results = await stageTrackerRunActions(items, id, payload, rows); return { toast: results.toasts[0] || null, toasts: results.toasts, pending: results.pending, results }; } + // Pure: the PR a takeover action acts on — the PR row itself, or the + // issue's nested PR waiting on its contributor. + function stageTrackerTakeoverTarget(item) { + if (!item) return null; + if (item.kind === 'pr') return stageTrackerTakeoverOf(item) ? item : null; + for (const lp of (Array.isArray(item.linked_prs) ? item.linked_prs : [])) { + if (lp && lp.takeover) return stageTrackerItemByKey(_stageTracker, stageTrackerItemKey({ repo: item.repo, kind: 'pr', number: lp.number })) || stageTrackerLinkedPRItem(item, lp); + } + return null; + } // Menu / selection bar entry point: items are the clicked or selected rows. async function stageTrackerDoAction(items, id) { return runRowAction(id, items); } diff --git a/src/pkg/delegatedecision/policy.go b/src/pkg/delegatedecision/policy.go index 876901e896..ee90a454c0 100644 --- a/src/pkg/delegatedecision/policy.go +++ b/src/pkg/delegatedecision/policy.go @@ -185,10 +185,19 @@ type Input struct { ReporterTrustHold bool // AdoptionStalled: a contributor PR whose adoption parked at 085. AdoptionStalled bool + // AdoptionGraceElapsed: a contributor PR at 072 whose offline grace + // has run out and whose adoption the engine holds (maintainer policy, + // or nothing moved). The delegate picks Adopt now + // (RuleAdoptNow) rather than wait any longer (hivecommons/hive#15038). + AdoptionGraceElapsed bool // BlockedOnPRClosed: a review-backlog item whose PR closed unmerged. BlockedOnPRClosed bool } +// RuleAdoptNow is the rule name of the grace-elapsed Adopt now decision; +// the dashboard runs it as a forced adoption (Adopt now), not a queued one. +const RuleAdoptNow = "grace-elapsed-adopt-now" + // Decision is what the delegate decided and how to record it. type Decision struct { Verdict Verdict `json:"verdict"` @@ -451,6 +460,14 @@ func decidePR(in Input) Decision { return d } } + if !in.HiveAuthored && in.Kind == KindPR && in.AdoptionGraceElapsed { + text := "adopt now: the offline grace on " + ref + " has already elapsed; adopt in supersede mode at once, preserving the author's commits and sign-off" + return Decision{ + Verdict: VerdictAdoptSupersede, Rule: RuleAdoptNow, Text: text, + Rationale: "the contributor's grace window has run out and nothing moved; waiting longer helps no one (hivecommons/hive#15038)", + Actions: []Action{decisionComment(text), {Kind: ActionAdoptSupersede}}, + } + } if !in.HiveAuthored && !in.ContributorOnline && (in.AdoptionStalled || in.Conflicting || !in.CIGreen || in.DCOMissing) { text := "supersede now: adopt " + ref + " in supersede mode, preserving the author's commits and sign-off; do not wait for the grace deadline" return Decision{ diff --git a/src/pkg/fixqueue/fixqueue.go b/src/pkg/fixqueue/fixqueue.go index 50ec91abac..6fc00bbc22 100644 --- a/src/pkg/fixqueue/fixqueue.go +++ b/src/pkg/fixqueue/fixqueue.go @@ -75,8 +75,18 @@ type Item struct { // (set by Requeue); NotBefore is when an interrupt may retry it. Attempts int NotBefore time.Time + // RerouteFrom is set when the item is not the queue owner's own PR: an + // operator (RerouteBy) rerouted RerouteFrom's returned PR to this + // contributor for RerouteReason. The fix prompt says so and tells the + // contributor to carry the original commits + sign-off. + RerouteFrom string + RerouteBy string + RerouteReason string } +// Rerouted reports whether the item is another author's PR rerouted here. +func (it Item) Rerouted() bool { return it.RerouteFrom != "" } + // Key identifies an item. func (it Item) Key() string { return Key(it.Repo, it.Number) } @@ -419,7 +429,9 @@ func (s *Scheduler) pop(user string, c *contributor, mode Mode) *Dispatch { d := &dispatch{mode: mode, items: map[string]Item{head.Key(): head}} rest := c.queue[:0:0] for _, q := range c.queue[1:] { - if head.Cause.coalescable() && q.Cause == head.Cause { + // A rerouted PR (another author's) never shares a task with the + // owner's own PRs: its prompt differs. + if head.Cause.coalescable() && q.Cause == head.Cause && !head.Rerouted() && !q.Rerouted() { d.items[q.Key()] = q continue } diff --git a/src/pkg/github/automerge/automerge_adopt_now_test.go b/src/pkg/github/automerge/automerge_adopt_now_test.go new file mode 100644 index 0000000000..b59dba64b4 --- /dev/null +++ b/src/pkg/github/automerge/automerge_adopt_now_test.go @@ -0,0 +1,115 @@ +package automerge + +import ( + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/config" +) + +// Adopt now (hivecommons/hive#15038): the operator's forced mark on the +// stage record makes the next pass adopt at once, by supersession, with the +// author's relay online, inside the grace window and under +// maintainer_policy: never — the three things that otherwise hold adoption. +// The marker names the operator (by=@login reason=operator-forced) and the +// note tells an online author the maintainer took over. +func TestAdoptNowBypassesPresenceGraceAndMaintainerPolicy(t *testing.T) { + h, done := newAdoptHarness(t, ContributorNudgeOutcome{Mode: "spawn", Online: true}, maintainerPolicyWith(config.AdoptionMaintainerPolicyNever)) + defer done() + h.adopt.permissions = map[string]string{"mallory": "admin"} + h.adopt.allowMaintainerEdits(7, true) + h.sink.presence = &ContributorPresence{Registered: true, Online: true} + h.observe(adoptPR(7, "aaa"), "check-failing:unit") + key := stageKey("acme", "widget", 7) + labels := []string{"stage/072-returned-to-contributor", "role/contributor", "author/clanker"} + + // Five minutes in, online, maintainer, never: the engine would not touch it. + h.api.reset() + h.clock.advance(5 * time.Minute) + h.observe(adoptPR(7, "aaa", labels...), "check-failing:unit") + if len(h.adopt.pulls) != 0 || len(adoptionComments(h.api)) != 0 { + t.Fatalf("control: adopted without the forced mark: pulls=%d comments=%v", len(h.adopt.pulls), h.api.comments) + } + + // The operator clicks Adopt now: the dashboard notes the forced mark and + // nudges the sweep (adoption/supersede rides along as the request label). + store := h.e.stageStoreOrShared() + store.NoteAdoptionForced(key, "clubanderson", h.clock.now()) + h.api.reset() + h.clock.advance(time.Second) + res := h.observe(adoptPR(7, "aaa", append(labels, "adoption/supersede")...), "check-failing:unit") + if len(h.adopt.pulls) != 1 { + t.Fatalf("Adopt now did not supersede: pulls=%v added=%v", h.adopt.pulls, h.api.added) + } + if got := h.adopt.refs["refs/heads/hive/adopt-7"]; got != "aaa" { + t.Fatalf("adopt branch sha=%q (the author's commits must be carried unchanged)", got) + } + comments := adoptionComments(h.api) + if len(comments) != 1 { + t.Fatalf("adoption comments = %v", h.api.comments) + } + for _, want := range []string{ + "by=@clubanderson reason=operator-forced mode=supersede superseded_by=90 head=aaa", + "@mallory", "a maintainer asked the hive to take it over now rather than wait for your hive, which is online", + "carries your commits (and sign-off) unchanged", "closed automatically once #90 merges", + } { + if !strings.Contains(comments[0], want) { + t.Fatalf("forced adoption comment missing %q:\n%s", want, comments[0]) + } + } + if res.Comments != 1 { + t.Fatalf("res=%+v", res) + } + rec, _ := store.Get(key) + if rec.AdoptedHead != "aaa" || rec.AdoptedBy != 90 || rec.AdoptReason != AdoptReasonOperatorForced { + t.Fatalf("record after Adopt now: %+v", rec) + } + if _, forced := rec.AdoptionForced(); forced { + t.Fatalf("the forced mark must be consumed by the adoption: %+v", rec) + } + if rec.AdoptionBlocked("aaa") != "" { + t.Fatalf("a maintainer-policy block survived the operator's decision: %+v", rec) + } + + // Later passes keep it: never's release rule yields to the operator. + h.api.reset() + h.clock.advance(maintainerPermTTL + time.Minute) + h.observe(adoptPR(7, "aaa", "stage/074-adopted-by-hive", "role/contributor", "author/clanker", "adoption/supersede"), "check-failing:unit") + if rec, _ = store.Get(key); rec.AdoptedHead != "aaa" || rec.AdoptedBy != 90 { + t.Fatalf("operator-forced adoption released under never: %+v", rec) + } +} + +// An offline author gets the offline wording; a hold label still stops it. +func TestAdoptNowOfflineWordingAndHoldStops(t *testing.T) { + h, done := newAdoptHarness(t, ContributorNudgeOutcome{Mode: "comment"}, adoptPolicy()) + defer done() + h.sink.presence = &ContributorPresence{Registered: true, Online: false} + h.observe(adoptPR(7, "aaa"), "check-failing:unit") + key := stageKey("acme", "widget", 7) + labels := []string{"stage/072-returned-to-contributor", "role/contributor", "author/clanker"} + store := h.e.stageStoreOrShared() + store.NoteAdoptionForced(key, "clubanderson", h.clock.now()) + + h.api.reset() + h.clock.advance(time.Minute) + h.observe(adoptPR(7, "aaa", append(labels, "hold")...), "check-failing:unit") + if len(h.adopt.pulls) != 0 { + t.Fatalf("hold did not stop Adopt now: pulls=%v", h.adopt.pulls) + } + if rec, _ := store.Get(key); rec.AdoptForcedBy != "clubanderson" { + t.Fatalf("the forced mark must survive a held pass: %+v", rec) + } + + h.api.reset() + h.clock.advance(time.Minute) + h.observe(adoptPR(7, "aaa", labels...), "check-failing:unit") + comments := adoptionComments(h.api) + if len(h.adopt.pulls) != 1 || len(comments) != 1 { + t.Fatalf("Adopt now after the hold lifted: pulls=%d comments=%v", len(h.adopt.pulls), h.api.comments) + } + if !strings.Contains(comments[0], "reason=operator-forced") || !strings.Contains(comments[0], "rather than wait out the offline grace window") { + t.Fatalf("offline wording: %s", comments[0]) + } +} diff --git a/src/pkg/github/automerge/automerge_contributor_adopt.go b/src/pkg/github/automerge/automerge_contributor_adopt.go index b7dea5f46c..0a4180de70 100644 --- a/src/pkg/github/automerge/automerge_contributor_adopt.go +++ b/src/pkg/github/automerge/automerge_contributor_adopt.go @@ -120,6 +120,10 @@ const ( AdoptReasonRebaseRehome = "rebase-rehome" // AdoptReasonPushRehome recovers an adoption that lost fork push access. AdoptReasonPushRehome = "push-rehome" + // AdoptReasonOperatorForced marks an operator's "Adopt now": adoption + // taken at once by supersession, regardless of the author's presence, + // the grace window and maintainer_policy. The marker carries by=@login. + AdoptReasonOperatorForced = "operator-forced" ) // AdoptionStalledMarker opens the one note posted when an adopted PR is @@ -206,6 +210,11 @@ func adoptReasonText(reason string, grace time.Duration, online bool) string { return "the hive can no longer push to the contributor branch" case AdoptReasonInPlaceStalled: return "the review swarm's finding on this head went unaddressed past the stage dwell and the in-place fix lane only repairs CI" + case AdoptReasonOperatorForced: + if online { + return "a maintainer asked the hive to take it over now rather than wait for your hive, which is online — no fault of yours" + } + return "a maintainer asked the hive to take it over now rather than wait out the offline grace window" } if online { return fmt.Sprintf("CI stayed red for %s after the nudge and the relay nudge went unanswered", formatGrace(grace)) @@ -526,10 +535,21 @@ func adoptionBlockerText(obs stageObservation, rec stagelabels.Record) string { // AdoptionComment is the one note left on the original PR when adopted by // supersession. func AdoptionComment(obs stageObservation, hiveID string, superseding int, reason string, grace time.Duration, online bool) string { + return adoptionCommentBy(obs, nonEmpty(hiveID, "hive"), superseding, reason, grace, online) +} + +// AdoptionForcedComment is the adoption note for an operator's "Adopt now": +// the marker names the operator (by=@login reason=operator-forced) and the +// text tells the author a maintainer took the PR over. +func AdoptionForcedComment(obs stageObservation, by string, superseding int, online bool) string { + return adoptionCommentBy(obs, "@"+strings.TrimPrefix(strings.TrimSpace(by), "@"), superseding, AdoptReasonOperatorForced, 0, online) +} + +func adoptionCommentBy(obs stageObservation, by string, superseding int, reason string, grace time.Duration, online bool) string { return fmt.Sprintf("%s by=%s reason=%s mode=%s superseded_by=%d head=%s -->\n@%s the hive has adopted this PR (`%s`): %s. "+ "It is being finished as #%d, which carries your commits (and sign-off) unchanged; the hive will rebase and fix CI there. "+ "This PR is closed automatically once #%d merges. If you would rather finish it yourself, push a new head here and say so on #%d.", - AdoptionMarkerPrefix, nonEmpty(hiveID, "hive"), reason, stagelabels.AdoptModeSupersede, superseding, obs.HeadSHA, obs.Author, stagelabels.AdoptedByHive.Label(), adoptReasonText(reason, grace, online), superseding, superseding, superseding) + AdoptionMarkerPrefix, by, reason, stagelabels.AdoptModeSupersede, superseding, obs.HeadSHA, obs.Author, stagelabels.AdoptedByHive.Label(), adoptReasonText(reason, grace, online), superseding, superseding, superseding) } // AdoptionInPlaceComment is the one note left when the hive adopts the PR on @@ -586,13 +606,15 @@ func (c *Engine) adoptContributorPR(ctx context.Context, store *stagelabels.Stor return 0, nil } requested := hasLabel(obs.Labels, delegatedecision.LabelAdoptSupersede) + forcedBy, forced := rec.AdoptionForced() + forced = forced && obs.HeadSHA != "" && !(rec.Adopted(obs.HeadSHA) && rec.AdoptedBy > 0) if obs.Lane == stageLaneSelf { // The self-authored sweep also carries trusted-bot PRs // (github-actions and friends): a delegated supersede of one of // those runs like any contributor PR. Only the App's own PR has no // branch to re-home; that request is consumed with one note // instead of a silent no-op every sweep (hivecommons/docs#500). - if !requested { + if !requested && !forced { return 0, nil } if normalizeBotLogin(obs.Author) == normalizeBotLogin(c.transport.AppBotLogin()) { @@ -601,7 +623,12 @@ func (c *Engine) adoptContributorPR(ctx context.Context, store *stagelabels.Stor c.info("stage labels: delegated supersede of a trusted-bot PR on the self-authored lane", "repo", obs.Display, "pr", obs.Number, "author", obs.Author, "head", obs.HeadSHA) } due, reason := adoptionDue(rec, obs.HeadSHA, policy, now, presence, hasPresence) - if requested && obs.HeadSHA != "" && !(rec.Adopted(obs.HeadSHA) && rec.AdoptedBy > 0 && !rec.AdoptionCopyFailed()) { + if forced { + // An operator's "Adopt now" (hivecommons/hive#15038): adopt at + // once by supersession, whatever the author's presence, the grace + // window and maintainer_policy say. Only a hold label stops it. + due, reason = true, AdoptReasonOperatorForced + } else if requested && obs.HeadSHA != "" && !(rec.Adopted(obs.HeadSHA) && rec.AdoptedBy > 0 && !rec.AdoptionCopyFailed()) { // An explicit owner-delegate decision bypasses the nudge/grace and // re-homes a stalled in-place adoption through the same supersede path. due, reason = true, AdoptReasonOperator @@ -613,10 +640,11 @@ func (c *Engine) adoptContributorPR(ctx context.Context, store *stagelabels.Stor c.info("stage labels: adoption due but blocked by label", "repo", obs.Display, "pr", obs.Number, "label", l) return 0, nil } - if c.adoptionRefusedByAdmission(store, key, obs, requested, now) { + if forced { + c.info("stage labels: operator forced adoption; maintainer policy, admission and presence bypassed", "repo", obs.Display, "pr", obs.Number, "author", obs.Author, "by", forcedBy, "online", presence.Online, "policy", policy.maintainerPolicy()) + } else if c.adoptionRefusedByAdmission(store, key, obs, requested, now) { return 0, nil - } - if held, deferred := c.maintainerHoldsAdoption(ctx, obs, policy, requested, now); held || deferred { + } else if held, deferred := c.maintainerHoldsAdoption(ctx, obs, policy, requested, now); held || deferred { if held && !deferred { // Recorded so the activity monitor says why (hivecommons/hive#14524): // under ask the row offers Adopt, under never it names the policy. @@ -645,7 +673,7 @@ func (c *Engine) adoptContributorPR(ctx context.Context, store *stagelabels.Stor grace := adoptionGrace(rec, policy) appLogin := strings.TrimSpace(c.transport.AppBotLogin()) canPushInPlace := false - if policy.AdoptInPlace && !requested { + if policy.AdoptInPlace && !requested && !forced { canPushInPlace = c.canPushToPRBranch(ctx, obs) } dcoRehome := adoptionNeedsDCORehome(obs, canPushInPlace) @@ -689,7 +717,12 @@ func (c *Engine) adoptContributorPR(ctx context.Context, store *stagelabels.Stor return 1, nil } - return c.supersedeAdoptedPR(ctx, store, key, obs, rec, policy, reason, grace, rec.NudgeOnline, dcoRehome, now) + online := rec.NudgeOnline + if forced && hasPresence { + // The forced note tells an online author the maintainer took over. + online = presence.Online + } + return c.supersedeAdoptedPR(ctx, store, key, obs, rec, policy, reason, grace, online, dcoRehome, now) } // AdoptionSelfRefusedMarker stamps the note a delegated supersede of the @@ -731,7 +764,14 @@ func delegatedAdoptionAttempted(before, after stagelabels.Record) bool { } func (c *Engine) supersedeAdoptedPR(ctx context.Context, store *stagelabels.Store, key string, obs stageObservation, rec stagelabels.Record, policy StageLabelPolicy, reason string, grace time.Duration, online bool, dcoRehome bool, now time.Time) (int, error) { - if maintainer, deferred := c.maintainerReleasesAdoption(ctx, obs, policy, now); deferred { + forcedBy := "" + if reason == AdoptReasonOperatorForced { + forcedBy, _ = rec.AdoptionForced() + } + if forcedBy != "" { + // An operator's Adopt now is not released under maintainer_policy: + // never — the person the policy defers to has decided. + } else if maintainer, deferred := c.maintainerReleasesAdoption(ctx, obs, policy, now); deferred { return 0, nil } else if maintainer { // Backstop for every re-home path (dco-rehome, in-place-stalled) @@ -829,7 +869,8 @@ func (c *Engine) supersedeAdoptedPR(ctx context.Context, store *stagelabels.Stor } superseding := created.GetNumber() store.MarkAdopted(key, obs.HeadSHA, superseding, now) - c.info("stage labels: contributor PR adopted", "repo", obs.Display, "pr", number, "head", obs.HeadSHA, "superseded_by", superseding, "branch", branch, "fence", rec.AdoptDiffFence) + store.NoteAdoptReason(key, reason) + c.info("stage labels: contributor PR adopted", "repo", obs.Display, "pr", number, "head", obs.HeadSHA, "superseded_by", superseding, "branch", branch, "fence", rec.AdoptDiffFence, "forced_by", forcedBy) if policy.AdoptSupersedeCloseFirst { // hivecommons/hive#15135: one PR per issue — the original closes @@ -837,6 +878,9 @@ func (c *Engine) supersedeAdoptedPR(ctx context.Context, store *stagelabels.Stor return c.closeSupersededOriginalFirst(ctx, store, key, obs, policy, superseding, reason, rec.AdoptDiffFence, now) } body := AdoptionComment(obs, policy.HiveID, superseding, reason, grace, online) + if forcedBy != "" { + body = AdoptionForcedComment(obs, forcedBy, superseding, online) + } if dcoRehome { body = AdoptionDCORehomeComment(obs, policy.HiveID, superseding) } @@ -1066,7 +1110,10 @@ func (c *Engine) settleAdoption(ctx context.Context, store *stagelabels.Store, k if !ok { return 0, nil } - if maintainer, deferred := c.maintainerReleasesAdoption(ctx, obs, policy, now); deferred { + if rec.AdoptReason == AdoptReasonOperatorForced { + // An operator forced this adoption; maintainer_policy: never does + // not hand it back. + } else if maintainer, deferred := c.maintainerReleasesAdoption(ctx, obs, policy, now); deferred { // No evidence either way: neither re-home nor release this pass. return 0, nil } else if maintainer { diff --git a/src/pkg/github/automerge/automerge_stage_labels.go b/src/pkg/github/automerge/automerge_stage_labels.go index a45ada1446..35559436ba 100644 --- a/src/pkg/github/automerge/automerge_stage_labels.go +++ b/src/pkg/github/automerge/automerge_stage_labels.go @@ -1174,7 +1174,11 @@ func (c *Engine) ApplyStageLabels(ctx context.Context) (StageLabelResult, error) // regardless of author kind or whether a nudge was ever sent. if policy.Adoption && !obs.Merged && hasLabel(obs.Labels, delegatedecision.LabelAdoptSupersede) { before, _ := store.Get(key) - n, err := c.adoptContributorPR(ctx, store, key, obs, policy, ContributorPresence{}, false, now) + // Presence is read so a forced adoption's note can tell an + // online author the maintainer took over; the request itself + // does not depend on it. + presence, hasPresence := c.contributorPresence(ctx, obs.Author) + n, err := c.adoptContributorPR(ctx, store, key, obs, policy, presence, hasPresence, now) result.Comments += n if err != nil && firstErr == nil { firstErr = err diff --git a/src/pkg/stagelabels/store.go b/src/pkg/stagelabels/store.go index 02d1745d87..d11bea0d9a 100644 --- a/src/pkg/stagelabels/store.go +++ b/src/pkg/stagelabels/store.go @@ -213,6 +213,24 @@ type Record struct { AdmittedHead string `json:"admitted_head,omitempty"` AdmittedBy string `json:"admitted_by,omitempty"` AdmittedAt time.Time `json:"admitted_at,omitempty"` + // AdoptForcedBy / AdoptForcedAt record an operator's "Adopt now": the + // login that forced adoption and when. The next sweep adopts by + // supersession at once, regardless of the author's presence and of + // maintainer_policy; the attempt clears it (MarkAdopted). + AdoptForcedBy string `json:"adopt_forced_by,omitempty"` + AdoptForcedAt time.Time `json:"adopt_forced_at,omitempty"` + // RerouteTo / RerouteBy / RerouteAt / RerouteReason record an + // operator's "Reroute to another clanker": the PR's follow-up work was + // offered to RerouteTo's queue instead of waiting on the author. + // RerouteHead is the head the reroute was issued for; a new head (the + // target or the author pushed) ends the reroute. RerouteFallbackAt is + // when the pickup window lapsed and the hive fell back to Adopt now. + RerouteTo string `json:"reroute_to,omitempty"` + RerouteBy string `json:"reroute_by,omitempty"` + RerouteAt time.Time `json:"reroute_at,omitempty"` + RerouteReason string `json:"reroute_reason,omitempty"` + RerouteHead string `json:"reroute_head,omitempty"` + RerouteFallbackAt time.Time `json:"reroute_fallback_at,omitempty"` // DCORepairHead is the in-place-adopted head whose unsigned hive // commits the hive last rewrote with its sign-off on the contributor // branch (hivecommons/hive#14666); one attempt per head. @@ -1118,6 +1136,8 @@ func (s *Store) MarkAdopted(key, head string, by int, now time.Time) { r.AdoptedHead, r.AdoptedBy, r.AdoptedAt, r.AdoptCheckedAt = head, by, now, now r.AdoptMode = AdoptModeSupersede r.AdoptBlockedHead, r.AdoptBlockedBy, r.AdoptBlockedAt = "", "", time.Time{} + r.AdoptForcedBy, r.AdoptForcedAt = "", time.Time{} + r.RerouteTo, r.RerouteBy, r.RerouteAt, r.RerouteReason, r.RerouteHead = "", "", time.Time{}, "", "" s.items[key] = r s.dirty = true } @@ -1295,6 +1315,82 @@ func (r Record) Admission(head string) string { return r.AdmittedBy } +// NoteAdoptionForced records an operator's "Adopt now" by login at now. The +// pending reroute (if any) is dropped: a forced adoption supersedes it. +func (s *Store) NoteAdoptionForced(key, login string, now time.Time) { + s.mu.Lock() + defer s.mu.Unlock() + r, ok := s.items[key] + if !ok || login == "" { + return + } + r.AdoptForcedBy, r.AdoptForcedAt = login, now + r.RerouteTo, r.RerouteBy, r.RerouteAt, r.RerouteReason, r.RerouteHead = "", "", time.Time{}, "", "" + s.items[key] = r + s.dirty = true +} + +// ClearAdoptionForced forgets a forced adoption (it was attempted). +func (s *Store) ClearAdoptionForced(key string) { + s.mu.Lock() + defer s.mu.Unlock() + r, ok := s.items[key] + if !ok || r.AdoptForcedBy == "" { + return + } + r.AdoptForcedBy, r.AdoptForcedAt = "", time.Time{} + s.items[key] = r + s.dirty = true +} + +// AdoptionForced reports the operator who forced adoption of this PR and +// whether that force is still pending (no attempt recorded yet). +func (r Record) AdoptionForced() (string, bool) { + return r.AdoptForcedBy, r.AdoptForcedBy != "" +} + +// NoteReroute records that by rerouted the PR's follow-up work at head to +// login for reason. +func (s *Store) NoteReroute(key, head, login, by, reason string, now time.Time) { + s.mu.Lock() + defer s.mu.Unlock() + r, ok := s.items[key] + if !ok || login == "" { + return + } + r.RerouteTo, r.RerouteBy, r.RerouteAt, r.RerouteReason, r.RerouteHead = login, by, now, reason, head + r.RerouteFallbackAt = time.Time{} + s.items[key] = r + s.dirty = true +} + +// ClearReroute ends a reroute (picked up, head moved, adopted, or fallen +// back). fallback stamps RerouteFallbackAt so the row can say the pickup +// window lapsed. +func (s *Store) ClearReroute(key string, fallback bool, now time.Time) { + s.mu.Lock() + defer s.mu.Unlock() + r, ok := s.items[key] + if !ok || r.RerouteTo == "" { + return + } + r.RerouteTo, r.RerouteBy, r.RerouteAt, r.RerouteReason, r.RerouteHead = "", "", time.Time{}, "", "" + if fallback { + r.RerouteFallbackAt = now + } + s.items[key] = r + s.dirty = true +} + +// Rerouted reports the clanker login the PR's work at head is currently +// rerouted to, or "" (no reroute, or the head has moved since). +func (r Record) Rerouted(head string) string { + if r.RerouteTo == "" || (head != "" && r.RerouteHead != "" && r.RerouteHead != head) { + return "" + } + return r.RerouteTo +} + // NoteAdoptReason records why the current adoption happened (the marker's // reason=) on an existing record. func (s *Store) NoteAdoptReason(key, reason string) { diff --git a/src/pkg/stagelabels/takeover_test.go b/src/pkg/stagelabels/takeover_test.go new file mode 100644 index 0000000000..fa71646fdb --- /dev/null +++ b/src/pkg/stagelabels/takeover_test.go @@ -0,0 +1,96 @@ +package stagelabels + +import ( + "path/filepath" + "testing" + "time" +) + +// An operator's Adopt now / Reroute (hivecommons/hive#15038) is recorded on +// an existing record only; a forced adoption drops a pending reroute, a +// pickup fallback stamps when the window lapsed, and a moved head ends the +// reroute. +func TestStoreTakeover(t *testing.T) { + now := time.Date(2026, 10, 28, 20, 0, 0, 0, time.UTC) + st := NewStore(filepath.Join(t.TempDir(), "s.json"), func() time.Time { return now }) + key := Key("hivecommons/hive", 15038) + + // Unknown key or empty login: no-op, no record created. + st.NoteAdoptionForced(key, "op", now) + st.NoteReroute(key, "aaa", "bee2", "op", "address review", now) + st.ClearAdoptionForced(key) + st.ClearReroute(key, true, now) + if _, ok := st.Get(key); ok { + t.Fatal("takeover notes created a record") + } + st.Observe(key, ReturnedToContributor, "waiting on @danathar") + st.NoteAdoptionForced(key, "", now) + st.NoteReroute(key, "aaa", "", "op", "r", now) + r, _ := st.Get(key) + if by, ok := r.AdoptionForced(); ok || by != "" || r.Rerouted("aaa") != "" { + t.Fatalf("empty login must not record: %+v", r) + } + // Clearing what is not there is a no-op. + st.ClearAdoptionForced(key) + st.ClearReroute(key, true, now) + if r, _ = st.Get(key); !r.RerouteFallbackAt.IsZero() { + t.Fatal("ClearReroute on a non-rerouted record stamped a fallback") + } + + // Reroute: recorded for the head, read back per head. + st.NoteReroute(key, "aaa", "bee2", "op", "address review", now) + r, _ = st.Get(key) + if r.Rerouted("aaa") != "bee2" || r.Rerouted("") != "bee2" || r.RerouteBy != "op" || r.RerouteReason != "address review" || !r.RerouteAt.Equal(now) { + t.Fatalf("reroute: %+v", r) + } + if r.Rerouted("bbb") != "" { + t.Fatal("a moved head must end the reroute") + } + + // Forced adoption drops the pending reroute. + st.NoteAdoptionForced(key, "op", now.Add(time.Minute)) + r, _ = st.Get(key) + by, ok := r.AdoptionForced() + if !ok || by != "op" || !r.AdoptForcedAt.Equal(now.Add(time.Minute)) { + t.Fatalf("forced: %+v", r) + } + if r.Rerouted("aaa") != "" || r.RerouteTo != "" || r.RerouteHead != "" { + t.Fatalf("forced adoption must drop the reroute: %+v", r) + } + st.ClearAdoptionForced(key) + if r, _ = st.Get(key); r.AdoptForcedBy != "" || !r.AdoptForcedAt.IsZero() { + t.Fatalf("clear forced: %+v", r) + } + + // Reroute again; a fallback clear stamps RerouteFallbackAt, a plain + // clear (picked up) does not. + st.NoteReroute(key, "aaa", "bee3", "op", "", now) + st.ClearReroute(key, false, now.Add(2*time.Minute)) + r, _ = st.Get(key) + if r.RerouteTo != "" || !r.RerouteFallbackAt.IsZero() { + t.Fatalf("picked-up clear: %+v", r) + } + st.NoteReroute(key, "aaa", "bee3", "op", "", now) + st.ClearReroute(key, true, now.Add(31*time.Minute)) + r, _ = st.Get(key) + if r.RerouteTo != "" || !r.RerouteFallbackAt.Equal(now.Add(31*time.Minute)) { + t.Fatalf("fallback clear: %+v", r) + } + // A fresh reroute forgets the old fallback stamp. + st.NoteReroute(key, "bbb", "bee2", "op", "", now) + if r, _ = st.Get(key); !r.RerouteFallbackAt.IsZero() || r.Rerouted("bbb") != "bee2" { + t.Fatalf("re-reroute: %+v", r) + } + + // Persisted and reloaded. + if err := st.Save(); err != nil { + t.Fatal(err) + } + st2 := NewStore(st.path, func() time.Time { return now }) + if err := st2.Load(); err != nil { + t.Fatal(err) + } + if r, _ = st2.Get(key); r.Rerouted("bbb") != "bee2" || r.RerouteBy != "op" { + t.Fatalf("reloaded: %+v", r) + } +}