From 6cff0fa2f60d228ee9fc54a99008e3ab162a18ec Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Wed, 28 Oct 2026 13:00:24 -0400 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20Adoption:=20maintainer=5Fpolicy=20a?= =?UTF-8?q?dopt|ask|never=20(default=20adopt);=20072=20row=20says=20why=20?= =?UTF-8?q?and=20offers=20Adopt?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit hivecommons/hive#14524 (hanthor, XXL, stage/072, nudged twice, 26h, hive offline) was never adopted: every sweep logged "author maintains the repository; not adopting" and nothing in the UI said so. Owner decision (2026-10-28): clanker PRs are adoptable on disconnect regardless of the owner's repo role. - config: governor.labels.stage.adoption.maintainer_policy adopt|ask|never, default adopt. adopt never reads the role; ask holds a maintainer's PR for an owner and records author-is-maintainer on the stage record; never is the previous rule (hold + release). Human-authored PRs stay unadopted under all three (the 072 machinery is clanker-only). - engine: maintainerHoldsAdoption / maintainerReleasesAdoption route the five authorMaintainsRepo call sites through the policy; the owner's adoption/supersede request lifts the ask hold. - tracker: every nudged 072 PR row carries adoption{author, due, blocked_by, since, nudges, author_online, author_registered, author_last_seen, author_maintainer, policy, action, text} from the stage record and the same hub presence the adoption uses; caption and an amber pill read "waiting on @hanthor (maintainer, offline 26h) — adopt?" instead of a bare "must act". - decision API: decision "adopt" (PR only, write, adoption enabled) posts an attributed note, sets adoption/supersede, audits repo_item_decision_adopt; SPA row action decide:adopt in the same decide:* vocabulary with an in-app confirm. - Settings → Labels three-way selector with one-line explanations. - tests (config, store, engine policy branches, tracker payload/text/ caption, decision API, governor API, SPA helpers), docs, changelog. Signed-off-by: Andrew Anderson --- GOVERNANCE.md | 2 + .../added-adoption-maintainer-policy.md | 1 + src/cmd/hive/merge_eligibility.go | 1 + src/docs/api-reference.md | 32 +- src/docs/contributor-relay.md | 2 + src/docs/dashboard-sections.md | 2 + src/docs/labels-and-control-signals.md | 17 + src/docs/operator-reference.md | 14 +- .../config/adoption_maintainer_policy_test.go | 25 ++ src/pkg/config/config.go | 35 ++ .../config/testdata/agent_runtime_golden.json | 3 +- src/pkg/dashboard/api_governor.go | 26 +- src/pkg/dashboard/api_repo_item_decision.go | 59 ++- src/pkg/dashboard/server.go | 4 + src/pkg/dashboard/stage_tracker.go | 20 +- src/pkg/dashboard/stage_tracker_adoption.go | 206 +++++++++++ .../dashboard/stage_tracker_adoption_test.go | 339 ++++++++++++++++++ src/pkg/dashboard/stage_tracker_decision.go | 39 ++ src/pkg/dashboard/static/index.html | 70 +++- .../automerge_adopt_maintainer_policy_test.go | 187 ++++++++++ .../automerge_adopt_maintainer_test.go | 41 ++- .../automerge/automerge_contributor_adopt.go | 97 +++-- .../automerge/automerge_stage_labels.go | 5 + src/pkg/stagelabels/adoption_blocked_test.go | 77 ++++ src/pkg/stagelabels/store.go | 55 +++ 25 files changed, 1295 insertions(+), 64 deletions(-) create mode 100644 changelog.d/added-adoption-maintainer-policy.md create mode 100644 src/pkg/config/adoption_maintainer_policy_test.go create mode 100644 src/pkg/dashboard/stage_tracker_adoption.go create mode 100644 src/pkg/dashboard/stage_tracker_adoption_test.go create mode 100644 src/pkg/github/automerge/automerge_adopt_maintainer_policy_test.go create mode 100644 src/pkg/stagelabels/adoption_blocked_test.go diff --git a/GOVERNANCE.md b/GOVERNANCE.md index 52e2e4dc36..7a78ab7414 100644 --- a/GOVERNANCE.md +++ b/GOVERNANCE.md @@ -18,6 +18,8 @@ Current maintainers: Routine changes use lazy consensus through GitHub review. Maintainers may merge when CI and review expectations are satisfied, DCO sign-off is present, and no unresolved objection remains. +A maintainer's role does not shield their hive's work from the hive's stand-in rule: clanker PRs are adoptable on disconnect regardless of the owner's repo role (a PR a contributor's hive opened is adopted like any other when that hive goes away; `governor.labels.stage.adoption.maintainer_policy`, default `adopt`). + ## Decision process 1. Proposals are opened as GitHub issues or pull requests. diff --git a/changelog.d/added-adoption-maintainer-policy.md b/changelog.d/added-adoption-maintainer-policy.md new file mode 100644 index 0000000000..faec098a8f --- /dev/null +++ b/changelog.d/added-adoption-maintainer-policy.md @@ -0,0 +1 @@ +- `governor.labels.stage.adoption.maintainer_policy: adopt | ask | never` (default **adopt**) replaces the hard-coded "author maintains the repository; not adopting" rule: clanker PRs are adoptable on disconnect regardless of the owner's repo role (owner decision on [#14524](https://github.com/hivecommons/hive/pull/14524), a maintainer's `author/clanker` PR left 26h at 072 with its hive offline). `ask` parks a maintainer's PR for an owner — the activity monitor row reads "waiting on @author (maintainer, offline 26h) — adopt?" and offers **Adopt** (`decide:adopt` → decision API `adopt`, which sets `adoption/supersede`); `never` is the previous behaviour. Every nudged 072 PR row now carries `adoption{due, blocked_by, since, nudges, author_online, …}` and a plain-words caption/pill; Settings → Labels gets the three-way selector. diff --git a/src/cmd/hive/merge_eligibility.go b/src/cmd/hive/merge_eligibility.go index 12a0cc8422..72117450ca 100644 --- a/src/cmd/hive/merge_eligibility.go +++ b/src/cmd/hive/merge_eligibility.go @@ -118,6 +118,7 @@ func stageLabelPolicyFunc(cfg *config.Config) func() automerge.StageLabelPolicy AdoptInPlace: stage.Adoption.InPlaceEnabled(), AdoptionStrictAttribution: stage.Adoption.StrictAttributionEnabled(), AdoptionAutoMerge: stage.Adoption.AutoMergeEnabled(), + AdoptionMaintainerPolicy: stage.Adoption.EffectiveMaintainerPolicy(), HiveID: cfg.HiveID, AuthorKindLabels: cfg.Governor.Labels.Author.Names(), RelayKnown: contributorRelayKnown, diff --git a/src/docs/api-reference.md b/src/docs/api-reference.md index 8015fe2abd..5ce6900014 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:42` | | `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:43` | | `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:64` | -| `GET` | `/api/health` | Public | Basic health probe | `pkg/dashboard/server.go:1522` | -| `GET` | `/api/health/deep` | Public | Deep health probe | `pkg/dashboard/server.go:1523` | -| `GET` | `/api/livez` | Public | Kubernetes liveness probe | `pkg/dashboard/server.go:1524` | -| `GET` | `/metrics` | Registered only when `HIVE_METRICS_ENABLED`; requires `Authorization: ****** (403 if the token is unset) | Prometheus metrics | `pkg/dashboard/server.go:1530` | -| `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:1535` | -| `GET` | `/api/status/summary` | Dashboard auth/session | Compact agent/governor/budget status summary for pollers; honors `Accept-Encoding: gzip` | `pkg/dashboard/server.go:1536` | -| `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:1537` | -| `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:1538` | -| `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:1539` | -| `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:1540` | -| `GET` | `/api/events` | Dashboard auth/session | Server-sent event stream | `pkg/dashboard/server.go:1541` | +| `GET` | `/api/health` | Public | Basic health probe | `pkg/dashboard/server.go:1526` | +| `GET` | `/api/health/deep` | Public | Deep health probe | `pkg/dashboard/server.go:1527` | +| `GET` | `/api/livez` | Public | Kubernetes liveness probe | `pkg/dashboard/server.go:1528` | +| `GET` | `/metrics` | Registered only when `HIVE_METRICS_ENABLED`; requires `Authorization: ****** (403 if the token is unset) | Prometheus metrics | `pkg/dashboard/server.go:1534` | +| `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:1539` | +| `GET` | `/api/status/summary` | Dashboard auth/session | Compact agent/governor/budget status summary for pollers; honors `Accept-Encoding: gzip` | `pkg/dashboard/server.go:1540` | +| `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:1541` | +| `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:1542` | +| `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:1543` | +| `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:1544` | +| `GET` | `/api/events` | Dashboard auth/session | Server-sent event stream | `pkg/dashboard/server.go:1545` | | `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:44` | -| `GET` | `/branding/custom.css` | Dashboard auth/session | Operator branding stylesheet override, read per request (see [branding](branding.md)) | `pkg/dashboard/server.go:1602` | +| `GET` | `/branding/custom.css` | Dashboard auth/session | Operator branding stylesheet override, read per request (see [branding](branding.md)) | `pkg/dashboard/server.go:1606` | | `GET` | `/api/snapshot/frame-ancestors` | Public | Snapshot framing allowlist | `pkg/dashboard/api.go:77` | | `GET` | `/api/snapshot` | Public | Snapshot data | `pkg/dashboard/api.go:78` | | `GET` | `/snapshot` | Public | Public read-only snapshot page | `pkg/dashboard/api.go:79` | @@ -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:1542` | -| `POST` | `/api/github-app/install-clicked` | Dashboard auth/session | GitHub App Install Clicked | `pkg/dashboard/server.go:1543` | -| `GET` | `/gh-setup` | Public | GitHub App Setup Callback | `pkg/dashboard/server.go:1544` | +| `POST` | `/api/github-app/recheck` | Dashboard auth/session | GitHub App Recheck | `pkg/dashboard/server.go:1546` | +| `POST` | `/api/github-app/install-clicked` | Dashboard auth/session | GitHub App Install Clicked | `pkg/dashboard/server.go:1547` | +| `GET` | `/gh-setup` | Public | GitHub App Setup Callback | `pkg/dashboard/server.go:1548` | ## Configuration @@ -594,7 +594,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:1549` | +| `GET` | `/sso` | Public | SSO | `pkg/dashboard/server.go:1553` | ## Hub SaaS diff --git a/src/docs/contributor-relay.md b/src/docs/contributor-relay.md index 6a060eb469..42734cd263 100644 --- a/src/docs/contributor-relay.md +++ b/src/docs/contributor-relay.md @@ -1261,6 +1261,8 @@ That last line types a fresh prompt into a pane whose CLI is still mid-turn, int **A blip is not an abandonment until the grace window says so.** The re-adoption check above is zero-width for a `1006`: the hub processes the dead socket the instant its read fails, while the relay does not even start redialing for `BASE_RECONNECT_DELAY_MS` (1 s). So on a real network blip the release always won the race, and every blip wrote an `abandoned_disconnect` run row plus a "released: connection lost" activity row for a task that resumed one second later — 11 phantom rows across 17 completed tasks in one 3.5-hour run ([#7838](https://github.com/hivecommons/hive/issues/7838)). The visible booking now waits `HIVE_CONTRIBUTE_DISCONNECT_GRACE` (default 5 s); at the deadline the hub re-runs the re-adoption check and also asks whether a completion/failure row has since been written for the task id, and writes nothing if either is true. The short release cooldown — the double-assign hedge — is still booked immediately and still withdrawn by the resume, so the window is covered either way. +**Who wrote the PR does not change the stand-in rule.** Clanker PRs are adoptable on disconnect regardless of the owner's repo role: once the nudge window passes with the contributor's hive gone, the hub's hive adopts a maintainer's `author/clanker` PR exactly as it adopts anyone else's (`governor.labels.stage.adoption.maintainer_policy`, default `adopt`; `ask` parks it for an owner's Adopt, `never` opts out). + **The lease has to outlive the hub process.** Leases used to live only in the hub's memory, so a restart — which self-upgrade rolls ([#5391](https://github.com/hivecommons/hive/issues/5391)) make routine rather than rare — emptied the registry while every relay carried on working. After the roll *no* in-flight resume could match, and each one produced the same four lines above, this time for a reason the relay could do nothing about ([#5681](https://github.com/hivecommons/hive/issues/5681)). Observed 2026-09-02: revoked at 14:24:40, the same issue reassigned to the same relay at 14:24:44, discarding two and a half minutes of a turn that was progressing normally. The registry is now written to `/data/contributors/task-leases.json` (owner-only) on every assignment, renewal and release, and read back at startup, so a restart is just a longer-than-usual disconnect. This does not loosen who may claim what. The restored record is one the *hub itself* wrote, and a resume is matched against it exactly as before; a lease whose window has already passed is dropped at startup rather than restored. diff --git a/src/docs/dashboard-sections.md b/src/docs/dashboard-sections.md index 3a3798457a..cc7e6a4b1d 100644 --- a/src/docs/dashboard-sections.md +++ b/src/docs/dashboard-sections.md @@ -677,6 +677,8 @@ Fed by `GET /api/stage-tracker`. Every issue and pull request follows the same p | `needs human` (`needs-human` label) | merge gate | PR at stage/080 or later; always on an issue at its own stage | | `needs human decision` (`needs-decision` labels on another stage) | merge gate | PR at stage/080 or later; always on an issue at its own stage | +**Adoption pill (072).** A nudged `author/clanker` pull request at `stage/072-returned-to-contributor` carries `adoption{author, due, blocked_by, since, nudges, author_online, author_registered, author_last_seen, author_maintainer, policy, action, text}` — the nudge count and first-nudge time from the stage record, the author's live hub presence (the same lookup the contributor-offline adoption itself consults), and, when the adoption engine judged adoption due and held it, why (`blocked_by: author-is-maintainer`). The row's caption and an amber pill say it in plain words instead of a bare "Returned to contributor": `waiting on @hanthor (maintainer, offline 26h) — adopt?` under `governor.labels.stage.adoption.maintainer_policy: ask`, `waiting on @zoe (offline 40m, 2 nudges)` while the default `adopt` policy's clock runs, `… — not adopted: maintainer_policy is never` under `never` ([hivecommons/hive#14524](https://github.com/hivecommons/hive/pull/14524): the PR sat 26h at 072 with its author's hive gone and nothing on screen saying why). When `action` is `decide:adopt` the row also carries `decision_needed` (question "@hanthor maintains this repository and has been offline for 26h; adopt the PR?", `blocker_reason: adoption:author-is-maintainer`, options Adopt then Hold/Release), so the lit 072 chevron and the `adopt?` pill open the Needs-human popover, and the row menu and the selection bar offer **Adopt (hive takes over)** — same action-id vocabulary as the other `decide:*` entries — which, after an in-app confirm, POSTs `{"decision":"adopt"}` to the item's decision endpoint: the hive posts an attributed note, sets `adoption/supersede` (the owner-delegate's request label) and the next sweep adopts the head on the existing adopt/supersede path; the toast reads `adoption-queued`. Write access required; the action is absent when nothing is the owner's to decide. + **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. **Hive's own unblock is live.** When the blocked sweep or the review-backlog block reconciler lifts `blocked` itself (the tracked PR merged or closed; the `` note), it takes the same path as an inbound label webhook: the tracker cache is dropped and the issue is queued for the targeted re-read (`ItemPatches` delivery `self:edit`), which patches the status row and the governor's cached snapshot at once. A reconcile enumeration that was already listing when the unblock happened used to overwrite that patch with its pre-unblock copy, and the rows reverted to `blocked` until the next pass (~an hour on the hive's hive); the governor now replays re-reads newer than the listing's start onto the pass's result before publishing it, so a row never moves backwards behind a read it has already made. diff --git a/src/docs/labels-and-control-signals.md b/src/docs/labels-and-control-signals.md index 1dcc14e700..b01c3d1780 100644 --- a/src/docs/labels-and-control-signals.md +++ b/src/docs/labels-and-control-signals.md @@ -886,6 +886,23 @@ When a clanker-authored contributor PR goes red the hive does not just relabel i (hivecommons/hive#12527: the author's relay was polling for work during the nudge and dropped off 30 minutes later; a snapshot-based grace kept the PR at 072 indefinitely). The marker records which rule fired: + The author's repository role does not change this. **Clanker PRs are + adoptable on disconnect regardless of the owner's repo role** + (`governor.labels.stage.adoption.maintainer_policy`, default `adopt`; + owner decision 2026-10-28 on hivecommons/hive#14524, where a + maintainer's own `author/clanker` PR sat at 072 for 26h with its hive + gone while every sweep logged "author maintains the repository; not + adopting"): a PR a contributor's hive opened is the hive's to stand in + for when that hive goes away, whoever owns the account. `ask` holds a + maintainer's PR for an owner's decision instead — the stage record + notes `author-is-maintainer`, the activity monitor row reads + "waiting on @author (maintainer, offline 26h) — adopt?" and its menu + offers **Adopt**, which sets `adoption/supersede` (the owner-delegate's + own request label) so the next sweep adopts as `contributor-offline`; + `never` is the earlier hands-off rule (projectbluefin/utah-packages#619): + never adopt, and release an existing adoption of a maintainer's head. + Under every setting a human-authored PR (no `author/clanker`) is never + adopted. - `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 eec7d71bb0..be0add7481 100644 --- a/src/docs/operator-reference.md +++ b/src/docs/operator-reference.md @@ -650,7 +650,19 @@ on) — judged against live hub presence each sweep: relay offline for heartbeat, no contributor profile here for `adoption.after_unregistered` (default 2h) since the first nudge, or online but silent for `contributor_grace_online` (default 2h; `contributor_grace_offline`, 15m, when -the hub reports no presence). `hold`/`do-not-merge` blocks adoption. When the +the hub reports no presence). `hold`/`do-not-merge` blocks adoption. The +author's repository role does not: clanker PRs are adoptable on disconnect +regardless of the owner's repo role +(`governor.labels.stage.adoption.maintainer_policy`, default `adopt`; owner +decision on hivecommons/hive#14524 — the PR a contributor's hive opened is the +hive's to stand in for when that hive disconnects, maintainer or not). +`ask` holds a maintainer's PR for an owner: the activity monitor row says +"waiting on @author (maintainer, offline 26h) — adopt?" and offers **Adopt** +(decision API `adopt`, which sets `adoption/supersede` for the next sweep); +`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 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/adoption_maintainer_policy_test.go b/src/pkg/config/adoption_maintainer_policy_test.go new file mode 100644 index 0000000000..b6d9d91909 --- /dev/null +++ b/src/pkg/config/adoption_maintainer_policy_test.go @@ -0,0 +1,25 @@ +package config + +import "testing" + +// governor.labels.stage.adoption.maintainer_policy (hivecommons/hive#14524): +// adopt by default — clanker PRs are adoptable on disconnect regardless of +// the owner's repo role — with ask and never as opt-outs; anything else +// falls back to the default. +func TestStageAdoptionMaintainerPolicy(t *testing.T) { + if DefaultAdoptionMaintainerPolicy != AdoptionMaintainerPolicyAdopt { + t.Fatalf("default = %q, want adopt (owner decision 2026-10-28)", DefaultAdoptionMaintainerPolicy) + } + for in, want := range map[string]string{ + "": "adopt", "adopt": "adopt", " ADOPT ": "adopt", + "ask": "ask", "Ask": "ask", "never": "never", " never\n": "never", + "always": "adopt", "no": "adopt", + } { + if got := (StageAdoptionConfig{MaintainerPolicy: in}).EffectiveMaintainerPolicy(); got != want { + t.Errorf("EffectiveMaintainerPolicy(%q) = %q, want %q", in, got, want) + } + } + if len(AdoptionMaintainerPolicies) != 3 { + t.Fatalf("policies = %v", AdoptionMaintainerPolicies) + } +} diff --git a/src/pkg/config/config.go b/src/pkg/config/config.go index 6611ec328f..1c3db54e9f 100644 --- a/src/pkg/config/config.go +++ b/src/pkg/config/config.go @@ -2827,6 +2827,41 @@ type StageAdoptionConfig struct { // requiring the original author's trust tier. nil = true. Off, an // adopted PR by an untrusted contributor waits for a human /lgtm. AutoMerge *bool `yaml:"auto_merge,omitempty"` + // MaintainerPolicy says what adoption does when the PR's author holds + // admin or maintain on the repository (hivecommons/hive#14524): + // AdoptionMaintainerPolicyAdopt (default) ignores the role — a + // clanker PR whose hive disconnected is adopted like any other; + // AdoptionMaintainerPolicyAsk never adopts on its own but parks the + // question with the owner (an Adopt action in the activity monitor); + // AdoptionMaintainerPolicyNever is the pre-#14524 rule: the hive never + // takes a maintainer's PR over and releases any adoption of one. + MaintainerPolicy string `yaml:"maintainer_policy,omitempty"` +} + +// Values for governor.labels.stage.adoption.maintainer_policy. +const ( + AdoptionMaintainerPolicyAdopt = "adopt" + AdoptionMaintainerPolicyAsk = "ask" + AdoptionMaintainerPolicyNever = "never" + // DefaultAdoptionMaintainerPolicy: clanker PRs are adoptable on + // disconnect regardless of the author's repository role (owner + // decision 2026-10-28, hivecommons/hive#14524). + DefaultAdoptionMaintainerPolicy = AdoptionMaintainerPolicyAdopt +) + +// AdoptionMaintainerPolicies lists the accepted values, default first. +var AdoptionMaintainerPolicies = []string{AdoptionMaintainerPolicyAdopt, AdoptionMaintainerPolicyAsk, AdoptionMaintainerPolicyNever} + +// EffectiveMaintainerPolicy normalises MaintainerPolicy; empty or unknown +// reads as the default (adopt). +func (c StageAdoptionConfig) EffectiveMaintainerPolicy() string { + v := strings.ToLower(strings.TrimSpace(c.MaintainerPolicy)) + for _, p := range AdoptionMaintainerPolicies { + if v == p { + return p + } + } + return DefaultAdoptionMaintainerPolicy } // IsEnabled reports whether adoption runs (default on). diff --git a/src/pkg/config/testdata/agent_runtime_golden.json b/src/pkg/config/testdata/agent_runtime_golden.json index aa64f4c425..e04a7a1ec2 100644 --- a/src/pkg/config/testdata/agent_runtime_golden.json +++ b/src/pkg/config/testdata/agent_runtime_golden.json @@ -201,7 +201,8 @@ "AfterUnregistered": "", "InPlace": null, "StrictAttribution": null, - "AutoMerge": null + "AutoMerge": null, + "MaintainerPolicy": "" }, "Stalled": { "RequireQuiet": null diff --git a/src/pkg/dashboard/api_governor.go b/src/pkg/dashboard/api_governor.go index 770279c758..d8a8c98f92 100644 --- a/src/pkg/dashboard/api_governor.go +++ b/src/pkg/dashboard/api_governor.go @@ -12,6 +12,7 @@ import ( "os" "path/filepath" "regexp" + "slices" "sort" "strconv" "strings" @@ -160,8 +161,12 @@ func (s *Server) handleGovernorConfigGet(w http.ResponseWriter, r *http.Request) "stagePresenceWindow": cfg.Governor.Labels.Stage.PresenceWindow, // governor.labels.stage.adoption.enabled / contributor_grace_*: the // stage-074 adoption of red contributor PRs. - "stageAdoptionEnabled": cfg.Governor.Labels.Stage.Adoption.IsEnabled(), - "stageStalledRequireQuiet": cfg.Governor.Labels.Stage.Stalled.IsRequireQuiet(), + "stageAdoptionEnabled": cfg.Governor.Labels.Stage.Adoption.IsEnabled(), + // governor.labels.stage.adoption.maintainer_policy: adopt | ask | + // never, what adoption does when the author maintains the + // repository (hivecommons/hive#14524). + "stageAdoptionMaintainerPolicy": cfg.Governor.Labels.Stage.Adoption.EffectiveMaintainerPolicy(), + "stageStalledRequireQuiet": cfg.Governor.Labels.Stage.Stalled.IsRequireQuiet(), // governor.labels.stage.engine.mode: the ADR-0025 central stage // engine's rollout switch (off | shadow | enforce). "stageEngineMode": cfg.Governor.Labels.Stage.Engine.EffectiveMode().String(), @@ -794,9 +799,11 @@ func (s *Server) handleGovernorLabels(w http.ResponseWriter, r *http.Request) { StagePresenceWindow *string `json:"stage_presence_window"` // Stage-074 adoption: governor.labels.stage.adoption.enabled and // governor.labels.stage.contributor_grace_online / _offline. - StageAdoptionEnabled *bool `json:"stage_adoption_enabled"` - StageGraceOnline *string `json:"stage_grace_online"` - StageGraceOffline *string `json:"stage_grace_offline"` + StageAdoptionEnabled *bool `json:"stage_adoption_enabled"` + // governor.labels.stage.adoption.maintainer_policy (adopt | ask | never). + StageAdoptionMaintainerPolicy *string `json:"stage_adoption_maintainer_policy"` + StageGraceOnline *string `json:"stage_grace_online"` + StageGraceOffline *string `json:"stage_grace_offline"` // governor.labels.stage.stalled.require_quiet (hivecommons/hive#12534). StageStalledRequireQuiet *bool `json:"stage_stalled_require_quiet"` // governor.labels.stage.engine.mode (ADR-0025): off | shadow | enforce. @@ -923,6 +930,12 @@ func (s *Server) handleGovernorLabels(w http.ResponseWriter, r *http.Request) { return } } + if body.StageAdoptionMaintainerPolicy != nil { + if v := strings.ToLower(strings.TrimSpace(*body.StageAdoptionMaintainerPolicy)); v != "" && !slices.Contains(config.AdoptionMaintainerPolicies, v) { + jsonError(w, "stage_adoption_maintainer_policy must be one of "+strings.Join(config.AdoptionMaintainerPolicies, ", "), http.StatusBadRequest) + return + } + } if body.Labels != nil { filtered := make([]string, 0, len(*body.Labels)) @@ -1009,6 +1022,9 @@ func (s *Server) handleGovernorLabels(w http.ResponseWriter, r *http.Request) { v := *body.StageAdoptionEnabled s.deps.Config.Governor.Labels.Stage.Adoption.Enabled = &v } + if body.StageAdoptionMaintainerPolicy != nil { + s.deps.Config.Governor.Labels.Stage.Adoption.MaintainerPolicy = strings.ToLower(strings.TrimSpace(*body.StageAdoptionMaintainerPolicy)) + } if body.StageGraceOnline != nil { s.deps.Config.Governor.Labels.Stage.ContributorGraceOnline = strings.TrimSpace(*body.StageGraceOnline) } diff --git a/src/pkg/dashboard/api_repo_item_decision.go b/src/pkg/dashboard/api_repo_item_decision.go index ed2c918bea..04bc21d59f 100644 --- a/src/pkg/dashboard/api_repo_item_decision.go +++ b/src/pkg/dashboard/api_repo_item_decision.go @@ -9,6 +9,7 @@ import ( "strconv" "strings" + "github.com/hivecommons/hive/pkg/delegatedecision" ghpkg "github.com/hivecommons/hive/pkg/github" "github.com/hivecommons/hive/pkg/review" ) @@ -39,6 +40,16 @@ import ( // (and, when given, the superseding PR), then a not_planned close (a PR // takes the supersession sweep's own labelled close path). // +// // - adopt → on a PR only: the owner's answer to "the author +// +// maintains this repository; adopt it?" that +// governor.labels.stage.adoption.maintainer_policy: ask parks a nudged +// contributor PR with (hivecommons/hive#14524). One attributed comment, +// then the `adoption/supersede` request label — the same path the +// owner-delegate's adopt-supersede verdict takes — so the adoption +// engine's next pass adopts the head (in place or by supersession) +// exactly as it would a contributor who went offline. +// // Authorisation is the repo-hold bar (canToggleRepoHold): a verified owner, // or a signed-in GitHub user with write on the repository — which is exactly // the permission the un-park sweep checks on a commenter. @@ -47,6 +58,7 @@ const ( repoItemDecisionDirection = "direction" repoItemDecisionCloseSuperseded = "close-superseded" repoItemDecisionCloseWontFix = "close-wontfix" + repoItemDecisionAdopt = "adopt" repoItemDecisionMaxBody = 16 << 10 repoItemDecisionMaxComment = 4000 @@ -54,6 +66,13 @@ const ( auditRepoItemDecisionApprove = "repo_item_decision_approve" auditRepoItemDecisionDirection = "repo_item_decision_direction" auditRepoItemDecisionClose = "repo_item_decision_close" + auditRepoItemDecisionAdopt = "repo_item_decision_adopt" + + // repoItemDecisionAdoptMarker opens the attributed note an Adopt + // decision leaves on the PR. + repoItemDecisionAdoptMarker = "\n@%s asked the hive to adopt this pull request: its author maintains the repository and their hive has been offline since the nudge, so adoption waited for an owner's decision (`governor.labels.stage.adoption.maintainer_policy: ask`). The adoption engine takes it from here on its next pass; the author's commits and sign-off are kept.", repoItemDecisionAdoptMarker, user, user) + if comment != "" { + body += "\n\n> " + strings.ReplaceAll(comment, "\n", "\n> ") } + return body } // handlePullRequestDecision answers approve / direction on a pull request. diff --git a/src/pkg/dashboard/server.go b/src/pkg/dashboard/server.go index a72d811565..448923a4ae 100644 --- a/src/pkg/dashboard/server.go +++ b/src/pkg/dashboard/server.go @@ -30,6 +30,7 @@ import ( "github.com/hivecommons/hive/pkg/dashboard/webstatic" "github.com/hivecommons/hive/pkg/fleetreport" "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/github/automerge" "github.com/hivecommons/hive/pkg/hiveadvisor" spoke "github.com/hivecommons/hive/pkg/hub/spoke" "github.com/hivecommons/hive/pkg/planning" @@ -119,6 +120,9 @@ type Server struct { // stageStore is the stage-label memory /api/stage-tracker reads; nil // means the process-wide stagelabels.Shared(). Tests inject one. stageStore *stagelabels.Store + // presenceLookup overrides the contribute hub as the tracker's author + // presence source for 072 rows (stage_tracker_adoption.go); tests only. + presenceLookup func(login string) (automerge.ContributorPresence, bool) // 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 2f50e24e85..b2f901d014 100644 --- a/src/pkg/dashboard/stage_tracker.go +++ b/src/pkg/dashboard/stage_tracker.go @@ -393,6 +393,11 @@ type StageTrackerItem struct { NudgeCount int `json:"nudge_count,omitempty"` LastNudgeAt *time.Time `json:"last_nudge_at,omitempty"` AdoptedBy int `json:"adopted_by,omitempty"` + // Adoption is, on a nudged PR at stage/072, whether adoption is due, + // what holds it, and the author's live presence, with the plain-words + // line the row shows instead of a bare "Returned to contributor" + // (hivecommons/hive#14524). + Adoption *StageTrackerAdoption `json:"adoption,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"` @@ -475,6 +480,8 @@ type StageTrackerLinkedPR struct { // DecisionNeeded mirrors the nested PR's own row field so the issue's // sub-row can open the same "Needs human" popover. DecisionNeeded *StageTrackerDecision `json:"decision_needed,omitempty"` + // Adoption mirrors the nested PR's own row field (hivecommons/hive#14524). + Adoption *StageTrackerAdoption `json:"adoption,omitempty"` } // Stage numbers the tracker lays out by. Pinned to stagelabels.Table in @@ -1526,6 +1533,7 @@ func (s *Server) buildStageTracker(status *StatusPayload, store *stagelabels.Sto } return store.Get(stagelabels.Key(repo, number)) } + presence, maintainerPolicy := s.stageTrackerPresence(), s.stageTrackerMaintainerPolicy() 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 @@ -1585,6 +1593,13 @@ func (s *Server) buildStageTracker(status *StatusPayload, store *stagelabels.Sto it.Modifiers = slices.DeleteFunc(it.Modifiers, func(m string) bool { return m == modNeedsTriage }) } it.Caption, it.Actor = stageTrackerCaption(stage, it.Reason, it.Author, it.Kind, it.Mirrored, rec, hasRec, it.LinkedPR, it.Head) + // Adoption is clanker-only (a human's PR is never adopted), so a + // human-authored 072 row keeps its plain caption. + if stage == stagelabels.ReturnedToContributor && it.Kind == "pr" && it.AuthorKind != authorKindHuman { + if it.Adoption = stageTrackerAdoption(*it, rec, hasRec, presence, maintainerPolicy, now); it.Adoption != nil { + it.Caption = stageTrackerAdoptionCaption(it.Caption, it.Adoption) + } + } base, approver := stagelabels.HumanApprovedReason(it.Reason) it.HumanApprover = approver it.ManualMerge = stageTrackerManualMergeReason(base) @@ -1666,7 +1681,7 @@ func (s *Server) buildStageTracker(status *StatusPayload, store *stagelabels.Sto it.LinkedPRs = append(it.LinkedPRs, StageTrackerLinkedPR{Number: lp.Number, URL: lp.URL}) } } - it.DecisionNeeded = stageTrackerDecisionNeeded(it, nil, sentinelLabel) + it.DecisionNeeded = stageTrackerDecisionNeededAt(it, nil, sentinelLabel, now) add(it) } addPR := func(repoName string, pr github.PullRequest, verdict *github.MergeVerdict, bucket, bucketReason string) { @@ -1721,7 +1736,7 @@ func (s *Server) buildStageTracker(status *StatusPayload, store *stagelabels.Sto if a, ok := verdictFor(repoName, pr.Number, pr.HeadSHA); ok { agg = &a } - it.DecisionNeeded = stageTrackerDecisionNeeded(it, agg, sentinelLabel) + it.DecisionNeeded = stageTrackerDecisionNeededAt(it, agg, sentinelLabel, now) add(it) } for _, repo := range status.Repos { @@ -2475,6 +2490,7 @@ func stageTrackerResolveLinkedPRs(items []StageTrackerItem) { lp.Title, lp.Author, lp.AuthorKind, lp.Stage = pr.Title, pr.Author, pr.AuthorKind, pr.Stage lp.StageSince, lp.Caption = pr.StageSince, pr.Caption lp.SentinelAlert, lp.SentinelReason, lp.Head = pr.SentinelAlert, pr.SentinelReason, pr.Head + lp.Adoption = pr.Adoption lp.HumanApprover, lp.ManualMerge = pr.HumanApprover, pr.ManualMerge lp.HumanMergeReason, lp.HumanMergeReasonText = pr.HumanMergeReason, pr.HumanMergeReasonText lp.BaseRef = pr.BaseRef diff --git a/src/pkg/dashboard/stage_tracker_adoption.go b/src/pkg/dashboard/stage_tracker_adoption.go new file mode 100644 index 0000000000..5f012117d0 --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_adoption.go @@ -0,0 +1,206 @@ +package dashboard + +import ( + "context" + "fmt" + "strings" + "time" + + "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/github/automerge" + "github.com/hivecommons/hive/pkg/stagelabels" +) + +// The 072 adoption state on a tracker row (hivecommons/hive#14524: PR +// #14524 sat at stage/072 for 26h, nudged twice, its author's hive gone, +// while every cycle logged "author maintains the repository; not +// adopting" and nothing in the UI said so). A nudged contributor PR +// carries `adoption`: whether the engine found adoption due, what holds it +// (`blocked_by`), since when the author has been nudged, how many nudges +// went out, and the author's live hub presence — read through the same +// presence source the contributor-offline adoption itself consults +// (automerge.ContributorPresenceSource, the contribute hub). When the hold +// is the owner's to lift, `action` names the row action that lifts it +// under the context menu's own id vocabulary ("decide:adopt"). + +// StageTrackerAdoption is the `adoption` field of a 072 row. +type StageTrackerAdoption struct { + // Author is the PR author the row waits on (the nested PR's, not the + // issue's, when the row is an issue carrying its covering PR). + Author string `json:"author,omitempty"` + // Due is true once the adoption engine judged adoption due at the + // current head and held it (BlockedBy says why). + Due bool `json:"due"` + // BlockedBy is the hold reason ("author-is-maintainer"), "" when the + // engine holds nothing. + BlockedBy string `json:"blocked_by,omitempty"` + // Since is when the author was first nudged at this head. + Since *time.Time `json:"since,omitempty"` + // Nudges counts the nudges sent for the head. + Nudges int `json:"nudges"` + // AuthorOnline / AuthorRegistered are the author's live hub presence; + // AuthorLastSeen the freshest heartbeat (zero when never seen). + AuthorOnline bool `json:"author_online"` + AuthorRegistered bool `json:"author_registered"` + AuthorLastSeen *time.Time `json:"author_last_seen,omitempty"` + // AuthorMaintainer is true when the hold reason is the author's + // repository role. + AuthorMaintainer bool `json:"author_maintainer,omitempty"` + // Policy is the live governor.labels.stage.adoption.maintainer_policy. + Policy string `json:"policy,omitempty"` + // Action is the row action that lifts the hold ("decide:adopt"), "" + // when nothing is the owner's to decide. + Action string `json:"action,omitempty"` + // Text is the plain-words pill/tooltip: "waiting on @hanthor + // (maintainer, offline 26h) — adopt?". + Text string `json:"text"` +} + +// 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" + +// stageTrackerPresence returns the live presence lookup the tracker uses +// for 072 rows: the contribute hub when the server has one. Tests inject +// presenceLookup. +func (s *Server) stageTrackerPresence() func(login string) (automerge.ContributorPresence, bool) { + if s == nil { + return nil + } + if s.presenceLookup != nil { + return s.presenceLookup + } + if s.contributeHub == nil { + return nil + } + hub := s.contributeHub + return func(login string) (automerge.ContributorPresence, bool) { + return hub.Presence(context.Background(), login), true + } +} + +// stageTrackerMaintainerPolicy is the live maintainer policy ("adopt" when +// the config is unreadable). +func (s *Server) stageTrackerMaintainerPolicy() string { + if s == nil || s.deps == nil || s.deps.Config == nil { + return config.DefaultAdoptionMaintainerPolicy + } + return s.deps.Config.Governor.Labels.Stage.Adoption.EffectiveMaintainerPolicy() +} + +// stageTrackerAdoption builds the `adoption` field for a PR row at +// stage/072 from its stage record and the author's live presence; nil +// when the row was never nudged at its current head (nothing to adopt +// yet) or is already adopted. +func stageTrackerAdoption(it StageTrackerItem, rec stagelabels.Record, hasRec bool, presence func(login string) (automerge.ContributorPresence, bool), policy string, now time.Time) *StageTrackerAdoption { + if it.Kind != "pr" || !hasRec || rec.NudgeCount == 0 || rec.NudgeStart().IsZero() { + return nil + } + if it.Head != "" && rec.NudgeHead != "" && rec.NudgeHead != it.Head { + // The head moved since the nudge: the 072 clock restarts on the + // next sweep; nothing to say about adoption yet. + return nil + } + if rec.AdoptedHead != "" && (it.Head == "" || rec.Adopted(it.Head) || rec.AdoptedInPlace()) { + return nil + } + since := rec.NudgeStart() + out := &StageTrackerAdoption{Author: it.Author, Since: &since, Nudges: rec.NudgeCount, Policy: policy} + if presence != nil && it.Author != "" { + if p, ok := presence(it.Author); ok { + out.AuthorOnline, out.AuthorRegistered = p.Online, p.Registered + if !p.LastSeen.IsZero() { + t := p.LastSeen + out.AuthorLastSeen = &t + } + } + } + head := it.Head + if head == "" { + head = rec.NudgeHead + } + if by := rec.AdoptionBlocked(head); by != "" { + out.Due, out.BlockedBy = true, by + out.AuthorMaintainer = by == stagelabels.AdoptBlockedAuthorMaintainer + if by == stagelabels.AdoptBlockedAuthorMaintainer && policy == config.AdoptionMaintainerPolicyAsk { + out.Action = decisionActionAdopt + } + } + out.Text = stageTrackerAdoptionText(it.Author, *out, now) + return out +} + +// stageTrackerAdoptionText is the plain-words pill/tooltip for a 072 row: +// +// waiting on @hanthor (maintainer, offline 26h) — adopt? +// waiting on @hanthor (offline 40m, 2 nudges) — adoption due in a moment +// waiting on @hanthor (online, 1 nudge) +func stageTrackerAdoptionText(author string, a StageTrackerAdoption, now time.Time) string { + who := "the author" + if author != "" { + who = "@" + author + } + var facts []string + if a.AuthorMaintainer { + facts = append(facts, "maintainer") + } + if a.AuthorOnline { + facts = append(facts, "online") + } else { + facts = append(facts, "offline"+stageTrackerAdoptionOfflineFor(a, now)) + } + if a.Nudges > 0 && !(a.Due && a.BlockedBy != "") { + facts = append(facts, plural(a.Nudges, "nudge")) + } + text := "waiting on " + who + " (" + strings.Join(facts, ", ") + ")" + switch { + case a.BlockedBy == stagelabels.AdoptBlockedAuthorMaintainer && a.Policy == config.AdoptionMaintainerPolicyAsk: + text += " — adopt?" + case a.BlockedBy == stagelabels.AdoptBlockedAuthorMaintainer: + text += " — not adopted: maintainer_policy is never" + case a.BlockedBy != "": + text += " — not adopted: " + a.BlockedBy + } + return text +} + +// stageTrackerAdoptionOfflineFor renders " 26h" for the time the author's +// hive has been gone: since its last heartbeat when one is known and later +// than the first nudge, else since the first nudge. +func stageTrackerAdoptionOfflineFor(a StageTrackerAdoption, now time.Time) string { + var from time.Time + if a.Since != nil { + from = *a.Since + } + if a.AuthorLastSeen != nil && a.AuthorLastSeen.After(from) { + from = *a.AuthorLastSeen + } + if from.IsZero() || !now.After(from) { + return "" + } + d := now.Sub(from) + switch { + case d >= 48*time.Hour: + return fmt.Sprintf(" %dd", int(d/(24*time.Hour))) + case d >= time.Hour: + return fmt.Sprintf(" %dh", int(d/time.Hour)) + default: + return fmt.Sprintf(" %dm", max(1, int(d/time.Minute))) + } +} + +// stageTrackerAdoptionCaption folds the adoption line into the 072 caption: +// "Returned to @hanthor — waiting on @hanthor (maintainer, offline 26h) — +// adopt?" replaces the bare "@hanthor must act (2 nudges sent)". +func stageTrackerAdoptionCaption(caption string, a *StageTrackerAdoption) string { + if a == nil || a.Text == "" { + return caption + } + // Only the trailing "— @x must act (N nudges sent)" clause is replaced; + // the reason clause before it ("review swarm requested changes") stays. + head := caption + if i := strings.LastIndex(caption, " — "); i >= 0 && strings.Contains(caption[i:], " must act") { + head = caption[:i] + } + return head + " — " + a.Text +} diff --git a/src/pkg/dashboard/stage_tracker_adoption_test.go b/src/pkg/dashboard/stage_tracker_adoption_test.go new file mode 100644 index 0000000000..971a50c48b --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_adoption_test.go @@ -0,0 +1,339 @@ +package dashboard + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/delegatedecision" + "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/github/automerge" + "github.com/hivecommons/hive/pkg/stagelabels" +) + +// hivecommons/hive#14524: a maintainer's clanker PR sat at 072 for 26h, +// nudged twice, its hive offline, while the row read a bare "Returned to +// contributor". The tracker now carries `adoption{}` and says why in plain +// words; under maintainer_policy: ask the row offers Adopt. + +func adoptionFixture(t *testing.T, now time.Time, policy string, presence func(string) (automerge.ContributorPresence, bool)) (*Server, *stagelabels.Store, *StatusPayload) { + t.Helper() + s := newTestServer() + clock := now + store := stagelabels.NewStore("", func() time.Time { return clock }) + s.stageStore = store + s.presenceLookup = presence + s.deps = &Dependencies{Config: &config.Config{}} + s.deps.Config.Governor.Labels.Stage.Adoption.MaintainerPolicy = policy + key := stagelabels.Key("hivecommons/hive", 14524) + clock = now.Add(-26 * time.Hour) + store.Observe(key, stagelabels.ReturnedToContributor, "check-failing:ratchet") + store.MarkNudged(key, "feed", 1, false, clock) + clock = now.Add(-20 * time.Hour) + store.MarkNudged(key, "feed", 2, false, clock) + clock = now + status := minimalPayload() + status.HiveID = "hive" + status.Repos = []FrontendRepo{{ + Name: "hive", Full: "hivecommons/hive", + OpenPrs: []any{FrontendPR{PullRequest: github.PullRequest{Number: 14524, Title: "Big change", Author: "hanthor", HeadSHA: "feed", Labels: []string{"stage/072-returned-to-contributor", "author/clanker", "role/contributor"}}}}, + }} + s.UpdateStatus(status) + return s, store, status +} + +func offlinePresence(lastSeen time.Time) func(string) (automerge.ContributorPresence, bool) { + return func(login string) (automerge.ContributorPresence, bool) { + if login != "hanthor" { + return automerge.ContributorPresence{}, false + } + return automerge.ContributorPresence{Registered: true, Online: false, LastSeen: lastSeen}, true + } +} + +func TestStageTrackerAdoptionAskOffersAdopt(t *testing.T) { + now := time.Date(2026, 10, 28, 16, 0, 0, 0, time.UTC) + s, store, status := adoptionFixture(t, now, config.AdoptionMaintainerPolicyAsk, offlinePresence(now.Add(-26*time.Hour))) + store.NoteAdoptionBlocked(stagelabels.Key("hivecommons/hive", 14524), "feed", stagelabels.AdoptBlockedAuthorMaintainer, now.Add(-25*time.Hour)) + it := trackerItem(t, s.buildStageTracker(status, store, now), "pr", 14524) + a := it.Adoption + if a == nil { + t.Fatalf("no adoption payload: %+v", it) + } + if !a.Due || a.BlockedBy != "author-is-maintainer" || a.Nudges != 2 || a.AuthorOnline || !a.AuthorRegistered || !a.AuthorMaintainer || a.Policy != "ask" || a.Action != "decide:adopt" { + t.Fatalf("adoption = %+v", a) + } + if a.Since == nil || !a.Since.Equal(now.Add(-26*time.Hour)) { + t.Fatalf("since = %v", a.Since) + } + if a.Text != "waiting on @hanthor (maintainer, offline 26h) — adopt?" { + t.Fatalf("text = %q", a.Text) + } + if it.Caption != "Returned to @hanthor — a required check is failing (ratchet) — waiting on @hanthor (maintainer, offline 26h) — adopt?" && !strings.HasSuffix(it.Caption, " — waiting on @hanthor (maintainer, offline 26h) — adopt?") { + t.Fatalf("caption = %q", it.Caption) + } + if strings.Contains(it.Caption, "must act") { + t.Fatalf("caption keeps the bare clause: %q", it.Caption) + } + // The ask hold is a decision a person owes: decision_needed carries the + // question and leads with Adopt under the same action id (#14995). + d := it.DecisionNeeded + if d == nil || len(d.Options) == 0 || d.Options[0].Action != "decide:adopt" || !d.Options[0].Enabled { + t.Fatalf("decision_needed = %+v", d) + } + if !strings.HasPrefix(d.Question, "@hanthor maintains this repository and has been offline for 26h; adopt the PR?") || d.BlockerReason != "adoption:author-is-maintainer" || d.Since == nil || !d.Since.Equal(now.Add(-26*time.Hour)) { + t.Fatalf("decision question = %q reason=%q since=%v", d.Question, d.BlockerReason, d.Since) + } + // The wire shape the SPA reads. + raw, _ := json.Marshal(it) + for _, want := range []string{`"adoption":{`, `"due":true`, `"blocked_by":"author-is-maintainer"`, `"nudges":2`, `"author_online":false`, `"action":"decide:adopt"`} { + if !strings.Contains(string(raw), want) { + t.Errorf("payload lacks %s: %s", want, raw) + } + } +} + +func TestStageTrackerAdoptionNeverSaysSo(t *testing.T) { + now := time.Date(2026, 10, 28, 16, 0, 0, 0, time.UTC) + s, store, status := adoptionFixture(t, now, config.AdoptionMaintainerPolicyNever, offlinePresence(time.Time{})) + store.NoteAdoptionBlocked(stagelabels.Key("hivecommons/hive", 14524), "feed", stagelabels.AdoptBlockedAuthorMaintainer, now.Add(-25*time.Hour)) + it := trackerItem(t, s.buildStageTracker(status, store, now), "pr", 14524) + if a := it.Adoption; a == nil || a.Action != "" || a.Text != "waiting on @hanthor (maintainer, offline 26h) — not adopted: maintainer_policy is never" { + t.Fatalf("adoption = %+v", a) + } + if it.DecisionNeeded != nil { + t.Fatalf("never is not a person's decision: %+v", it.DecisionNeeded) + } +} + +// adopt (default): nothing is held, so the row only reports the wait, the +// nudges and the presence; no Adopt is offered. +func TestStageTrackerAdoptionDefaultReportsWait(t *testing.T) { + now := time.Date(2026, 10, 28, 16, 0, 0, 0, time.UTC) + s, store, status := adoptionFixture(t, now, "", offlinePresence(now.Add(-3*time.Hour))) + a := trackerItem(t, s.buildStageTracker(status, store, now), "pr", 14524).Adoption + if a == nil || a.Due || a.BlockedBy != "" || a.Action != "" || a.Policy != "adopt" { + t.Fatalf("adoption = %+v", a) + } + if a.Text != "waiting on @hanthor (offline 3h, 2 nudges)" { + t.Fatalf("text = %q", a.Text) + } + // Online author: no offline span. + s.presenceLookup = func(string) (automerge.ContributorPresence, bool) { + return automerge.ContributorPresence{Registered: true, Online: true}, true + } + if a = trackerItem(t, s.buildStageTracker(status, store, now), "pr", 14524).Adoption; a == nil || a.Text != "waiting on @hanthor (online, 2 nudges)" { + t.Fatalf("online text = %+v", a) + } +} + +// A stale blocked mark (head moved) and an adopted record carry nothing. +func TestStageTrackerAdoptionStaleAndAdopted(t *testing.T) { + now := time.Date(2026, 10, 28, 16, 0, 0, 0, time.UTC) + s, store, status := adoptionFixture(t, now, config.AdoptionMaintainerPolicyAsk, offlinePresence(time.Time{})) + key := stagelabels.Key("hivecommons/hive", 14524) + store.NoteAdoptionBlocked(key, "old", stagelabels.AdoptBlockedAuthorMaintainer, now.Add(-time.Hour)) + if a := trackerItem(t, s.buildStageTracker(status, store, now), "pr", 14524).Adoption; a == nil || a.Due || a.Action != "" { + t.Fatalf("stale head still blocks: %+v", a) + } + store.MarkAdopted(key, "feed", 14977, now) + if a := trackerItem(t, s.buildStageTracker(status, store, now), "pr", 14524).Adoption; a != nil { + t.Fatalf("adopted record still carries adoption: %+v", a) + } +} + +func TestStageTrackerAdoptionOfflineFor(t *testing.T) { + now := time.Date(2026, 10, 28, 16, 0, 0, 0, time.UTC) + at := func(d time.Duration) *time.Time { t := now.Add(-d); return &t } + for _, tc := range []struct { + a StageTrackerAdoption + want string + }{ + {StageTrackerAdoption{Since: at(26 * time.Hour)}, " 26h"}, + {StageTrackerAdoption{Since: at(26 * time.Hour), AuthorLastSeen: at(40 * time.Minute)}, " 40m"}, + {StageTrackerAdoption{Since: at(26 * time.Hour), AuthorLastSeen: at(3 * 24 * time.Hour)}, " 26h"}, + {StageTrackerAdoption{Since: at(5 * 24 * time.Hour)}, " 5d"}, + {StageTrackerAdoption{Since: at(10 * time.Second)}, " 1m"}, + {StageTrackerAdoption{}, ""}, + } { + if got := stageTrackerAdoptionOfflineFor(tc.a, now); got != tc.want { + t.Errorf("%+v: got %q want %q", tc.a, got, tc.want) + } + } +} + +func TestStageTrackerAdoptionCaption(t *testing.T) { + a := &StageTrackerAdoption{Text: "waiting on @x (offline 2h)"} + for in, want := range map[string]string{ + "Returned to @x — review swarm requested changes — @x must act (1 nudge sent)": "Returned to @x — review swarm requested changes — waiting on @x (offline 2h)", + "Returned to @x — @x must act": "Returned to @x — waiting on @x (offline 2h)", + "Returned to @x": "Returned to @x — waiting on @x (offline 2h)", + } { + if got := stageTrackerAdoptionCaption(in, a); got != want { + t.Errorf("%q → %q, want %q", in, got, want) + } + } + if got := stageTrackerAdoptionCaption("Returned to @x — @x must act", nil); got != "Returned to @x — @x must act" { + t.Errorf("nil adoption changed the caption: %q", got) + } +} + +// POST …/items/N/decision {"decision":"adopt"}: PR only, needs adoption +// enabled, posts the attributed note, sets adoption/supersede, audits. +func TestRepoItemDecisionAdopt(t *testing.T) { + mock := &repoItemDecisionMock{prForeign: true} + srv := newRepoItemDecisionServer(t, mock) + srv.deps.Config.Governor.Labels.Stage.Adoption.MaintainerPolicy = config.AdoptionMaintainerPolicyAsk + + if w := postRepoItemDecision(t, srv, 7, "writer", `{"decision":"adopt","type":"issue"}`); w.Code != http.StatusBadRequest { + t.Fatalf("issue adopt: code=%d body=%s", w.Code, w.Body.String()) + } + if w := postRepoItemDecision(t, srv, 8, "reader", `{"decision":"adopt","type":"pr"}`); w.Code != http.StatusForbidden { + t.Fatalf("reader adopt: code=%d body=%s", w.Code, w.Body.String()) + } + off := false + srv.deps.Config.Governor.Labels.Stage.Adoption.Enabled = &off + if w := postRepoItemDecision(t, srv, 8, "writer", `{"decision":"adopt","type":"pr"}`); w.Code != http.StatusConflict { + t.Fatalf("adoption disabled: code=%d body=%s", w.Code, w.Body.String()) + } + srv.deps.Config.Governor.Labels.Stage.Adoption.Enabled = nil + if len(mock.added) != 0 || len(mock.comments) != 0 { + t.Fatalf("refused requests mutated GitHub: added=%v comments=%v", mock.added, mock.comments) + } + + w := postRepoItemDecision(t, srv, 8, "writer", `{"decision":"adopt","type":"pr"}`) + if w.Code != http.StatusOK { + t.Fatalf("adopt: code=%d body=%s", w.Code, w.Body.String()) + } + var resp repoItemDecisionResponse + _ = json.Unmarshal(w.Body.Bytes(), &resp) + if resp.Decision != "adopt" || resp.Status != "adoption-queued" || resp.Label != delegatedecision.LabelAdoptSupersede { + t.Fatalf("resp = %+v", resp) + } + if strings.Join(mock.added, ",") != delegatedecision.LabelAdoptSupersede { + t.Fatalf("added = %v", mock.added) + } + if len(mock.comments) != 1 || !strings.HasPrefix(mock.comments[0], "") || !strings.Contains(mock.comments[0], "@writer asked the hive to adopt") { + t.Fatalf("comments = %v", mock.comments) + } + if acts := decisionAuditActions(srv); len(acts) == 0 || acts[0] != auditRepoItemDecisionAdopt { + t.Fatalf("audit = %v", acts) + } +} + +// governor.labels.stage.adoption.maintainer_policy round-trips through the +// Labels tab and rejects unknown values before touching the config. +func TestGovernorLabelsAdoptionMaintainerPolicyRoundTrip(t *testing.T) { + s := covApiServer(t) + for _, bad := range []any{"always", "ASK ME", 7, true} { + if rec := doPut(s, "/api/config/governor/labels", map[string]any{"stage_adoption_maintainer_policy": bad}); rec.Code != http.StatusBadRequest { + t.Fatalf("%v: expected 400, got %d — %s", bad, rec.Code, rec.Body.String()) + } + } + if got := s.deps.Config.Governor.Labels.Stage.Adoption.MaintainerPolicy; got != "" { + t.Fatalf("a rejected PUT changed the policy to %q", got) + } + var got map[string]any + if err := json.Unmarshal(doGet(s, "/api/config/governor").Body.Bytes(), &got); err != nil { + t.Fatal(err) + } + if got["stageAdoptionMaintainerPolicy"] != "adopt" { + t.Fatalf("default stageAdoptionMaintainerPolicy = %v, want adopt", got["stageAdoptionMaintainerPolicy"]) + } + if rec := doPut(s, "/api/config/governor/labels", map[string]any{"stage_adoption_maintainer_policy": " Ask "}); rec.Code != http.StatusOK { + t.Fatalf("labels PUT: %d — %s", rec.Code, rec.Body.String()) + } + if got := s.deps.Config.Governor.Labels.Stage.Adoption.MaintainerPolicy; got != "ask" { + t.Fatalf("policy = %q, want ask", got) + } + if err := json.Unmarshal(doGet(s, "/api/config/governor").Body.Bytes(), &got); err != nil { + t.Fatal(err) + } + if got["stageAdoptionMaintainerPolicy"] != "ask" { + t.Fatalf("stageAdoptionMaintainerPolicy after PUT = %v", got["stageAdoptionMaintainerPolicy"]) + } + + html := indexHTML(t) + labels := extractJSFunction(t, html, "renderGovLabels") + for _, want := range []string{ + "yamlHint('governor.labels.stage.adoption.maintainer_policy')", + `id="cfg-stage-adoption-maintainer-policy" data-change-action="markDirty" data-arg0="labels" data-arg1="stage_adoption_maintainer_policy" data-arg-types="s,s,v"`, + "_configState.data.stageAdoptionMaintainerPolicy || 'adopt'", + "['adopt',", "['ask',", "['never',", + } { + if !strings.Contains(labels, want) { + t.Errorf("renderGovLabels lacks %q", want) + } + } + if !strings.Contains(html, "key: 'governor.labels.stage.adoption.maintainer_policy'") { + t.Error("settings search index has no entry for governor.labels.stage.adoption.maintainer_policy") + } +} + +// The SPA's pure helpers: the chip text/tooltip, the Adopt row action +// (only when the payload offers it, only with write), and the confirm. +func TestStageTrackerAdoptionJS(t *testing.T) { + html := indexHTML(t) + script := strings.Join([]string{ + stageTrackerRowActionsPreamble(t, html), + jsFunc(t, html, "stageTrackerAdoptionTip"), + jsFunc(t, html, "stageTrackerAdoptOffered"), + jsFunc(t, html, "stageTrackerAdoptionChipText"), + jsFunc(t, html, "stageTrackerAdoptionChipHtml"), + ` +const ask = { kind: 'pr', repo: 'hivecommons/hive', number: 14524, stage: 72, stage_label: 'stage/072-returned-to-contributor', author: 'hanthor', labels: [], + adoption: { author: 'hanthor', due: true, blocked_by: 'author-is-maintainer', nudges: 2, author_online: false, author_maintainer: true, policy: 'ask', action: 'decide:adopt', text: 'waiting on @hanthor (maintainer, offline 26h) — adopt?' } }; +const plain = { kind: 'pr', repo: 'hivecommons/hive', number: 1, stage: 72, stage_label: 'stage/072-returned-to-contributor', author: 'zoe', labels: [], + adoption: { author: 'zoe', due: false, nudges: 1, author_online: true, policy: 'adopt', text: 'waiting on @zoe (online, 1 nudge)' } }; +const none = { kind: 'pr', repo: 'hivecommons/hive', number: 2, stage: 72, stage_label: 'stage/072-returned-to-contributor', author: 'zoe', labels: [] }; +assert.strictEqual(stageTrackerAdoptionTip(ask), 'waiting on @hanthor (maintainer, offline 26h) — adopt?'); +assert.strictEqual(stageTrackerAdoptionTip(none), ''); +assert.strictEqual(stageTrackerAdoptOffered(ask), true); +assert.strictEqual(stageTrackerAdoptOffered(plain), false); +assert.strictEqual(stageTrackerAdoptionChipText(ask), 'adopt?'); +assert.strictEqual(stageTrackerAdoptionChipText(plain), 'waiting on @zoe'); +assert.ok(stageTrackerAdoptionChipHtml(ask).includes('ham-badge-adoption-ask')); +assert.ok(stageTrackerAdoptionChipHtml(ask).includes('offline 26h')); +assert.strictEqual(stageTrackerAdoptionChipHtml(none), ''); +const ids = (item, ctx) => stageTrackerRowActions(item, ctx).map(a => a.id); +const w = { write: true, user: 'owner' }; +assert.ok(ids(ask, w).includes('decide:adopt'), 'ask row offers Adopt: ' + ids(ask, w)); +assert.ok(!ids(plain, w).includes('decide:adopt'), 'plain 072 row must not offer Adopt'); +assert.ok(!ids(none, w).includes('decide:adopt')); +const ro = stageTrackerRowActions(ask, { write: false, user: '' }).find(a => a.id === 'decide:adopt'); +assert.ok(ro && ro.enabled === false && ro.why, 'read-only Adopt is listed but disabled'); +assert.strictEqual(STAGE_TRACKER_ACTION_LABELS['decide:adopt'], 'Adopt (hive takes over)'); +`, + }, "\n") + runStageTrackerRowActionsScript(t, script) + for _, want := range []string{ + "case 'decide:adopt': {", + "'Adoption: ' + adoption", + ".ham-badge-adoption {", + "adoption: lp.adoption", + } { + if !strings.Contains(html, want) { + t.Errorf("index.html lacks %q", want) + } + } +} + +// The tracker endpoint serialises adoption on the nested PR of an issue +// row too (the issue carrying its covering PR). +func TestStageTrackerAdoptionEndpointShape(t *testing.T) { + now := time.Date(2026, 10, 28, 16, 0, 0, 0, time.UTC) + s, store, _ := adoptionFixture(t, now, config.AdoptionMaintainerPolicyAsk, offlinePresence(now.Add(-26*time.Hour))) + store.NoteAdoptionBlocked(stagelabels.Key("hivecommons/hive", 14524), "feed", stagelabels.AdoptBlockedAuthorMaintainer, now.Add(-25*time.Hour)) + rr := httptest.NewRecorder() + s.handleStageTracker(rr, httptest.NewRequest(http.MethodGet, "/api/stage-tracker", nil)) + if rr.Code != http.StatusOK { + t.Fatalf("status %d: %s", rr.Code, rr.Body.String()) + } + if !strings.Contains(rr.Body.String(), `"blocked_by":"author-is-maintainer"`) { + t.Fatalf("endpoint body lacks adoption: %s", rr.Body.String()) + } +} diff --git a/src/pkg/dashboard/stage_tracker_decision.go b/src/pkg/dashboard/stage_tracker_decision.go index d7f03072c8..5ea451e525 100644 --- a/src/pkg/dashboard/stage_tracker_decision.go +++ b/src/pkg/dashboard/stage_tracker_decision.go @@ -128,6 +128,12 @@ func stageTrackerVerdictLookup(artifact *review.Artifact) func(repo string, numb // aggregate for the PR's current head when the artifact has one; // sentinelLabel is the configured sentinel alert label. func stageTrackerDecisionNeeded(it StageTrackerItem, verdict *review.Aggregate, sentinelLabel string) *StageTrackerDecision { + return stageTrackerDecisionNeededAt(it, verdict, sentinelLabel, time.Now()) +} + +// stageTrackerDecisionNeededAt is stageTrackerDecisionNeeded with the clock +// the tracker build uses, so spans in questions match the row's pill. +func stageTrackerDecisionNeededAt(it StageTrackerItem, verdict *review.Aggregate, sentinelLabel string, now time.Time) *StageTrackerDecision { held := slices.Contains(it.Modifiers, modHold) switch { case it.Kind == "pr" && (it.Stage == stagelabels.NeedsDecision.Number() || slices.Contains(it.Modifiers, modNeedsDecision)): @@ -142,10 +148,43 @@ func stageTrackerDecisionNeeded(it StageTrackerItem, verdict *review.Aggregate, return decisionForTriage(it, held) case slices.Contains(it.Modifiers, modNeedsHuman): return decisionForNeedsHuman(it, held) + case it.Kind == "pr" && it.Adoption != nil && it.Adoption.Action == decisionActionAdopt: + return decisionForAdoption(it, held, now) } return nil } +// decisionForAdoption: a nudged 072 PR whose author maintains the +// repository, held for an owner under +// governor.labels.stage.adoption.maintainer_policy: ask +// (hivecommons/hive#14524). The question names the author and how long +// their hive has been gone; the lead option is Adopt. +func decisionForAdoption(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.BlockedBy} + 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 + " maintains this repository and " + gone + "; adopt the PR? The hive would take it over as it does any contributor's (the author's commits and sign-off are kept)." + d.Blocker = "maintainer_policy is ask: the hive never adopts a maintainer's PR on its own; a person decides." + if held { + d.Blocker += " " + decisionHeldBlocker + } + d.Options = []StageTrackerDecisionOption{ + decisionOption(decisionActionAdopt, "Adopt (hive takes over)", !held, "Release the hold first"), + decisionHoldOption(held), + } + return d +} + func decisionHoldOption(held bool) StageTrackerDecisionOption { if held { return StageTrackerDecisionOption{Action: decisionActionRelease, Label: "Release hold", Enabled: true} diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 4f4f30a64e..fb7e80228f 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -1505,6 +1505,8 @@ status token the sentinel pill on the repo card already uses. */ .ham-badge-sentinel { color: var(--status-error); border-color: color-mix(in srgb, var(--status-error) 55%, transparent); font-weight: var(--fw-medium); } .ham-seg.active.ham-sentinel { background: var(--status-error); color: var(--surface-0); } + /* 072 adoption chip (maintainer-policy, hive PR 14524): "waiting on @author (maintainer, offline 26h) — adopt?" */ + .ham-badge-adoption { color: var(--status-warn); border-color: color-mix(in srgb, var(--status-warn) 55%, transparent); font-weight: var(--fw-medium); } .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%); } @@ -14165,6 +14167,39 @@

Where to get help

const STAGE_TRACKER_BLOCKED_ON_PR_MERGED = 'merged; the blocked sweep lifts the label next'; const STAGE_TRACKER_BLOCKED_ON_PR_CLOSED = 'closed unmerged; the blocked sweep re-triages it next'; + // The 072 adoption line (`adoption`: {due, blocked_by, since, nudges, + // author_online, action, text} — hivecommons/hive#14524): the payload's + // plain-words text, '' when the row carries none. + function stageTrackerAdoptionTip(item) { + const a = item && item.adoption; + return a && a.text ? String(a.text) : ''; + } + // Whether the row offers the owner's Adopt: the engine found adoption + // due and held it for a reason the owner settles (maintainer_policy: + // ask names `action: "decide:adopt"`). + function stageTrackerAdoptOffered(item) { + const a = item && item.kind === 'pr' ? item.adoption : null; + return !!(a && a.due && a.action === 'decide:adopt'); + } + // The chip text: "adopt?" when the owner is asked, else "waiting on @x". + function stageTrackerAdoptionChipText(item) { + const a = item && item.adoption; + if (!a) return ''; + if (stageTrackerAdoptOffered(item)) return 'adopt?'; + return a.blocked_by ? 'not adopted' : ('waiting on ' + (a.author ? '@' + a.author : 'author')); + } + function stageTrackerAdoptionChipHtml(item) { + const tip = stageTrackerAdoptionTip(item); + if (!tip) return ''; + const offered = stageTrackerAdoptOffered(item); + const cls = 'ham-badge ham-badge-adoption' + (offered ? ' ham-badge-adoption-ask' : ''); + // "adopt?" opens the Needs-human popover (its decision_needed carries + // the Adopt option) when the popover helpers are present. + const decision = offered && typeof stageTrackerDecisionOf === 'function' && item.decision_needed ? stageTrackerDecisionOf(item) : null; + if (decision) return stageTrackerDecisionTriggerHtml(decision, esc(stageTrackerAdoptionChipText(item)), tip, cls); + return `${esc(stageTrackerAdoptionChipText(item))}`; + } + // "Sentinel flagged security-relevant changes at : // " — the sentinel wording for an item's tooltips and aria // labels; '' when the item carries no alert. Without a reason or a @@ -14493,6 +14528,9 @@

Where to get help

if (actorKind) lines.push('Next move: ' + actorKind); const blockedPR = mods.indexOf('blocked') >= 0 ? stageTrackerBlockedOnPR(item) : null; if (blockedPR) lines.push(blockedPR.tip); + // Guarded: the test harnesses load helpers by name, and this one is additive. + const adoption = typeof stageTrackerAdoptionTip === 'function' ? stageTrackerAdoptionTip(item) : ''; + if (adoption) lines.push('Adoption: ' + adoption + (typeof stageTrackerAdoptOffered === 'function' && stageTrackerAdoptOffered(item) ? ' (row menu → Adopt)' : '')); if (mods.length) lines.push('Flags: ' + mods.map(m => STAGE_TRACKER_MOD_TEXT[m] || m).join(', ')); const stale = stageTrackerStaleLabelsText(item); if (stale) lines.push(stale); @@ -14515,7 +14553,7 @@

Where to get help

} function stageTrackerChipsHtml(item) { - const sentinel = stageTrackerSentinelChipHtml(item); + const sentinel = stageTrackerSentinelChipHtml(item) + (typeof stageTrackerAdoptionChipHtml === 'function' ? stageTrackerAdoptionChipHtml(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; @@ -14792,7 +14830,7 @@

Where to get help

const who = (lp.author_kind || 'hive') + (lp.author ? ' · @' + lp.author : ''); prRefs = [STAGE_TRACKER_LINKED_GLYPH + stageTrackerPRRef(lp.number, lp.url, lp.author_kind || '', lp.author, lp.title, (lp.title ? lp.title + '\n' : '') + 'Author: ' + who + ' · ' + stageTrackerLinkedTip(item, lp.number, ctx)) + (lp.base_ref ? ` ${esc(lp.base_ref)}` : '')]; shown = Object.assign({}, item, { via_pr: true, stage: lp.stage || 40, stage_since: lp.stage_since || item.stage_since, modifiers: lp.modifiers || item.modifiers, deferred_modifiers: lp.deferred_modifiers || item.deferred_modifiers || [], caption: lp.caption || item.caption, reason: lp.reason || item.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 || '', decision_needed: lp.decision_needed || null }); + 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 || '', decision_needed: lp.decision_needed || null, adoption: lp.adoption || null }); } else if (linked.length) { // Several covering PRs: the issue strip ends at Claimed, all passed // and nothing lit; one sub-row per PR carries the live chevron. @@ -16131,6 +16169,7 @@

All labels

const STAGE_TRACKER_ACTION_LABELS = { 'decide:delegate': 'Let hive decide', 'decide:approve': 'Approve', 'decide:direction': 'Give direction', 'decide:close-superseded': 'Close as superseded by', 'decide:close-wontfix': "Close as won't-fix", + 'decide:adopt': 'Adopt (hive takes over)', 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', }; @@ -16319,6 +16358,9 @@

All labels

const on = target === item ? '' : ' PR #' + (Number(target.number) || 0); out.push({ id: 'decide', label: 'Decide' + on + '…', enabled: write, why: write ? '' : STAGE_TRACKER_WHY_WRITE, submenu: stageTrackerDecideOptions(target, ctx), target }); } + // 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 }); 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 }); @@ -17027,6 +17069,10 @@

All labels

const v = await stageTrackerAsk(id, 'prompt', { title: stageTrackerActionLabel(id), label: 'Comment for ' + refs + ' (optional)', placeholder: 'Why this is closed', confirmLabel: 'Close' }); return v == null ? null : { comment: v }; } + case 'decide:adopt': { + const why = items.map(it => stageTrackerAdoptionTip(it)).filter(Boolean).join('\n'); + return (await hiveConfirm({ title: 'Adopt pull request' + (items.length > 1 ? 's' : ''), message: (why ? why + '\n\n' : '') + 'Have the hive adopt ' + refs + ' as ' + who + '? The author\'s commits and sign-off are kept; the hive rebases and fixes CI (in place when GitHub allows, else on a superseding hive PR that closes this one when it merges). Recorded as your decision on the PR.', confirmLabel: 'Adopt' })) ? {} : null; + } case 'needs-human': { 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 }; @@ -17215,7 +17261,11 @@

All labels

} catch (e) { showToast('Could not copy: ' + (e && e.message ? e.message : 'clipboard unavailable'), 'error'); } return { toasts: [], pending: [] }; } - if (id.indexOf('decide:') === 0) { + if (id === 'decide:adopt') { + // Adopt acts on the nudged PR row itself (072, not a decision park). + items = items.filter(stageTrackerAdoptOffered); + 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 // only mirrored from it); dedupe when the PR row is selected too. const seen = {}; @@ -41914,6 +41964,7 @@

Configure LiteLLM

{ tab: 'Labels', section: 'Labels', label: 'Stalled requires quiet', key: 'governor.labels.stage.stalled.require_quiet', text: 'stalled no activity quiet dwell head push comment review ci label governor.labels.stage.stalled.require_quiet governor.labels.stage.dwell' }, { tab: 'Labels', section: 'Labels', label: 'Central stage engine', key: 'governor.labels.stage.engine.mode', text: 'stage engine mode shadow enforce dry run pause anomaly reconciler ADR-0025 governor.labels.stage.engine.mode' }, { tab: 'Labels', section: 'Labels', label: 'Stage dwell overrides', key: 'governor.labels.stage.dwell', text: 'stage dwell stalled threshold governor.labels.stage.dwell' }, + { tab: 'Labels', section: 'Labels', label: 'Adoption of a maintainer\'s PR', key: 'governor.labels.stage.adoption.maintainer_policy', text: 'adoption maintainer policy adopt ask never maintainer own pr clanker disconnected offline adopt action governor.labels.stage.adoption.maintainer_policy' }, { tab: 'Labels', section: 'Labels', label: 'Contributor nudge', key: 'governor.labels.stage.contributor_nudge.enabled', text: 'contributor nudge returned-to-contributor red ci fix-pr relay interrupt renudge presence window governor.labels.stage.contributor_nudge.enabled governor.labels.stage.contributor_nudge.renudge_interval governor.labels.stage.presence_window' }, { tab: 'Labels', section: 'Labels', label: 'Adopt red contributor PRs', key: 'governor.labels.stage.adoption.enabled', text: 'adoption adopted-by-hive stage 074 red contributor pr grace online offline supersede takeover in place after offline unregistered heartbeat governor.labels.stage.adoption.enabled governor.labels.stage.contributor_grace_online governor.labels.stage.contributor_grace_offline governor.labels.stage.adoption.after_offline governor.labels.stage.adoption.after_unregistered governor.labels.stage.adoption.in_place governor.labels.stage.adoption.strict_attribution strict attribution governor.labels.stage.adoption.auto_merge auto merge adopted head hive authority' }, { tab: 'Hub', section: 'Contributor Relay', label: 'Fix budget', key: 'contribute.max_parallel_fixes', text: 'fix budget parallel fixes focus window red pr fix-pr preempt spawn contribute.max_parallel_fixes contribute.min_focus_window' }, @@ -48703,6 +48754,14 @@

Backend placement policy

const stageAdoptionOn = (_configState.dirty.labels && _configState.dirty.labels.stage_adoption_enabled !== undefined) ? _configState.dirty.labels.stage_adoption_enabled : (_configState.data.stageAdoptionEnabled !== false); + const stageAdoptionMaintainerPolicy = (_configState.dirty.labels && _configState.dirty.labels.stage_adoption_maintainer_policy !== undefined) + ? _configState.dirty.labels.stage_adoption_maintainer_policy + : (_configState.data.stageAdoptionMaintainerPolicy || 'adopt'); + const stageAdoptionMaintainerOptions = [ + ['adopt', 'adopt — a clanker PR whose hive disconnected is adopted whoever wrote it, repo role ignored (default)'], + ['ask', 'ask — never adopt a maintainer\'s PR on its own; mark it for an owner decision and offer Adopt in the activity monitor'], + ['never', 'never — the hive never takes over a maintainer\'s PR and releases any adoption of one'], + ].map(([v, label]) => ``).join(''); const stageStalledQuietOn = (_configState.dirty.labels && _configState.dirty.labels.stage_stalled_require_quiet !== undefined) ? _configState.dirty.labels.stage_stalled_require_quiet : (_configState.data.stageStalledRequireQuiet !== false); @@ -48771,6 +48830,11 @@

Stage labels

A contributor counts as online when their relay heartbeat is within this window; online contributors get the fix-pr interrupt immediately, offline ones only the comment (their fix waits in the queue).
Adopt red contributor PRs after the grace ${yamlHint('governor.labels.stage.adoption.enabled')} ${settingHelpMark('settings', 'labels', 'Adopt red contributor PRs', `When a nudged contributor PR is still red after its grace (online 2h / offline 1h, below) the hive moves it to stage/074-adopted-by-hive: it pushes hive/adopt-N at the contributor's head (commits and sign-off preserved), opens a superseding App PR carrying the original Closes lines, comments once on the original, and the scanner's red-PR fix-first kick rebases and fixes CI on that branch. The original closes automatically when the superseding PR merges. Off: the PR stays in 072 and just stalls. See docs/labels-and-control-signals.md.`)}
+
+ + +
adopt: repo role ignored, adopt on disconnect like any clanker PR. ask: park it for an owner decision with an Adopt action. never: hands-off and release.
+
diff --git a/src/pkg/github/automerge/automerge_adopt_maintainer_policy_test.go b/src/pkg/github/automerge/automerge_adopt_maintainer_policy_test.go new file mode 100644 index 0000000000..aaa884f928 --- /dev/null +++ b/src/pkg/github/automerge/automerge_adopt_maintainer_policy_test.go @@ -0,0 +1,187 @@ +package automerge + +import ( + "testing" + "time" + + gh "github.com/google/go-github/v72/github" + + "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/delegatedecision" + "github.com/hivecommons/hive/pkg/stagelabels" +) + +// governor.labels.stage.adoption.maintainer_policy (hivecommons/hive#14524): +// hive's own hosted spoke left PR #14524 — a maintainer's clanker PR, nudged +// twice, its hive gone 26h — at 072 every cycle with "author maintains the +// repository; not adopting". Owner decision: clanker PRs are adoptable on +// disconnect regardless of the owner's repo role (default adopt); ask and +// never remain opt-outs. + +const maintainerLabels072 = "stage/072-returned-to-contributor" + +func maintainerPolicyWith(policy string) StageLabelPolicy { + p := adoptPolicy() + p.AdoptInPlace = true + p.AdoptionMaintainerPolicy = policy + return p +} + +func TestMaintainerPolicyDefaultsToAdopt(t *testing.T) { + for in, want := range map[string]string{ + "": config.AdoptionMaintainerPolicyAdopt, "adopt": config.AdoptionMaintainerPolicyAdopt, + " Ask ": config.AdoptionMaintainerPolicyAsk, "NEVER": config.AdoptionMaintainerPolicyNever, + "bogus": config.AdoptionMaintainerPolicyAdopt, + } { + if got := (StageLabelPolicy{AdoptionMaintainerPolicy: in}).maintainerPolicy(); got != want { + t.Errorf("maintainerPolicy(%q) = %q, want %q", in, got, want) + } + } +} + +// adopt (the default): the author's role is never read and a maintainer's +// clanker PR is adopted on the same clock as any contributor's. +func TestMaintainerPolicyAdoptTakesMaintainerPR(t *testing.T) { + for _, policy := range []string{"", config.AdoptionMaintainerPolicyAdopt} { + t.Run("policy="+policy, func(t *testing.T) { + h, done := newAdoptHarness(t, ContributorNudgeOutcome{Mode: "comment"}, maintainerPolicyWith(policy)) + defer done() + h.adopt.permissions = map[string]string{"mallory": "admin"} + h.adopt.allowMaintainerEdits(7, true) + h.observe(adoptPR(7, "aaa"), "check-failing:unit") + h.clock.advance(2 * time.Hour) + h.observe(adoptPR(7, "aaa", maintainerLabels072, "role/contributor", "author/clanker"), "check-failing:unit") + rec, _ := h.e.stageStoreOrShared().Get(stageKey("acme", "widget", 7)) + if !rec.AdoptedInPlace() || rec.AdoptReason != AdoptReasonOffline { + t.Fatalf("maintainer's clanker PR not adopted under policy %q: %+v", policy, rec) + } + if h.adopt.permissionReads != 0 { + t.Fatalf("permission read %d times; adopt must not consult the role", h.adopt.permissionReads) + } + if rec.AdoptionBlocked("aaa") != "" { + t.Fatalf("adopted record still marked blocked: %+v", rec) + } + }) + } +} + +// adopt never loosens the human-author rule: a PR without author/clanker +// is still not adopted. +func TestMaintainerPolicyAdoptKeepsHumanRule(t *testing.T) { + h, done := newAdoptHarness(t, ContributorNudgeOutcome{Mode: "comment"}, maintainerPolicyWith(config.AdoptionMaintainerPolicyAdopt)) + defer done() + h.adopt.permissions = map[string]string{"mallory": "admin"} + h.adopt.allowMaintainerEdits(7, true) + // No relay trailer and no registered presence: a person's own PR. + h.sink.presence = &ContributorPresence{} + human := func(labels ...string) *gh.PullRequest { + pr := adoptPR(7, "aaa", labels...) + pr.Body = gh.Ptr("Fixes the widget.\n") + return pr + } + h.observe(human(), "check-failing:unit") + h.clock.advance(3 * time.Hour) + h.observe(human("stage/071-needs-author", "role/contributor", "author/human"), "check-failing:unit") + rec, _ := h.e.stageStoreOrShared().Get(stageKey("acme", "widget", 7)) + if rec.AdoptedHead != "" || rec.NudgeCount != 0 || len(adoptionComments(h.api)) != 0 { + t.Fatalf("human-authored PR adopted: %+v", rec) + } +} + +// adopt also keeps an existing maintainer adoption: the release-on-role +// paths only fire under never. +func TestMaintainerPolicyAdoptKeepsLiveAdoption(t *testing.T) { + h, done := newAdoptHarness(t, ContributorNudgeOutcome{Mode: "comment"}, maintainerPolicyWith(config.AdoptionMaintainerPolicyAdopt)) + defer done() + h.adopt.allowMaintainerEdits(7, true) + h.observe(adoptPR(7, "aaa"), "check-failing:unit") + h.clock.advance(2 * time.Hour) + h.observe(adoptPR(7, "aaa", maintainerLabels072, "role/contributor", "author/clanker"), "check-failing:unit") + h.adopt.permissions = map[string]string{"mallory": "admin"} + h.clock.advance(maintainerPermTTL + time.Minute) + h.observe(adoptPR(7, "aaa", "stage/074-adopted-by-hive", "role/contributor", "author/clanker"), "check-failing:unit") + rec, _ := h.e.stageStoreOrShared().Get(stageKey("acme", "widget", 7)) + if !rec.AdoptedInPlace() { + t.Fatalf("maintainer's adoption released under adopt: %+v", rec) + } +} + +// ask: a maintainer's due adoption is held and recorded as blocked +// (author-is-maintainer) for the tracker; the owner's Adopt — the +// adoption/supersede request label — lifts the hold on the next pass. +func TestMaintainerPolicyAskHoldsThenOwnerAdopts(t *testing.T) { + h, done := newAdoptHarness(t, ContributorNudgeOutcome{Mode: "comment"}, maintainerPolicyWith(config.AdoptionMaintainerPolicyAsk)) + defer done() + h.adopt.permissions = map[string]string{"mallory": "maintain"} + h.adopt.allowMaintainerEdits(7, true) + h.observe(adoptPR(7, "aaa"), "check-failing:unit") + key := stageKey("acme", "widget", 7) + h.clock.advance(2 * time.Hour) + h.observe(adoptPR(7, "aaa", maintainerLabels072, "role/contributor", "author/clanker"), "check-failing:unit") + rec, _ := h.e.stageStoreOrShared().Get(key) + if rec.AdoptedHead != "" || len(adoptionComments(h.api)) != 0 { + t.Fatalf("ask adopted on its own: %+v", rec) + } + if got := rec.AdoptionBlocked("aaa"); got != stagelabels.AdoptBlockedAuthorMaintainer { + t.Fatalf("blocked reason = %q, want %q (%+v)", got, stagelabels.AdoptBlockedAuthorMaintainer, rec) + } + if rec.AdoptBlockedAt.IsZero() || rec.AdoptionBlocked("bbb") != "" { + t.Fatalf("blocked stamp: %+v", rec) + } + // A non-maintainer under ask is adopted as usual. + h.adopt.permissions = map[string]string{"mallory": "write"} + h.clock.advance(maintainerPermTTL + time.Minute) + h.observe(adoptPR(7, "aaa", maintainerLabels072, "role/contributor", "author/clanker"), "check-failing:unit") + if rec, _ = h.e.stageStoreOrShared().Get(key); !rec.AdoptedInPlace() { + t.Fatalf("write-level author not adopted under ask: %+v", rec) + } +} + +func TestMaintainerPolicyAskOwnerRequestLiftsHold(t *testing.T) { + h, done := newAdoptHarness(t, ContributorNudgeOutcome{Mode: "comment"}, maintainerPolicyWith(config.AdoptionMaintainerPolicyAsk)) + defer done() + h.adopt.permissions = map[string]string{"mallory": "admin"} + h.adopt.allowMaintainerEdits(7, true) + h.observe(adoptPR(7, "aaa"), "check-failing:unit") + key := stageKey("acme", "widget", 7) + h.clock.advance(2 * time.Hour) + h.observe(adoptPR(7, "aaa", maintainerLabels072, "role/contributor", "author/clanker"), "check-failing:unit") + if rec, _ := h.e.stageStoreOrShared().Get(key); rec.AdoptionBlocked("aaa") == "" { + t.Fatalf("setup: not held: %+v", rec) + } + // The owner clicks Adopt: the dashboard sets adoption/supersede. + h.clock.advance(time.Minute) + h.observe(adoptPR(7, "aaa", maintainerLabels072, "role/contributor", "author/clanker", delegatedecision.LabelAdoptSupersede), "check-failing:unit") + rec, _ := h.e.stageStoreOrShared().Get(key) + if rec.AdoptedHead != "aaa" { + t.Fatalf("owner's Adopt did not adopt: %+v", rec) + } + if rec.AdoptionBlocked("aaa") != "" { + t.Fatalf("blocked mark survived the adoption: %+v", rec) + } + // And the adoption is kept on later passes (only never releases). + h.clock.advance(maintainerPermTTL + time.Minute) + h.observe(adoptPR(7, "aaa", "stage/074-adopted-by-hive", "role/contributor", "author/clanker", delegatedecision.LabelAdoptSupersede), "check-failing:unit") + if rec, _ = h.e.stageStoreOrShared().Get(key); rec.AdoptedHead != "aaa" { + t.Fatalf("owner-requested adoption released under ask: %+v", rec) + } +} + +// never: the pre-#14524 rule, held and released; the tracker sees no +// owner action (no blocked mark is written, the policy is not ask). +func TestMaintainerPolicyNeverHoldsWithoutAsking(t *testing.T) { + h, done := newAdoptHarness(t, ContributorNudgeOutcome{Mode: "comment"}, maintainerPolicyWith(config.AdoptionMaintainerPolicyNever)) + defer done() + h.adopt.permissions = map[string]string{"mallory": "admin"} + h.adopt.allowMaintainerEdits(7, true) + h.observe(adoptPR(7, "aaa"), "check-failing:unit") + h.clock.advance(2 * time.Hour) + h.observe(adoptPR(7, "aaa", maintainerLabels072, "role/contributor", "author/clanker", delegatedecision.LabelAdoptSupersede), "check-failing:unit") + rec, _ := h.e.stageStoreOrShared().Get(stageKey("acme", "widget", 7)) + if rec.AdoptedHead != "" { + t.Fatalf("never adopted a maintainer (even on request): %+v", rec) + } + if got := rec.AdoptionBlocked("aaa"); got != stagelabels.AdoptBlockedAuthorMaintainer { + t.Fatalf("never should still record why for the row: %q (%+v)", got, rec) + } +} diff --git a/src/pkg/github/automerge/automerge_adopt_maintainer_test.go b/src/pkg/github/automerge/automerge_adopt_maintainer_test.go index 1f0a55c971..cc814db122 100644 --- a/src/pkg/github/automerge/automerge_adopt_maintainer_test.go +++ b/src/pkg/github/automerge/automerge_adopt_maintainer_test.go @@ -8,14 +8,27 @@ import ( "testing" "time" + "github.com/hivecommons/hive/pkg/config" "github.com/hivecommons/hive/pkg/delegatedecision" "github.com/hivecommons/hive/pkg/stagelabels" ) // projectbluefin/utah-packages#619: the author was a repository admin. The // hive nudged the PR at 072, adopted it as contributor-offline 16 minutes -// later and then re-homed it, closing the admin's own PR. Adoption stands in -// for a quiet contributor relay, never for a maintainer. +// later and then re-homed it, closing the admin's own PR. That rule became +// governor.labels.stage.adoption.maintainer_policy: never. The default is +// adopt since hivecommons/hive#14524 (a maintainer's own clanker PR sat at +// 072 for 26h with its hive offline): clanker PRs are adoptable on +// disconnect regardless of the owner's repo role. The tests below pin +// `never` where they exercise the hands-off rule; see +// automerge_adopt_maintainer_policy_test.go for adopt and ask. + +// maintainerNeverPolicy is adoptPolicy() under maintainer_policy: never. +func maintainerNeverPolicy() StageLabelPolicy { + p := adoptPolicy() + p.AdoptionMaintainerPolicy = config.AdoptionMaintainerPolicyNever + return p +} func TestRepoMaintainerLevel(t *testing.T) { for _, tc := range []struct { @@ -39,7 +52,7 @@ func TestRepoMaintainerLevel(t *testing.T) { func TestAdoptionSkipsRepositoryMaintainer(t *testing.T) { for _, role := range []string{"admin", "maintain"} { t.Run(role, func(t *testing.T) { - p := adoptPolicy() + p := maintainerNeverPolicy() p.AdoptInPlace = true h, done := newAdoptHarness(t, ContributorNudgeOutcome{Mode: "comment"}, p) defer done() @@ -67,7 +80,7 @@ func TestAdoptionSkipsRepositoryMaintainer(t *testing.T) { } func TestAdoptionFailsClosedOnPermissionError(t *testing.T) { - h, done := newAdoptHarness(t, ContributorNudgeOutcome{Mode: "comment"}, adoptPolicy()) + h, done := newAdoptHarness(t, ContributorNudgeOutcome{Mode: "comment"}, maintainerNeverPolicy()) defer done() h.adopt.failPermission = true h.observe(adoptPR(7, "aaa"), "check-failing:unit") @@ -89,7 +102,7 @@ func TestAdoptionFailsClosedOnPermissionError(t *testing.T) { // An in-place adoption taken before the author was known to maintain the // repository is released on the next pass and never re-homed. func TestInPlaceAdoptionOfMaintainerIsReleased(t *testing.T) { - p := adoptPolicy() + p := maintainerNeverPolicy() p.AdoptInPlace = true h, done := newAdoptHarness(t, ContributorNudgeOutcome{Mode: "comment"}, p) defer done() @@ -119,7 +132,7 @@ func TestInPlaceAdoptionOfMaintainerIsReleased(t *testing.T) { // The permission cache is keyed by repository and author, expires after // maintainerPermTTL, and never caches a failed read. func TestMaintainerPermissionCache(t *testing.T) { - h, done := newAdoptHarness(t, ContributorNudgeOutcome{}, adoptPolicy()) + h, done := newAdoptHarness(t, ContributorNudgeOutcome{}, maintainerNeverPolicy()) defer done() h.adopt.permissions = map[string]string{"mallory": "admin"} ctx := context.Background() @@ -164,7 +177,7 @@ func TestMaintainerPermissionCache(t *testing.T) { // hivecommons/hive#14313: the cache mutex guards map access only; it is not // held while GetPermissionLevel is in flight. func TestMaintainerPermissionLockNotHeldAcrossAPICall(t *testing.T) { - h, done := newAdoptHarness(t, ContributorNudgeOutcome{}, adoptPolicy()) + h, done := newAdoptHarness(t, ContributorNudgeOutcome{}, maintainerNeverPolicy()) defer done() var held atomic.Bool h.adopt.onPermission = func() { @@ -187,7 +200,7 @@ func TestMaintainerPermissionLockNotHeldAcrossAPICall(t *testing.T) { // is neither released nor re-homed until the read succeeds. func TestPermissionUnreadableKeepsLiveAdoption(t *testing.T) { t.Run("in-place", func(t *testing.T) { - p := adoptPolicy() + p := maintainerNeverPolicy() p.AdoptInPlace = true h, done := newAdoptHarness(t, ContributorNudgeOutcome{Mode: "comment"}, p) defer done() @@ -212,7 +225,7 @@ func TestPermissionUnreadableKeepsLiveAdoption(t *testing.T) { } }) t.Run("supersede", func(t *testing.T) { - h, done := newAdoptHarness(t, ContributorNudgeOutcome{}, adoptPolicy()) + h, done := newAdoptHarness(t, ContributorNudgeOutcome{}, maintainerNeverPolicy()) defer done() h.observe(adoptPR(7, "aaa"), "check-failing:unit") key := stageKey("acme", "widget", 7) @@ -247,7 +260,7 @@ func TestMaintainerAdoptionReleaseClosesOpenSuperseder(t *testing.T) { {name: "merged", state: "closed", merged: true}, } { t.Run(tc.name, func(t *testing.T) { - h, done := newAdoptHarness(t, ContributorNudgeOutcome{}, adoptPolicy()) + h, done := newAdoptHarness(t, ContributorNudgeOutcome{}, maintainerNeverPolicy()) defer done() h.adopt.permissions = map[string]string{"mallory": "admin"} h.observe(adoptPR(7, "aaa"), "check-failing:unit") @@ -289,7 +302,7 @@ func TestMaintainerAdoptionReleaseClosesOpenSuperseder(t *testing.T) { } func TestMaintainerSupersederCloseFailureKeepsAdoption(t *testing.T) { - h, done := newAdoptHarness(t, ContributorNudgeOutcome{}, adoptPolicy()) + h, done := newAdoptHarness(t, ContributorNudgeOutcome{}, maintainerNeverPolicy()) defer done() h.adopt.permissions = map[string]string{"mallory": "admin"} h.observe(adoptPR(7, "aaa"), "check-failing:unit") @@ -308,11 +321,11 @@ func TestMaintainerSupersederCloseFailureKeepsAdoption(t *testing.T) { } func TestSupersedeMaintainerRefusesBeforeMutation(t *testing.T) { - h, done := newAdoptHarness(t, ContributorNudgeOutcome{}, adoptPolicy()) + h, done := newAdoptHarness(t, ContributorNudgeOutcome{}, maintainerNeverPolicy()) defer done() h.adopt.permissions = map[string]string{"mallory": "admin"} obs := stageObservation{Owner: "acme", Repo: "widget", Author: "mallory", Number: 7, HeadSHA: "aaa", BaseRef: "v5"} - if _, err := h.e.supersedeAdoptedPR(context.Background(), h.e.stageStoreOrShared(), stageKey("acme", "widget", 7), obs, stagelabels.Record{}, adoptPolicy(), AdoptReasonDCORehome, 0, false, true, h.clock.at); err != nil { + if _, err := h.e.supersedeAdoptedPR(context.Background(), h.e.stageStoreOrShared(), stageKey("acme", "widget", 7), obs, stagelabels.Record{}, maintainerNeverPolicy(), AdoptReasonDCORehome, 0, false, true, h.clock.at); err != nil { t.Fatal(err) } if h.adopt.refAttempts != 0 || len(h.adopt.pulls) != 0 || len(h.adopt.prEdits) != 0 { @@ -321,7 +334,7 @@ func TestSupersedeMaintainerRefusesBeforeMutation(t *testing.T) { } func TestDelegatedSupersedeCannotTakeOverMaintainer(t *testing.T) { - h, done := newAdoptHarness(t, ContributorNudgeOutcome{}, adoptPolicy()) + h, done := newAdoptHarness(t, ContributorNudgeOutcome{}, maintainerNeverPolicy()) defer done() h.adopt.permissions = map[string]string{"mallory": "maintain"} labels := []string{"stage/085-needs-decision", delegatedecision.LabelAdoptSupersede} diff --git a/src/pkg/github/automerge/automerge_contributor_adopt.go b/src/pkg/github/automerge/automerge_contributor_adopt.go index 9b4decacde..c01af38c99 100644 --- a/src/pkg/github/automerge/automerge_contributor_adopt.go +++ b/src/pkg/github/automerge/automerge_contributor_adopt.go @@ -11,6 +11,7 @@ import ( "time" gh "github.com/google/go-github/v72/github" + "github.com/hivecommons/hive/pkg/config" "github.com/hivecommons/hive/pkg/delegatedecision" "github.com/hivecommons/hive/pkg/effects" hgithub "github.com/hivecommons/hive/pkg/github" @@ -591,10 +592,18 @@ 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 maintainer, err := c.authorMaintainsRepo(ctx, obs, now); maintainer || err != nil { - c.info("stage labels: adoption due but the author maintains the repository; not adopting", "repo", obs.Display, "pr", obs.Number, "author", obs.Author, "deferred", err != nil) + 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. + store.NoteAdoptionBlocked(key, obs.HeadSHA, stagelabels.AdoptBlockedAuthorMaintainer, now) + c.info("stage labels: adoption due but the author maintains the repository; not adopting", "repo", obs.Display, "pr", obs.Number, "author", obs.Author, "policy", policy.maintainerPolicy(), "deferred", false) + } else { + c.info("stage labels: adoption due but the author's repository permission is unreadable; deferred", "repo", obs.Display, "pr", obs.Number, "author", obs.Author, "policy", policy.maintainerPolicy()) + } return 0, nil } + store.ClearAdoptionBlocked(key) fence, err := c.adoptionDiffRefusal(ctx, obs) if fence != "" && (err != nil || adoptionFenceDefers(fence)) { // The fence could not judge this head (it moved, or its file list @@ -670,13 +679,12 @@ 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) { - maintainer, err := c.authorMaintainsRepo(ctx, obs, now) - if err != nil { + if maintainer, deferred := c.maintainerReleasesAdoption(ctx, obs, policy, now); deferred { return 0, nil - } - if maintainer { - // Backstop for every re-home path (dco-rehome, in-place-stalled): - // a maintainer's PR is never closed in favour of a hive copy. + } else if maintainer { + // Backstop for every re-home path (dco-rehome, in-place-stalled) + // under maintainer_policy: never — a maintainer's PR is never + // closed in favour of a hive copy. c.info("stage labels: not superseding a repository maintainer's PR; adoption released", "repo", obs.Display, "pr", obs.Number, "author", obs.Author, "reason", reason) return c.releaseMaintainerAdoption(ctx, store, key, obs, rec.AdoptedBy) } @@ -915,14 +923,12 @@ func (c *Engine) settleAdoption(ctx context.Context, store *stagelabels.Store, k if !ok { return 0, nil } - maintainer, err := c.authorMaintainsRepo(ctx, obs, now) - if err != nil { + if maintainer, deferred := c.maintainerReleasesAdoption(ctx, obs, policy, now); deferred { // No evidence either way: neither re-home nor release this pass. return 0, nil - } - if maintainer { - // Supersede adoption taken before this rule, or before the - // author's permission was raised: hand the PR back. + } else if maintainer { + // maintainer_policy: never — a supersede adoption taken before the + // rule, or before the author's permission was raised, is handed back. c.info("stage labels: adoption of a repository maintainer's PR released", "repo", obs.Display, "pr", obs.Number, "author", obs.Author, "superseded_by", rec.AdoptedBy) return c.releaseMaintainerAdoption(ctx, store, key, obs, rec.AdoptedBy) } @@ -1119,6 +1125,56 @@ func (c *Engine) authorMaintainsRepo(ctx context.Context, obs stageObservation, return maintainer, nil } +// maintainerPolicy resolves the policy's maintainer rule ("" = adopt). +func (p StageLabelPolicy) maintainerPolicy() string { + switch strings.ToLower(strings.TrimSpace(p.AdoptionMaintainerPolicy)) { + case config.AdoptionMaintainerPolicyAsk: + return config.AdoptionMaintainerPolicyAsk + case config.AdoptionMaintainerPolicyNever: + return config.AdoptionMaintainerPolicyNever + } + return config.AdoptionMaintainerPolicyAdopt +} + +// maintainerHoldsAdoption applies governor.labels.stage.adoption.maintainer_policy +// to an adoption that is due (hivecommons/hive#14524). adopt: the author's +// role is not read and never holds (a clanker PR whose hive disconnected +// is adoptable whoever its author is). never: a maintainer's PR is held +// outright. ask: held until a person asks for it — the owner's Adopt +// (the adoption/supersede request label, `requested`) lifts the hold. +// deferred is true when the role could not be read; the caller then +// neither adopts nor records anything. +func (c *Engine) maintainerHoldsAdoption(ctx context.Context, obs stageObservation, policy StageLabelPolicy, requested bool, now time.Time) (held, deferred bool) { + switch policy.maintainerPolicy() { + case config.AdoptionMaintainerPolicyAdopt: + return false, false + case config.AdoptionMaintainerPolicyAsk: + if requested { + return false, false + } + } + maintainer, err := c.authorMaintainsRepo(ctx, obs, now) + if err != nil { + return false, true + } + return maintainer, false +} + +// maintainerReleasesAdoption is the settle-side twin: only under +// maintainer_policy: never does an existing adoption of a maintainer's PR +// get released (or a re-home refused). Under adopt and ask the adoption +// stands — under ask it was a person's decision. +func (c *Engine) maintainerReleasesAdoption(ctx context.Context, obs stageObservation, policy StageLabelPolicy, now time.Time) (maintainer, deferred bool) { + if policy.maintainerPolicy() != config.AdoptionMaintainerPolicyNever { + return false, false + } + m, err := c.authorMaintainsRepo(ctx, obs, now) + if err != nil { + return false, true + } + return m, false +} + // AdoptionMaintainerSupersederMarker is stamped on the note that closes the // hive's superseding PR when the original turns out to be a maintainer's. const AdoptionMaintainerSupersederMarker = "" @@ -1248,14 +1304,13 @@ func (c *Engine) baseSyncTouchesWorkflows(ctx context.Context, obs stageObservat // Returns the number of comments posted. func (c *Engine) settleInPlaceAdoption(ctx context.Context, store *stagelabels.Store, key string, obs stageObservation, prev stagelabels.Record, policy StageLabelPolicy, now time.Time) (int, error) { if prev.AdoptedInPlace() { - maintainer, err := c.authorMaintainsRepo(ctx, obs, now) - if err != nil { + if maintainer, deferred := c.maintainerReleasesAdoption(ctx, obs, policy, now); deferred { // No evidence either way: keep the adoption as it is. return 0, nil - } - if maintainer { - // Taken over before this rule, or before the author's permission - // was raised: hand the PR back rather than keep or re-home it. + } else if maintainer { + // maintainer_policy: never — taken over before the rule, or + // before the author's permission was raised: hand the PR back + // rather than keep or re-home it. c.info("stage labels: in-place adoption of a repository maintainer's PR released", "repo", obs.Display, "pr", obs.Number, "author", obs.Author) return c.releaseMaintainerAdoption(ctx, store, key, obs, prev.AdoptedBy) } @@ -1531,7 +1586,7 @@ func (c *Engine) escapeStalledAdoption(ctx context.Context, store *stagelabels.S // Read the author's permission before the attempt is recorded: an // unreadable answer leaves the in-place adoption untouched, and a // maintainer's adoption is released by settleInPlaceAdoption. - if maintainer, err := c.authorMaintainsRepo(ctx, obs, now); maintainer || err != nil { + if maintainer, deferred := c.maintainerReleasesAdoption(ctx, obs, policy, now); maintainer || deferred { return adoptionEscape{}, 0, nil } // Re-read the current diff before copying a head. A concurrent push diff --git a/src/pkg/github/automerge/automerge_stage_labels.go b/src/pkg/github/automerge/automerge_stage_labels.go index 997eb1fcd3..c2dd02b8b6 100644 --- a/src/pkg/github/automerge/automerge_stage_labels.go +++ b/src/pkg/github/automerge/automerge_stage_labels.go @@ -88,6 +88,11 @@ type StageLabelPolicy struct { // Every other contributor-lane gate still applies; the head must be // exactly the one the stage store records as adopted/pushed by the hive. AdoptionAutoMerge bool + // AdoptionMaintainerPolicy is governor.labels.stage.adoption.maintainer_policy + // (config.AdoptionMaintainerPolicy*): what adoption does when the PR + // author holds admin or maintain on the repository. "" reads as the + // default, adopt (hivecommons/hive#14524). + AdoptionMaintainerPolicy string // DCORequired resolves the per-repo `governor.labels.stage.dco.required` // override for "owner/repo"; ok false means "detect" (a DCO context in // the branch's required checks or on the head). nil = always detect. diff --git a/src/pkg/stagelabels/adoption_blocked_test.go b/src/pkg/stagelabels/adoption_blocked_test.go new file mode 100644 index 0000000000..6290c0ea0c --- /dev/null +++ b/src/pkg/stagelabels/adoption_blocked_test.go @@ -0,0 +1,77 @@ +package stagelabels + +import ( + "path/filepath" + "testing" + "time" +) + +// The adoption hold the activity monitor reads (hivecommons/hive#14524): +// noted per head, ignored once the head moves or the PR is adopted, +// cleared when adoption proceeds. +func TestStoreAdoptionBlocked(t *testing.T) { + now := time.Date(2026, 10, 28, 12, 0, 0, 0, time.UTC) + clock := func() time.Time { return now } + st := NewStore(filepath.Join(t.TempDir(), "s.json"), clock) + key := Key("hivecommons/hive", 14524) + + // Unknown key or empty head/reason: no-op. + st.NoteAdoptionBlocked(key, "aaa", AdoptBlockedAuthorMaintainer, now) + if _, ok := st.Get(key); ok { + t.Fatal("note created a record") + } + st.Observe(key, ReturnedToContributor, "check-failing:unit") + st.NoteAdoptionBlocked(key, "", AdoptBlockedAuthorMaintainer, now) + st.NoteAdoptionBlocked(key, "aaa", "", now) + if r, _ := st.Get(key); r.AdoptBlockedHead != "" || r.AdoptBlockedBy != "" { + t.Fatalf("empty note recorded: %+v", r) + } + + st.NoteAdoptionBlocked(key, "aaa", AdoptBlockedAuthorMaintainer, now) + r, _ := st.Get(key) + if got := r.AdoptionBlocked("aaa"); got != AdoptBlockedAuthorMaintainer || !r.AdoptBlockedAt.Equal(now) { + t.Fatalf("blocked: %q %+v", got, r) + } + if r.AdoptionBlocked("bbb") != "" || r.AdoptionBlocked("") != "" { + t.Fatal("stale head reported as blocked") + } + // Re-noting the same hold keeps the first stamp. + st.NoteAdoptionBlocked(key, "aaa", AdoptBlockedAuthorMaintainer, now.Add(time.Hour)) + if r, _ = st.Get(key); !r.AdoptBlockedAt.Equal(now) { + t.Fatalf("re-note moved the stamp: %+v", r) + } + + st.ClearAdoptionBlocked(key) + if r, _ = st.Get(key); r.AdoptionBlocked("aaa") != "" || r.AdoptBlockedHead != "" || !r.AdoptBlockedAt.IsZero() { + t.Fatalf("clear left state: %+v", r) + } + + // Adoption clears the hold too, in place and by supersession. + st.NoteAdoptionBlocked(key, "aaa", AdoptBlockedAuthorMaintainer, now) + st.MarkAdopted(key, "aaa", 14977, now) + if r, _ = st.Get(key); r.AdoptionBlocked("aaa") != "" || r.AdoptBlockedBy != "" { + t.Fatalf("MarkAdopted kept the hold: %+v", r) + } + key2 := Key("hivecommons/hive", 2) + st.Observe(key2, ReturnedToContributor, "check-failing:unit") + st.NoteAdoptionBlocked(key2, "ccc", AdoptBlockedAuthorMaintainer, now) + st.MarkAdoptedInPlace(key2, "ccc", "contributor-offline", now) + if r, _ = st.Get(key2); r.AdoptionBlocked("ccc") != "" || r.AdoptBlockedBy != "" { + t.Fatalf("MarkAdoptedInPlace kept the hold: %+v", r) + } + + // Persisted across a reload. + key3 := Key("hivecommons/hive", 3) + st.Observe(key3, ReturnedToContributor, "check-failing:unit") + st.NoteAdoptionBlocked(key3, "ddd", AdoptBlockedAuthorMaintainer, now) + if err := st.Save(); err != nil { + t.Fatal(err) + } + again := NewStore(st.path, clock) + if err := again.Load(); err != nil { + t.Fatal(err) + } + if r, ok := again.Get(key3); !ok || r.AdoptionBlocked("ddd") != AdoptBlockedAuthorMaintainer { + t.Fatalf("hold not persisted: %+v", r) + } +} diff --git a/src/pkg/stagelabels/store.go b/src/pkg/stagelabels/store.go index 64388a0026..4f21deba16 100644 --- a/src/pkg/stagelabels/store.go +++ b/src/pkg/stagelabels/store.go @@ -174,6 +174,16 @@ type Record struct { // for; it survives ClearAdoptionEscalation so a blocker that flaps on // one head is noted once. AdoptEscalationNotedHead string `json:"adopt_escalation_noted_head,omitempty"` + // AdoptBlockedHead / AdoptBlockedBy / AdoptBlockedAt record that + // adoption came due at this head and the engine held it for a reason a + // person must settle (AdoptBlockedAuthorMaintainer: the author + // maintains the repository under maintainer_policy: ask — + // hivecommons/hive#14524). The activity monitor reads it to say why a + // nudged PR is not adopted and to offer Adopt; adoption or a new nudge + // head clears it. + AdoptBlockedHead string `json:"adopt_blocked_head,omitempty"` + AdoptBlockedBy string `json:"adopt_blocked_by,omitempty"` + AdoptBlockedAt time.Time `json:"adopt_blocked_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. @@ -970,6 +980,7 @@ func (s *Store) MarkAdoptedInPlace(key, head, reason string, now time.Time) { } r.AdoptedHead, r.AdoptedBy, r.AdoptedAt, r.AdoptCheckedAt = head, 0, now, now r.AdoptMode, r.AdoptReason = AdoptModeInPlace, reason + r.AdoptBlockedHead, r.AdoptBlockedBy, r.AdoptBlockedAt = "", "", time.Time{} r.AdoptedHeadAt = now s.items[key] = r s.dirty = true @@ -1062,10 +1073,54 @@ 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{} s.items[key] = r s.dirty = true } +// AdoptBlockedAuthorMaintainer is the AdoptBlockedBy reason for a due +// adoption held under governor.labels.stage.adoption.maintainer_policy: ask. +const AdoptBlockedAuthorMaintainer = "author-is-maintainer" + +// NoteAdoptionBlocked records that adoption is due at head but held for +// reason; the first sighting's time is kept while head and reason hold. +func (s *Store) NoteAdoptionBlocked(key, head, reason string, now time.Time) { + s.mu.Lock() + defer s.mu.Unlock() + r, ok := s.items[key] + if !ok || head == "" || reason == "" { + return + } + if r.AdoptBlockedHead == head && r.AdoptBlockedBy == reason { + return + } + r.AdoptBlockedHead, r.AdoptBlockedBy, r.AdoptBlockedAt = head, reason, now + s.items[key] = r + s.dirty = true +} + +// ClearAdoptionBlocked forgets a held adoption (it went ahead, or the +// policy no longer holds it). +func (s *Store) ClearAdoptionBlocked(key string) { + s.mu.Lock() + defer s.mu.Unlock() + r, ok := s.items[key] + if !ok || r.AdoptBlockedHead == "" && r.AdoptBlockedBy == "" { + return + } + r.AdoptBlockedHead, r.AdoptBlockedBy, r.AdoptBlockedAt = "", "", time.Time{} + s.items[key] = r + s.dirty = true +} + +// AdoptionBlocked reports the reason a due adoption at head is held, or "". +func (r Record) AdoptionBlocked(head string) string { + if head == "" || r.AdoptBlockedHead != head || r.Adopted(head) { + return "" + } + return r.AdoptBlockedBy +} + // NoteAdoptReason records why the current adoption happened (the marker's // reason=) on an existing record. func (s *Store) NoteAdoptReason(key, reason string) {