From 3e916f76ad015cd52bc362a80c0c6688cdb8836e Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Wed, 18 Nov 2026 00:17:55 -0500 Subject: [PATCH 1/2] =?UTF-8?q?=F0=9F=90=9B=20Contributor=20lane:=20grace?= =?UTF-8?q?=20window=20before=20claiming=20owner/hive-filed=20issues?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes #18898 Signed-off-by: Andrew Anderson --- .../added-18898-contributor-owner-grace.md | 1 + src/cmd/hive/claims_admission_test.go | 37 ++++ src/cmd/hive/claimswire.go | 6 + src/cmd/hive/github_client_config.go | 1 + src/cmd/hive/main.go | 13 ++ src/docs/contributor-relay.md | 2 + src/docs/operator-reference/README.md | 2 +- src/pkg/config/claims.go | 24 +++ src/pkg/config/claims_grace_test.go | 27 +++ src/pkg/dashboard/contribute_admission.go | 37 ++++ src/pkg/dashboard/contribute_ledgers.go | 14 ++ .../dashboard/contribute_owner_grace_test.go | 63 +++++++ src/pkg/dashboard/contribute_select.go | 5 + src/pkg/dashboard/contribute_sse.go | 1 + src/pkg/dashboard/contribute_withheld.go | 6 + src/pkg/dashboard/contribute_withheld_test.go | 1 + src/pkg/dashboard/convergence_kick.go | 1 + src/pkg/dashboard/deps.go | 9 + .../dashboard/settings_parity_allowlist.txt | 1 + src/pkg/github/client.go | 3 + src/pkg/github/issue_claim_gate.go | 28 +++ src/pkg/github/issue_contributor_grace.go | 175 ++++++++++++++++++ .../github/issue_contributor_grace_test.go | 146 +++++++++++++++ 23 files changed, 602 insertions(+), 1 deletion(-) create mode 100644 changelog.d/added-18898-contributor-owner-grace.md create mode 100644 src/pkg/config/claims_grace_test.go create mode 100644 src/pkg/dashboard/contribute_owner_grace_test.go create mode 100644 src/pkg/github/issue_contributor_grace.go create mode 100644 src/pkg/github/issue_contributor_grace_test.go diff --git a/changelog.d/added-18898-contributor-owner-grace.md b/changelog.d/added-18898-contributor-owner-grace.md new file mode 100644 index 0000000000..96d82b0769 --- /dev/null +++ b/changelog.d/added-18898-contributor-owner-grace.md @@ -0,0 +1 @@ +- **The contributor lane waits 15 minutes before claiming an issue an owner, maintainer or the hive itself just filed.** `governor.claims.contributor_grace_s` (default `900`; negative turns it off) withholds an issue whose author is an owner/maintainer (author association `OWNER`, `MEMBER`, `COLLABORATOR`) or this hive's own App from `selectTask` and the Ready queue (Withheld reason `owner_grace`) and refuses a contributor's fresh ledger claim with `owner grace: filed by 3m ago; ...`, so the owner or the owner's dispatcher can claim first; #18866 and #18880 each grew a duplicate contributor PR because the lane claimed within seconds of filing. A person adding `help wanted` after filing waives the grace. Live leases, hive agents and outside reporters are unaffected. ([#18898](https://github.com/hivecommons/hive/issues/18898), part of [#18890](https://github.com/hivecommons/hive/issues/18890)). diff --git a/src/cmd/hive/claims_admission_test.go b/src/cmd/hive/claims_admission_test.go index 7822cbdb38..4fc26890f4 100644 --- a/src/cmd/hive/claims_admission_test.go +++ b/src/cmd/hive/claims_admission_test.go @@ -12,6 +12,7 @@ import ( "strings" "sync/atomic" "testing" + "time" "github.com/hivecommons/hive/pkg/claims" "github.com/hivecommons/hive/pkg/config" @@ -294,3 +295,39 @@ func TestRecordAgentStartFiledClaimLedgersSelfFiledIssue(t *testing.T) { t.Fatalf("another agent's dispatch of the self-filed issue = %+v, %v; want held by scanner", res, err) } } + +// hivecommons/hive#18898: a contributor's fresh claim on an issue an owner +// filed moments ago is refused with the owner-grace reason; the same issue +// after the window, or a hive agent's own claim on it, is admitted. +func TestContributorClaimRefusedInsideOwnerGrace(t *testing.T) { + var ageMin atomic.Int64 + ageMin.Store(2) + api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/repos/o/r/issues/7" { + http.NotFound(w, r) + return + } + created := time.Now().Add(-time.Duration(ageMin.Load()) * time.Minute).UTC().Format(time.RFC3339) + fmt.Fprintf(w, `{"number":7,"state":"open","created_at":%q,"author_association":"OWNER","user":{"login":"andy"},"labels":[]}`, created) + })) + defer api.Close() + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + client := github.NewClientForTest(api.URL, "o", []string{"r"}, logger) + client.SetContributorGrace(15 * time.Minute) + ledger := testClaimsLedger(t) + installClaimAdmissionCheck(context.Background(), ledger, func() *github.Client { return client }) + + req := claims.Request{Repo: "o/r", Issue: 7, Holder: "karibhou", HolderID: "c-1", Kind: claims.KindContributor} + res, err := ledger.Claim(req) + if err != nil || res.Outcome != claims.OutcomeRefused || !strings.HasPrefix(res.Reason, github.ClaimBlockReasonOwnerGracePrefix) { + t.Fatalf("claim inside the grace = %+v, %v; want refused with the owner grace reason", res, err) + } + if _, held := ledger.Lookup("o/r", 7); held { + t.Fatal("a refused contributor claim must not be recorded") + } + ageMin.Store(30) + res, err = ledger.Claim(req) + if err != nil || res.Outcome != claims.OutcomeClaimed { + t.Fatalf("claim after the grace = %+v, %v; want claimed", res, err) + } +} diff --git a/src/cmd/hive/claimswire.go b/src/cmd/hive/claimswire.go index 133cb34467..9749b3c8ec 100644 --- a/src/cmd/hive/claimswire.go +++ b/src/cmd/hive/claimswire.go @@ -224,6 +224,12 @@ func installClaimAdmissionCheck(ctx context.Context, ledger *claims.Ledger, clie if req.Kind == claims.KindAgent { return gh.IssueStartBlockReason(ctx, req.Repo, req.Issue, req.Holder) } + // A contributor's fresh claim also waits out the owner grace on + // an issue an owner, maintainer or this hive filed moments ago + // (hivecommons/hive#18898). + if req.Kind == claims.KindContributor { + return gh.IssueContributorDispatchBlockReason(ctx, req.Repo, req.Issue) + } return gh.IssueDispatchBlockReason(ctx, req.Repo, req.Issue) } return gh.IssueClaimBlockReason(ctx, req.Repo, req.Issue) diff --git a/src/cmd/hive/github_client_config.go b/src/cmd/hive/github_client_config.go index 560424f677..30cecf8b23 100644 --- a/src/cmd/hive/github_client_config.go +++ b/src/cmd/hive/github_client_config.go @@ -104,6 +104,7 @@ func (b *boot) applyGitHubClientConfigHooks(client *github.Client) { // Umbrella issues no automated claim may take and no claim stages // (governor.claims.never_claim_labels, default `epic`). client.SetNeverClaimLabels(b.cfg.Governor.Claims.EffectiveNeverClaimLabels()) + client.SetContributorGrace(b.cfg.Governor.Claims.EffectiveContributorGrace()) // Pre-dispatch open-PR guard (hivecommons/hive#14799, // scanner.skip_issues_with_open_pr, default on). client.SetSkipIssuesWithOpenPR(b.cfg.Scanner.IsSkipIssuesWithOpenPR()) diff --git a/src/cmd/hive/main.go b/src/cmd/hive/main.go index 06ff7bcc08..a4ba3687ba 100644 --- a/src/cmd/hive/main.go +++ b/src/cmd/hive/main.go @@ -1210,6 +1210,17 @@ func (b *boot) wireBootClosures() { IssueClaimed: func(repo string, number int) (github.IssueClaim, bool) { return getClaimLedger(b.logger).Lookup(repo, number) }, + // hivecommons/hive#18898: an issue an owner, maintainer or this hive + // filed inside the contributor grace window is not offered yet. + ContributorHold: func(repo string, number int, createdAt time.Time) string { + client := b.currentGitHubClient() + if client == nil { + return "" + } + ctx, cancel := context.WithTimeout(context.Background(), openPRLinkGuardTimeout) + defer cancel() + return client.ContributorGraceGuard(ctx, repo, number, createdAt) + }, // hivecommons/hive#14799: the ledger above is one eval cycle old; // ask the forge directly whether an open PR already links the // issue before the contribute lane dispatches it again. @@ -2531,6 +2542,7 @@ func (b *boot) bootStateWith(deps bootStateDeps) { b.observeWritebackRepos() b.ghClient.SetHoldLabels(b.githubHoldLabels()) b.ghClient.SetNeverClaimLabels(b.cfg.Governor.Claims.EffectiveNeverClaimLabels()) + b.ghClient.SetContributorGrace(b.cfg.Governor.Claims.EffectiveContributorGrace()) b.ghClient.SetSkipIssuesWithOpenPR(b.cfg.Scanner.IsSkipIssuesWithOpenPR()) b.ghClient.SetSentinelAlertLabel(b.cfg.Sentinel.LabelOrDefault()) if len(b.cfg.Governor.Labels.Exempt) > 0 { @@ -5865,6 +5877,7 @@ func (b *boot) bootHeartbeatWith(deps bootHeartbeatDeps) { } b.ghClient.SetHoldLabels(b.githubHoldLabels()) b.ghClient.SetNeverClaimLabels(b.cfg.Governor.Claims.EffectiveNeverClaimLabels()) + b.ghClient.SetContributorGrace(b.cfg.Governor.Claims.EffectiveContributorGrace()) b.ghClient.SetSkipIssuesWithOpenPR(b.cfg.Scanner.IsSkipIssuesWithOpenPR()) b.ghClient.SetSentinelAlertLabel(b.cfg.Sentinel.LabelOrDefault()) b.ghClient.SetIssueFilter(b.cfg.Project.IssueFilter) diff --git a/src/docs/contributor-relay.md b/src/docs/contributor-relay.md index c0bfb8f069..cdfe67823c 100644 --- a/src/docs/contributor-relay.md +++ b/src/docs/contributor-relay.md @@ -996,6 +996,7 @@ Withheld rows carry a stable reason code and, where the refusing gate had one, t | `in_flight` | A contributor is working the issue right now. | — | | `contributor_filter` | A title, author, or label filter above rejected the candidate. | Which filter matched | | `assigned_to_other` | The issue is assigned to someone else and **Skip Assigned to Others** is on. | Assignee logins | +| `owner_grace` | An owner, maintainer or this hive filed the issue inside `governor.claims.contributor_grace_s` and no person has added `help wanted` ([#18898](https://github.com/hivecommons/hive/issues/18898)). | The forge's sentence: who filed it and how long ago | Two properties are worth relying on: @@ -1531,6 +1532,7 @@ A resume that is genuinely refused — an operator yanked the task, or the relay - **A disconnect release releases the claim.** Once the [#7838](https://github.com/hivecommons/hive/issues/7838) grace window has passed without the task being re-adopted or finished, the hub releases the ledger claim (reason `released on disconnect`), clears the lease's mirror of it, and — like every release that ends a claim before its `until=`, including `lease revoked` and a lease that aged out unresumed (`lease expired`) — posts the release marker and removes the claim labels, so the issue is claimable by hive agents on their next eval cycle. The lease itself stays resumable; a relay that does come back re-asserts the claim on resume, and if a hive agent took the issue meanwhile the ledger keeps the higher claim and the relay is preempted the usual way. A forge marker this hive wrote is in any case believed only while its own ledger still holds the claim, so a budget-suppressed release comment cannot leave a phantom hold. - **Repeated drops put the issue in contributor cool-off.** The hub counts disconnect releases per issue; at `governor.claims.contributor_flap_threshold` drops (default 3) inside `contributor_flap_window_s` (default 2h) the issue is withheld from *every* contributor — `selectTask` skips it and a `task_progress` resume of its lease is refused with `task_revoke` — for `contributor_flap_cooloff_s` (default 6h). Hive agents are not withheld; the work detail says `contributor cool-off: 3 drops in 2h0m0s; hive agents may claim it`, and one INFO line names the issue and the cool-off deadline when it trips. In-memory: a hub restart forgets the drops (the claim release is the durable half). A negative threshold turns the cool-off off. - **Contributor claims cannot starve hive agents.** An issue continuously withheld from hive agents by contributor claims for `contributor_starvation_s` (default 4h; negative turns it off) with no PR evidence on the claim stops being withheld: the claim becomes advisory, the issue stays actionable with the reason `Contributor claim by is advisory: contributor claims have withheld this issue from hive agents for 4h0m with no PR`, and a hive agent may claim it (the ledger's takeover hook then stops the relay). Agent, human and external claims are never overridden. +- **An issue the owner filed moments ago is the owner's to claim first.** An issue whose author is an owner or maintainer (author association `OWNER`, `MEMBER` or `COLLABORATOR`) or this hive's own App/bot is withheld from the contributor lane for `governor.claims.contributor_grace_s` (default 900 = 15m; negative turns it off) after it is filed ([#18898](https://github.com/hivecommons/hive/issues/18898), child of [#18890](https://github.com/hivecommons/hive/issues/18890): #18866 and #18880 each grew a contributor PR because the lane claimed the issue seconds after filing, before the owner or the owner's dispatcher could). Inside the window `selectTask` and the Ready queue skip the issue (Withheld reason `owner_grace`), and a contributor's fresh ledger claim is refused with `owner grace: filed by 3m ago; contributor claims wait 15m unless a person adds `help wanted``. A person adding the `help wanted` label after filing (a timeline `labeled` event whose actor is not a bot) waives the grace at once, because that is the owner opening the issue to outside help. Only a *fresh* claim waits: a lease already live is not touched, hive agents are never held off, and an issue filed by an outside reporter is not delayed. **Not every task has a lease, and one of them is the relay's own.** After every fifth completion the relay runs a *PR review cycle*: it stops taking new issues and asks its agent to look over the open PRs it has filed, so review comments get answered. That task is built locally — a `pr-review-…` id, `number: 0`, no `task_assign`, no lease — and for a long time the reconnect path above did not know the difference. It re-asserted the review to a hub that had never heard of it, the hub refused under exactly the server-issued-lease rule described above, and the relay treated the resulting revoke as terminal: stop the agent, relaunch the CLI, ask for fresh work ([#5715](https://github.com/hivecommons/hive/issues/5715)). The tell was in the log line itself — `Reconnected while working on kubestellar/hive#0 — resuming`, naming an issue number that does not exist. On a hive where 1006 closes are routine (29 in under four hours in the report) a review that takes a couple of minutes almost never survived to finish, so PR review coverage silently did not happen. diff --git a/src/docs/operator-reference/README.md b/src/docs/operator-reference/README.md index 5c8e409265..5315e62221 100644 --- a/src/docs/operator-reference/README.md +++ b/src/docs/operator-reference/README.md @@ -217,7 +217,7 @@ Top-level YAML keys accepted by `config.Config`: | `contribute.min_focus_window` | `30m`. | Preempt mode only: after a preempted primary task resumes, the hub does not preempt that contributor again until it has run uninterrupted for this long. Settings → Hub → Fix budget. | | `variables` | Trusted variable resolver definitions. | Env-only substitution works without this block. | | `classification` | Go-consumed subset of `hive-project.yaml`'s `classification:` block — today only `review_bots`, the external review-bot logins whose inline threads on hive-authored PRs the hive addresses and resolves itself. | Off unless `review_bots.logins` names a bot. The same key in `hive-project.yaml` is read when `hive.yaml` has none. See [review-bot-threads.md](../review-bot-threads.md). | -| `claims` | The worker-claim ledger ([#8380](https://github.com/hivecommons/hive/issues/8380)): who is on an issue right now, ranked human > agent > contributor > external, so a person can take an issue over from a hive agent or a relay contributor and the displaced holder is told to stop. | Default ON. `enabled: false` turns recording, enforcement and `/api/claims` off. `human_ttl_s` 4h, `agent_ttl_s` 2h, `contributor_ttl_s` 30m, `max_ttl_s` 24h; the owner can also set these four from **Governor Config → Features → Work intake & issue lifecycle → Issue claims** (a value of 0 or *Reset to default* uses the default; human, agent and contributor may not exceed the max), and a saved change applies without a restart to claims made or renewed afterwards while existing claims keep their expiry ([#10981](https://github.com/hivecommons/hive/issues/10981)); `comment: false` / `label: false` suppress the GitHub issue comment / `stage/020-claimed` label mirror (`label: false` also suppresses the `stage/030-pr-in-progress` start label an agent claim mirrors — formerly `claimed` / `hive/in-progress`, [#11841](https://github.com/hivecommons/hive/issues/11841)). A governor kick only *lists* the issues it names (30-minute hold, no comment, not a claim); the agent claim, with its comment, is recorded on the agent's first start signal on an issue — its own `hive-open-issue claim` request, a `hive-open-pr` request naming it, or a comment with an explicit start statement (``, "starting now", an opening "Starting …" / "Implementing …"; see the [recognized forms](../hive-open-issue.md#comment)); a report-only comment (triage, verification, gate check, status), an explicit deferral ([#12387](https://github.com/hivecommons/hive/issues/12387)) or escalation, and any `label` request record no claim. `never_claim_labels` (default `[epic]`, case-insensitive; `[]` turns it off) names umbrella/tracking labels no automated producer may claim and no claim ever stages `stage/020`/`stage/030`; the same admission gate also refuses issues parked on a person (`stage/045-needs-decision`, `needs-spec`, …), `needs-human` and held issues. `escalate_after_claims` (default `2`, negative turns it off) counts those claims only: once one agent's last that-many claims on a free issue were followed by no linked PR, referencing commit, label or assignee change and no close/reopen, the issue is withheld from every kick, labelled `needs-human` and given one comment listing the claims, instead of being claimed again. A `hive/likely-done` issue an agent already started on after the merged PR (its verification) is withheld from kicks until a person comments, labels, assigns, closes or reopens it, so it is verified once rather than every cycle ([#10527](https://github.com/hivecommons/hive/issues/10527)). `reclaim_cooldown_s` (default `21600` = 6h; negative turns it off) keeps a relay contributor session off an issue it released without shipping — task failed, abandoned, or its lease revoked — while other contributors may retry at once after the short global failure cooldown; before it, a relay whose environment could not run a task took the same issue back every ten minutes, flapping its claim ([#13093](https://github.com/hivecommons/hive/issues/13093)). A relay's *disconnect* release (after the [#7838](https://github.com/hivecommons/hive/issues/7838) grace window), a revoked lease and a lease that aged out unresumed each release the issue claim on GitHub too — release marker posted, claim labels removed — so hive agents may claim the issue on the next cycle; `contributor_flap_threshold` (default `3`; negative turns it off) disconnect releases of one issue inside `contributor_flap_window_s` (default `7200` = 2h) put the issue in *contributor cool-off* for `contributor_flap_cooloff_s` (default `21600` = 6h): withheld from every contributor, immediately eligible for hive agents, work detail `contributor cool-off: N drops in W`; and `contributor_starvation_s` (default `14400` = 4h; negative turns it off) is how long contributor claims may keep hive agents off an issue with no PR before the claim becomes advisory and a hive agent may claim it anyway ([#13579](https://github.com/hivecommons/hive/issues/13579)). An issue labelled `blocked` (the review backlog's parking for a finding whose file exists only on an unmerged PR, or `hive-open-issue comment --blocked-on-pr`) is refused by the same admission gate until the tracked PR merges or closes. Driven from `hivectl claim` — see [hivectl.md](../hivectl.md#claim--unclaim--claims--issue-claims). | +| `claims` | The worker-claim ledger ([#8380](https://github.com/hivecommons/hive/issues/8380)): who is on an issue right now, ranked human > agent > contributor > external, so a person can take an issue over from a hive agent or a relay contributor and the displaced holder is told to stop. | Default ON. `enabled: false` turns recording, enforcement and `/api/claims` off. `human_ttl_s` 4h, `agent_ttl_s` 2h, `contributor_ttl_s` 30m, `max_ttl_s` 24h; the owner can also set these four from **Governor Config → Features → Work intake & issue lifecycle → Issue claims** (a value of 0 or *Reset to default* uses the default; human, agent and contributor may not exceed the max), and a saved change applies without a restart to claims made or renewed afterwards while existing claims keep their expiry ([#10981](https://github.com/hivecommons/hive/issues/10981)); `comment: false` / `label: false` suppress the GitHub issue comment / `stage/020-claimed` label mirror (`label: false` also suppresses the `stage/030-pr-in-progress` start label an agent claim mirrors — formerly `claimed` / `hive/in-progress`, [#11841](https://github.com/hivecommons/hive/issues/11841)). A governor kick only *lists* the issues it names (30-minute hold, no comment, not a claim); the agent claim, with its comment, is recorded on the agent's first start signal on an issue — its own `hive-open-issue claim` request, a `hive-open-pr` request naming it, or a comment with an explicit start statement (``, "starting now", an opening "Starting …" / "Implementing …"; see the [recognized forms](../hive-open-issue.md#comment)); a report-only comment (triage, verification, gate check, status), an explicit deferral ([#12387](https://github.com/hivecommons/hive/issues/12387)) or escalation, and any `label` request record no claim. `never_claim_labels` (default `[epic]`, case-insensitive; `[]` turns it off) names umbrella/tracking labels no automated producer may claim and no claim ever stages `stage/020`/`stage/030`; the same admission gate also refuses issues parked on a person (`stage/045-needs-decision`, `needs-spec`, …), `needs-human` and held issues. `escalate_after_claims` (default `2`, negative turns it off) counts those claims only: once one agent's last that-many claims on a free issue were followed by no linked PR, referencing commit, label or assignee change and no close/reopen, the issue is withheld from every kick, labelled `needs-human` and given one comment listing the claims, instead of being claimed again. A `hive/likely-done` issue an agent already started on after the merged PR (its verification) is withheld from kicks until a person comments, labels, assigns, closes or reopens it, so it is verified once rather than every cycle ([#10527](https://github.com/hivecommons/hive/issues/10527)). `contributor_grace_s` (default `900` = 15m; negative turns it off) withholds an issue filed by an owner, maintainer or this hive from the contributor lane for that long after it is filed, unless a person adds `help wanted` ([#18898](https://github.com/hivecommons/hive/issues/18898); yaml-only, see the [relay doc](../contributor-relay.md)). `reclaim_cooldown_s` (default `21600` = 6h; negative turns it off) keeps a relay contributor session off an issue it released without shipping — task failed, abandoned, or its lease revoked — while other contributors may retry at once after the short global failure cooldown; before it, a relay whose environment could not run a task took the same issue back every ten minutes, flapping its claim ([#13093](https://github.com/hivecommons/hive/issues/13093)). A relay's *disconnect* release (after the [#7838](https://github.com/hivecommons/hive/issues/7838) grace window), a revoked lease and a lease that aged out unresumed each release the issue claim on GitHub too — release marker posted, claim labels removed — so hive agents may claim the issue on the next cycle; `contributor_flap_threshold` (default `3`; negative turns it off) disconnect releases of one issue inside `contributor_flap_window_s` (default `7200` = 2h) put the issue in *contributor cool-off* for `contributor_flap_cooloff_s` (default `21600` = 6h): withheld from every contributor, immediately eligible for hive agents, work detail `contributor cool-off: N drops in W`; and `contributor_starvation_s` (default `14400` = 4h; negative turns it off) is how long contributor claims may keep hive agents off an issue with no PR before the claim becomes advisory and a hive agent may claim it anyway ([#13579](https://github.com/hivecommons/hive/issues/13579)). An issue labelled `blocked` (the review backlog's parking for a finding whose file exists only on an unmerged PR, or `hive-open-issue comment --blocked-on-pr`) is refused by the same admission gate until the tracked PR merges or closes. Driven from `hivectl claim` — see [hivectl.md](../hivectl.md#claim--unclaim--claims--issue-claims). | | `removed_agents` | Persistent tombstones for deleted agents. | Dashboard/overlay-owned; do not seed casually. | | `good_first_issue` | Hive-curated `good first issue` advertising: a 15-minute sweep scores open, unclaimed issues and gives the few that qualify GitHub's `good first issue` + `help wanted` labels and one welcome comment pointing at this hive's contributor relay. Not a hold — a hive agent starting the issue removes the label. | Default ON; `enabled: false` opts out. Silent until `dashboard.public_url` (or a hub-assigned dashboard URL) exists. See [Hive-curated good first issues](../good-first-issue.md). | | `decisions.delegate` | "Let hive decide": the activity monitor's Decide… › *Let hive decide* action has the hive decide an issue or PR parked at *Needs human decision* itself, as the owner's delegate under the owner-delegate policy, recording it as a human decision would be (`/hive decision`, park lifted, queue approval on a PR) with an audit marker. | Default ON (`enabled: true`); `enabled: false` hides the action hive-wide; `repos..enabled` overrides per repository. `llm.enabled` (default OFF) consults the owner-delegate decider model for items the rules leave at the reversible default, on the governor reviewer endpoint; `llm.model` overrides the model. `effect_timeout` (default `30m`) is how long a recorded decision may go without its expected effect before a repeat click answers "decided, but it hasn't taken effect" with the plain reason and the next actions, and the hive posts one follow-up comment. Rails and policy in [Dashboard sections → Let hive decide](../dashboard-sections.md#let-hive-decide). | diff --git a/src/pkg/config/claims.go b/src/pkg/config/claims.go index dc7a1d5acd..1b02ecfc80 100644 --- a/src/pkg/config/claims.go +++ b/src/pkg/config/claims.go @@ -84,6 +84,15 @@ type ClaimsConfig struct { // a hive agent may claim it anyway (hivecommons/hive#13579). 0 → // DefaultContributorStarvation (4h); negative turns the guard off. ContributorStarvationS int `yaml:"contributor_starvation_s,omitempty" json:"contributor_starvation_s,omitempty"` + // ContributorGraceS is how long, in seconds, a freshly filed issue whose + // author is an owner/maintainer (author association OWNER, MEMBER or + // COLLABORATOR) or this hive's own App/bot is withheld from the + // contributor lane, so the owner or the owner's dispatcher can claim it + // first (hivecommons/hive#18898; #18866 and #18880 each grew a duplicate + // contributor PR inside that window). A person adding `help wanted` after + // filing waives it. 0 → DefaultContributorGrace (15m); negative turns the + // grace off. + ContributorGraceS int `yaml:"contributor_grace_s,omitempty" json:"contributor_grace_s,omitempty"` } // DefaultReclaimCooldown is the reclaim_cooldown_s default. @@ -98,6 +107,21 @@ const ( DefaultContributorStarvation = 4 * time.Hour ) +// DefaultContributorGrace is the contributor_grace_s default. +const DefaultContributorGrace = 15 * time.Minute + +// EffectiveContributorGrace returns contributor_grace_s with the default +// applied; 0 means the grace is off. +func (c ClaimsConfig) EffectiveContributorGrace() time.Duration { + switch { + case c.ContributorGraceS < 0: + return 0 + case c.ContributorGraceS == 0: + return DefaultContributorGrace + } + return time.Duration(c.ContributorGraceS) * time.Second +} + // EffectiveContributorFlap returns the contributor flap cool-off settings // with defaults applied. A threshold of 0 means the cool-off is off. func (c ClaimsConfig) EffectiveContributorFlap() (threshold int, window, cooloff time.Duration) { diff --git a/src/pkg/config/claims_grace_test.go b/src/pkg/config/claims_grace_test.go new file mode 100644 index 0000000000..68c61d2ec7 --- /dev/null +++ b/src/pkg/config/claims_grace_test.go @@ -0,0 +1,27 @@ +package config + +import ( + "testing" + "time" +) + +func TestEffectiveContributorGrace(t *testing.T) { + for _, tc := range []struct { + name string + s int + want time.Duration + }{ + {"unset uses the default", 0, DefaultContributorGrace}, + {"explicit", 300, 5 * time.Minute}, + {"negative turns it off", -1, 0}, + } { + t.Run(tc.name, func(t *testing.T) { + if got := (ClaimsConfig{ContributorGraceS: tc.s}).EffectiveContributorGrace(); got != tc.want { + t.Fatalf("EffectiveContributorGrace() = %v, want %v", got, tc.want) + } + }) + } + if DefaultContributorGrace != 15*time.Minute { + t.Fatalf("default grace = %v, want 15m", DefaultContributorGrace) + } +} diff --git a/src/pkg/dashboard/contribute_admission.go b/src/pkg/dashboard/contribute_admission.go index 39d5e561c6..c08debe5df 100644 --- a/src/pkg/dashboard/contribute_admission.go +++ b/src/pkg/dashboard/contribute_admission.go @@ -76,6 +76,10 @@ type contributorAdmissionCandidate struct { // whenever claims are disabled, so the gate below never fires then. issueClaim ghpkg.IssueClaimMark claimed bool + // createdAt is the issue's creation time from the enumerated envelope; + // zero when unknown. The owner-grace hold (Dependencies.ContributorHold) + // uses it to skip the forge read for an old issue. + createdAt time.Time } // isGitHubBacked reports whether this candidate may be handed to the two @@ -112,6 +116,9 @@ type contributorAdmissionDecision struct { // issueClaim carries the live claim behind an issue_claim refusal // (#8380): who holds it and until when. Zero for every other reason. issueClaim ghpkg.IssueClaimMark + // detail is the human-readable refusal behind owner_grace: the forge's own + // "owner grace: filed by ... N ago" sentence. + detail string // convergence carries the dependency judgment behind a dependency-based // refusal (#3845): which record was observed, at which generation, and // which dependency IDs blocked. Zero-valued when admission never reached @@ -157,6 +164,10 @@ const ( // not be resolved, so satisfaction cannot be asserted and the candidate is // not mutably dispatched. contributorAdmissionReasonDependencyUnknown = "dependency_unknown" + // contributorAdmissionReasonOwnerGrace: an owner, maintainer or this hive + // filed the issue inside the contributor grace window and no person has + // opened it to outside help yet (hivecommons/hive#18898). + contributorAdmissionReasonOwnerGrace = "owner_grace" ) // evaluateContributorNeutralAdmission applies repository-global admission @@ -232,6 +243,16 @@ func (h *ContributeWSHub) evaluateContributorNeutralAdmission(sweep *contributor } } + // Owner grace (#18898): an issue an owner, maintainer or this hive filed + // moments ago is the owner's to claim first. Checked after the claim gates + // (a PR or claim already on it says more) and before churn. + if reason := h.contributorHold(candidate); reason != "" { + return contributorAdmissionDecision{ + reason: contributorAdmissionReasonOwnerGrace, + detail: reason, + } + } + // Churn guard (#7995). An issue nobody is on right now, but which has // already absorbed several pull requests without settling, is not ready // work — the open question on it is "what is left?", and only a maintainer @@ -338,6 +359,22 @@ func (h *ContributeWSHub) openPRLinkingIssue(candidate contributorAdmissionCandi return ghpkg.OpenPRLink{}, false } +// contributorHold asks the Dependencies.ContributorHold hook whether the +// forge says the contributor lane must hold this candidate off. Repo +// spellings are tried as in issueClaimedByOpenPR. No hook wired reports "". +func (h *ContributeWSHub) contributorHold(candidate contributorAdmissionCandidate) string { + if h == nil || h.server == nil || h.server.deps == nil || h.server.deps.ContributorHold == nil { + return "" + } + if reason := h.server.deps.ContributorHold(candidate.repoFull, candidate.number, candidate.createdAt); reason != "" { + return reason + } + if candidate.repoName != "" && candidate.repoName != candidate.repoFull { + return h.server.deps.ContributorHold(candidate.repoName, candidate.number, candidate.createdAt) + } + return "" +} + // churnTriagedMarker is the label a maintainer applies to say "I have looked // at the churn on this issue; it is still ordinary work". It clears the churn // guard for that issue and nothing else — the guard's whole purpose is to ask diff --git a/src/pkg/dashboard/contribute_ledgers.go b/src/pkg/dashboard/contribute_ledgers.go index 151525957b..385986f32a 100644 --- a/src/pkg/dashboard/contribute_ledgers.go +++ b/src/pkg/dashboard/contribute_ledgers.go @@ -562,6 +562,20 @@ func issueUpdatedAtFromMap(issue map[string]any) time.Time { return t } +// issueCreatedAtFromMap reads the enumerated issue's creation time, zero when +// absent or malformed. +func issueCreatedAtFromMap(issue map[string]any) time.Time { + s, _ := issue["created_at"].(string) + if s == "" { + return time.Time{} + } + t, err := time.Parse(time.RFC3339, s) + if err != nil { + return time.Time{} + } + return t +} + // failedTaskRecord is the on-disk shape of one failed-task entry (#2435). It // preserves the last-failure time and the running consecutive-failure count so a // hub restart does not reset a quarantine — otherwise a bounce would re-admit a diff --git a/src/pkg/dashboard/contribute_owner_grace_test.go b/src/pkg/dashboard/contribute_owner_grace_test.go new file mode 100644 index 0000000000..63cc09b654 --- /dev/null +++ b/src/pkg/dashboard/contribute_owner_grace_test.go @@ -0,0 +1,63 @@ +package dashboard + +import ( + "strings" + "testing" + "time" +) + +// An issue an owner filed moments ago is withheld from the contributor lane +// (selectTask and the Ready queue share the admission), and offered once the +// hold clears (hivecommons/hive#18898). +func TestOwnerGraceWithholdsFreshOwnerIssueFromContributors(t *testing.T) { + hub, server := covK2Hub(t) + var holdReasons = map[int]string{1: "owner grace: filed by andy 2m ago; contributor claims wait 15m unless a person adds `help wanted`"} + var seenCreated []time.Time + server.deps.ContributorHold = func(repo string, number int, createdAt time.Time) string { + seenCreated = append(seenCreated, createdAt) + return holdReasons[number] + } + + created := time.Now().Add(-2 * time.Minute).UTC().Format(time.RFC3339) + fresh := intgIssue(1, "owner filed", "andy", nil) + fresh["created_at"] = created + other := intgIssue(2, "someone else's", "stranger", nil) + setStatusIssues(server, fresh, other) + + queue := hub.ReadyQueue(readyQueueDefaultLimit) + if len(queue) != 1 || queue[0].Number != 2 { + t.Fatalf("owner-filed issue inside the grace must stay out of the ReadyQueue, got %+v", queue) + } + conn := &ContributorConnection{ + profile: &ContributorProfile{GitHubUsername: "alice", ContributorID: "c-alice", TrustTier: "contributor"}, + lastPong: time.Now(), + } + task := hub.selectTask(conn) + if task == nil || task.Type != "task_assign" || task.Number != 2 { + t.Fatalf("selectTask must skip the grace-held issue, got %+v", task) + } + sawCreated := false + for _, c := range seenCreated { + if !c.IsZero() && c.Format(time.RFC3339) == created { + sawCreated = true + } + } + if !sawCreated { + t.Fatalf("the hook must receive the issue's created_at; saw %v", seenCreated) + } + + // The hold lapses (grace elapsed or a person added help wanted): offered. + holdReasons = map[int]string{} + queue = hub.ReadyQueue(readyQueueDefaultLimit) + if len(queue) != 2 { + t.Fatalf("after the hold clears both issues are offered, got %+v", queue) + } +} + +func TestOwnerGraceWithheldRowCarriesTheReason(t *testing.T) { + d := contributorAdmissionDecision{reason: contributorAdmissionReasonOwnerGrace, detail: "owner grace: filed by andy 2m ago"} + item := withheldFromAdmissionDecision(withheldCandidate{repoFull: "o/r"}, d) + if item.Reason != contributorAdmissionReasonOwnerGrace || !strings.HasPrefix(item.Detail, "owner grace: ") { + t.Fatalf("withheld item = %+v, want owner_grace with the forge's sentence", item) + } +} diff --git a/src/pkg/dashboard/contribute_select.go b/src/pkg/dashboard/contribute_select.go index 08a86a1d4b..38680fe845 100644 --- a/src/pkg/dashboard/contribute_select.go +++ b/src/pkg/dashboard/contribute_select.go @@ -887,6 +887,7 @@ func (h *ContributeWSHub) selectTaskPass(c *ContributorConnection, skippedUnmint dependsOn: dependenciesFromIssueMap(issue), issueClaim: issueClaim, claimed: claimed, + createdAt: issueCreatedAtFromMap(issue), }) if !decision.admitted { switch decision.reason { @@ -909,6 +910,10 @@ func (h *ContributeWSHub) selectTaskPass(c *ContributorConnection, skippedUnmint "claimed_by", decision.issueClaim.Identity, "claim_expires_at", decision.issueClaim.ExpiresAt.UTC().Format(time.RFC3339), "claim_source", decision.issueClaim.Source) + case contributorAdmissionReasonOwnerGrace: + // #18898: the owner (or the owner's dispatcher) claims first. + h.logger.Info("[contribute-ws] skip: owner grace window", + "repo", repo.Full, "number", number, "reason", decision.detail) case contributorAdmissionReasonMergedClaimStale: // #8003: the fix landed days ago and the issue is still // open. Logged as the question it is, so the Operations diff --git a/src/pkg/dashboard/contribute_sse.go b/src/pkg/dashboard/contribute_sse.go index 7d198c1743..1439f4667f 100644 --- a/src/pkg/dashboard/contribute_sse.go +++ b/src/pkg/dashboard/contribute_sse.go @@ -462,6 +462,7 @@ func (h *ContributeWSHub) admissionQueueSnapshot(limit int, scope withheldScope) dependsOn: dependenciesFromIssueMap(issue), issueClaim: issueClaim, claimed: claimed, + createdAt: issueCreatedAtFromMap(issue), }) if !decision.admitted { // #4246 retained the convergence Decision behind this refusal diff --git a/src/pkg/dashboard/contribute_withheld.go b/src/pkg/dashboard/contribute_withheld.go index b85f78021d..f59cfb151b 100644 --- a/src/pkg/dashboard/contribute_withheld.go +++ b/src/pkg/dashboard/contribute_withheld.go @@ -80,6 +80,7 @@ var withheldReasonLabels = map[string]string{ contributorAdmissionReasonLabelSkipped: "Contribute skip label", contributorAdmissionReasonDependencyBlocked: "A dependency is still open", contributorAdmissionReasonDependencyUnknown: "A dependency could not be resolved", + contributorAdmissionReasonOwnerGrace: "Filed by an owner or maintainer moments ago; they claim first", withheldReasonDisabledRepo: "Repository is disabled for contribution", withheldReasonRepoUnmintable: "Repository excluded after a GitHub App token mint failure", withheldReasonTracker: "Tracker / umbrella issue", @@ -115,6 +116,7 @@ func isConvergenceWithheldReason(reason string) bool { contributorAdmissionReasonIssueClaim, contributorAdmissionReasonMergedClaimStale, contributorAdmissionReasonIssueChurn, + contributorAdmissionReasonOwnerGrace, withheldReasonDisabledRepo, withheldReasonRepoUnmintable, withheldReasonTracker, @@ -364,6 +366,10 @@ func withheldFromAdmissionDecision(c withheldCandidate, d contributorAdmissionDe // prose states them rather than restating the rule. item.Detail = d.churn.Reason() return item + case contributorAdmissionReasonOwnerGrace: + item := newWithheldItem(c, d.reason) + item.Detail = d.detail + return item case contributorAdmissionReasonWorkflowBlocked, contributorAdmissionReasonLabelSkipped: item := newWithheldItem(c, d.reason) if d.skippedLabel != "" { diff --git a/src/pkg/dashboard/contribute_withheld_test.go b/src/pkg/dashboard/contribute_withheld_test.go index 744d6118b4..3c9b0236db 100644 --- a/src/pkg/dashboard/contribute_withheld_test.go +++ b/src/pkg/dashboard/contribute_withheld_test.go @@ -569,6 +569,7 @@ func TestWithheld_EveryReasonHasALabel(t *testing.T) { contributorAdmissionReasonIssueChurn, contributorAdmissionReasonMergedClaimStale, contributorAdmissionReasonIssueClaim, + contributorAdmissionReasonOwnerGrace, } for _, reason := range reasons { if label, ok := withheldReasonLabels[reason]; !ok || label == "" { diff --git a/src/pkg/dashboard/convergence_kick.go b/src/pkg/dashboard/convergence_kick.go index ef84bfd0dd..5c93ab0808 100644 --- a/src/pkg/dashboard/convergence_kick.go +++ b/src/pkg/dashboard/convergence_kick.go @@ -98,5 +98,6 @@ func kickAdmissionCandidate(issue ghpkg.Issue) contributorAdmissionCandidate { }, labels: issue.Labels, dependsOn: issue.DependsOn, + createdAt: issue.CreatedAt, } } diff --git a/src/pkg/dashboard/deps.go b/src/pkg/dashboard/deps.go index 79ec9d906d..03629a8711 100644 --- a/src/pkg/dashboard/deps.go +++ b/src/pkg/dashboard/deps.go @@ -308,6 +308,15 @@ type Dependencies struct { // so the label write is idempotent. Nil disables the live check; the // client honours the scanner open-PR switch itself. OpenPRLinkingIssue func(repo string, number int, labels []string) (ghpkg.OpenPRLink, bool) + // ContributorHold asks the forge whether the contributor lane must hold + // off an issue for a reason that lives on GitHub rather than in the + // enumerated envelope: today the owner grace window + // (governor.claims.contributor_grace_s, hivecommons/hive#18898), an issue + // an owner, maintainer or this hive filed moments ago. createdAt is the + // enumerated issue's creation time so the hook can answer "" for an old + // issue without a forge read. A non-empty return is the refusal reason. + // Nil disables the check. + ContributorHold func(repo string, number int, createdAt time.Time) string // Watsonx / OpenRouter are the LLM-provider gateway views (#5565 slice 3): // narrow consumer-defined interfaces over pkg/watsonx and pkg/openrouter, diff --git a/src/pkg/dashboard/settings_parity_allowlist.txt b/src/pkg/dashboard/settings_parity_allowlist.txt index b530de75ae..5fade9193b 100644 --- a/src/pkg/dashboard/settings_parity_allowlist.txt +++ b/src/pkg/dashboard/settings_parity_allowlist.txt @@ -306,6 +306,7 @@ governor.claims.contributor_flap_threshold # contributor flap cool-off (#13579); governor.claims.contributor_flap_window_s # contributor flap cool-off (#13579); yaml-only governor.claims.contributor_flap_cooloff_s # contributor flap cool-off (#13579); yaml-only governor.claims.contributor_starvation_s # contributor starvation guard (#13579); yaml-only +governor.claims.contributor_grace_s # owner/hive-filed issue grace before the contributor lane may claim (#18898); yaml-only governor.auto_close_superseded # superseded hive-PR auto-close; yaml-only governor.cadence_owners. # TODO #11854 governor.gateways[].api_key_env # TODO #11854 diff --git a/src/pkg/github/client.go b/src/pkg/github/client.go index 8da6cf9972..83d879dfd2 100644 --- a/src/pkg/github/client.go +++ b/src/pkg/github/client.go @@ -116,6 +116,9 @@ type Client struct { // the config (nil = package default; see SetNeverClaimLabels). neverClaimMu sync.RWMutex neverClaimLabels []string + // contributorGraceNanos is governor.claims.contributor_grace_s as a + // duration in nanoseconds (0 = off; see SetContributorGrace). + contributorGraceNanos atomic.Int64 // openPRLinkState backs the pre-dispatch open-PR guard and the // duplicate-fix resolver (open_pr_links.go); built lazily. openPRLinkOnce sync.Once diff --git a/src/pkg/github/issue_claim_gate.go b/src/pkg/github/issue_claim_gate.go index 46f36efc32..4c3e25ccc0 100644 --- a/src/pkg/github/issue_claim_gate.go +++ b/src/pkg/github/issue_claim_gate.go @@ -6,6 +6,7 @@ import ( "regexp" "strings" "sync/atomic" + "time" "github.com/hivecommons/hive/pkg/claims" ) @@ -206,6 +207,11 @@ type issueClaimGateResult struct { // filedForHelpBy is the agent named by the issue body's filed-for-help // marker, "" when there is none. filedForHelpBy string + // author, association and createdAt describe who filed the issue and + // when, for the contributor grace window (hivecommons/hive#18898). + author string + association string + createdAt time.Time } // issueClaimGate reads the issue once and applies every label-based refusal. @@ -225,6 +231,9 @@ func (c *Client) issueClaimGate(ctx context.Context, repo string, number int) (i labels: extractLabels(issue.Labels), closed: strings.EqualFold(issue.GetState(), "closed"), filedForHelpBy: ParseFiledForHelpMarker(issue.GetBody()), + author: safeGetLogin(issue.GetUser()), + association: strings.TrimSpace(issue.GetAuthorAssociation()), + createdAt: issue.GetCreatedAt().Time, } labels := res.labels switch { @@ -271,10 +280,29 @@ func (c *Client) IssueStartBlockReason(ctx context.Context, repo string, number } func (c *Client) issueDispatchBlockReason(ctx context.Context, repo string, number int, agent string) (string, error) { + return c.dispatchBlockReason(ctx, repo, number, agent, false, time.Now()) +} + +// IssueContributorDispatchBlockReason is IssueDispatchBlockReason for the +// contributor lane's fresh claim: it also refuses an issue an owner, +// maintainer or this hive's own App filed less than +// governor.claims.contributor_grace ago (ClaimBlockReasonOwnerGracePrefix, +// hivecommons/hive#18898), so the owner or the owner's dispatcher can claim +// it first. +func (c *Client) IssueContributorDispatchBlockReason(ctx context.Context, repo string, number int) (string, error) { + return c.dispatchBlockReason(ctx, repo, number, "", true, time.Now()) +} + +func (c *Client) dispatchBlockReason(ctx context.Context, repo string, number int, agent string, contributor bool, now time.Time) (string, error) { gate, err := c.issueClaimGate(ctx, repo, number) if err != nil || gate.reason != "" { return gate.reason, err } + if contributor { + if reason := c.ownerGraceReason(ctx, repo, number, gate, now); reason != "" { + return reason, nil + } + } if agent = strings.TrimSpace(agent); agent != "" && strings.EqualFold(gate.filedForHelpBy, agent) { return ClaimBlockReasonFiledForHelpPrefix + gate.filedForHelpBy + "; it was filed without --claim, so it is open for others — leave it to them unless a maintainer removes the filed-for-help marker", nil } diff --git a/src/pkg/github/issue_contributor_grace.go b/src/pkg/github/issue_contributor_grace.go new file mode 100644 index 0000000000..229c4ef30d --- /dev/null +++ b/src/pkg/github/issue_contributor_grace.go @@ -0,0 +1,175 @@ +package github + +import ( + "context" + "fmt" + "strings" + "time" + + gh "github.com/google/go-github/v72/github" +) + +// ClaimBlockReasonOwnerGracePrefix is the IssueDispatchBlockReason prefix for +// a contributor claim refused inside the owner grace window +// (hivecommons/hive#18898): the issue was filed moments ago by an owner, a +// maintainer or this hive's own App, who (or whose dispatcher) normally +// claims it within minutes. #18866 and #18880 each grew a duplicate +// contributor PR because the lane claimed the issue seconds after filing. +const ClaimBlockReasonOwnerGracePrefix = "owner grace: " + +// Author associations GitHub reports for an owner or maintainer of the +// repository. Anything else (CONTRIBUTOR, NONE, FIRST_TIMER, ...) is an +// outside reporter and never waits for a grace. +var ownerGraceAssociations = map[string]bool{ + "OWNER": true, + "MEMBER": true, + "COLLABORATOR": true, +} + +// botLoginSuffix is the suffix the REST API appends to a GitHub App's login. +const botLoginSuffix = "[bot]" + +// SetContributorGrace installs governor.claims.contributor_grace_s as a +// duration: how long an owner/maintainer/hive-filed issue is withheld from +// the contributor lane. d <= 0 turns the grace off. +func (c *Client) SetContributorGrace(d time.Duration) { + if c == nil { + return + } + if d < 0 { + d = 0 + } + c.contributorGraceNanos.Store(int64(d)) +} + +func (c *Client) contributorGrace() time.Duration { + if c == nil { + return 0 + } + return time.Duration(c.contributorGraceNanos.Load()) +} + +// ContributorGraceGuard is the contribute queue's cheap pre-check +// (hivecommons/hive#18898): createdAt comes from the enumerated issue, and an +// issue older than the grace, or any issue with the grace off, answers "" +// without a forge read. Only an issue still inside the window reads the +// issue (and, for the `help wanted` waiver, its timeline). +func (c *Client) ContributorGraceGuard(ctx context.Context, repo string, number int, createdAt time.Time) string { + grace := c.contributorGrace() + if grace <= 0 { + return "" + } + now := time.Now() + if !createdAt.IsZero() && now.Sub(createdAt) >= grace { + return "" + } + gate, err := c.issueClaimGate(ctx, repo, number) + if err != nil { + // Fail open: a lookup failure must not stall the queue; the ledger's + // own admission check reads the issue again at claim time. + return "" + } + return c.ownerGraceReason(ctx, repo, number, gate, now) +} + +// ownerGraceReason returns the refusal for a contributor claim on an issue +// inside the owner grace window, or "". +func (c *Client) ownerGraceReason(ctx context.Context, repo string, number int, gate issueClaimGateResult, now time.Time) string { + grace := c.contributorGrace() + if grace <= 0 || gate.createdAt.IsZero() || gate.closed { + return "" + } + age := now.Sub(gate.createdAt) + if age < 0 { + age = 0 + } + if age >= grace { + return "" + } + if !c.ownerOrHiveFiled(gate) { + return "" + } + if graceHasLabel(gate.labels, helpWantedLabel) && c.helpWantedAddedByPerson(ctx, repo, number) { + return "" + } + return fmt.Sprintf("%sfiled by %s %s ago; contributor claims wait %s unless a person adds `%s`", + ClaimBlockReasonOwnerGracePrefix, gate.author, graceAgeText(age), graceAgeText(grace), helpWantedLabel) +} + +// ownerOrHiveFiled reports whether the issue's author is an owner or +// maintainer (author association) or one of this hive's own bot logins. +func (c *Client) ownerOrHiveFiled(gate issueClaimGateResult) bool { + if ownerGraceAssociations[strings.ToUpper(gate.association)] { + return true + } + return c.isHiveBotAccount(gate.author) +} + +// isHiveBotAccount reports whether login is this hive's own App or one of the +// configured additional bot logins, with or without the "[bot]" suffix. +func (c *Client) isHiveBotAccount(login string) bool { + login = strings.TrimSuffix(strings.TrimSpace(login), botLoginSuffix) + if login == "" || c == nil { + return false + } + for _, bot := range c.hiveBotLogins() { + if strings.EqualFold(strings.TrimSuffix(strings.TrimSpace(bot), botLoginSuffix), login) { + return true + } + } + return false +} + +// helpWantedAddedByPerson reports whether a non-bot actor applied the +// `help wanted` label to the issue: a person opening the issue to outside +// help waives the grace. A timeline failure keeps the grace (fail closed: +// waiving needs positive evidence). +func (c *Client) helpWantedAddedByPerson(ctx context.Context, repo string, number int) bool { + if c == nil || c.client == nil { + return false + } + owner, name := c.splitRepo(repo) + opts := &gh.ListOptions{PerPage: 100} + for { + events, resp, err := c.client.Issues.ListIssueTimeline(ctx, owner, name, number, opts) + if err != nil { + if c.logger != nil { + c.logger.Debug("owner grace: timeline unreadable, keeping the grace", "repo", repo, "number", number, "error", err) + } + return false + } + for _, event := range events { + if event == nil || !strings.EqualFold(event.GetEvent(), "labeled") || + !strings.EqualFold(strings.TrimSpace(event.GetLabel().GetName()), helpWantedLabel) { + continue + } + actor := event.GetActor() + if actor == nil || actor.GetLogin() == "" || strings.EqualFold(actor.GetType(), "Bot") || + strings.HasSuffix(actor.GetLogin(), botLoginSuffix) || c.isHiveBotAccount(actor.GetLogin()) { + continue + } + return true + } + if resp == nil || resp.NextPage == 0 { + return false + } + opts.Page = resp.NextPage + } +} + +func graceHasLabel(labels []string, want string) bool { + for _, l := range labels { + if strings.EqualFold(strings.TrimSpace(l), want) { + return true + } + } + return false +} + +// graceAgeText renders a duration in whole minutes ("3m"), or "under 1m". +func graceAgeText(d time.Duration) string { + if m := int(d / time.Minute); m > 0 { + return fmt.Sprintf("%dm", m) + } + return "under 1m" +} diff --git a/src/pkg/github/issue_contributor_grace_test.go b/src/pkg/github/issue_contributor_grace_test.go new file mode 100644 index 0000000000..75131a1cc3 --- /dev/null +++ b/src/pkg/github/issue_contributor_grace_test.go @@ -0,0 +1,146 @@ +package github + +import ( + "context" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +// graceIssueServer serves issue o/r#42 filed by author (with association) +// createdAgo ago, carrying labels, plus a timeline whose "labeled" events +// are the given (label, actor, actorType) triples. Every other path 404s, +// which the open-PR guard reads as "no link" (it fails open). +func graceIssueServer(t *testing.T, author, association string, createdAgo time.Duration, labels []string, timeline [][3]string) *httptest.Server { + t.Helper() + created := time.Now().Add(-createdAgo).UTC().Format(time.RFC3339) + return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/repos/o/r/issues/42": + var ls []string + for _, l := range labels { + ls = append(ls, fmt.Sprintf(`{"name":%q}`, l)) + } + fmt.Fprintf(w, `{"number":42,"state":"open","created_at":%q,"author_association":%q,"user":{"login":%q},"labels":[%s]}`, + created, association, author, strings.Join(ls, ",")) + case "/repos/o/r/issues/42/timeline": + var evs []string + for _, e := range timeline { + evs = append(evs, fmt.Sprintf(`{"event":"labeled","label":{"name":%q},"actor":{"login":%q,"type":%q}}`, e[0], e[1], e[2])) + } + fmt.Fprintf(w, `[%s]`, strings.Join(evs, ",")) + default: + http.NotFound(w, r) + } + })) +} + +func graceReason(t *testing.T, srv *httptest.Server, grace time.Duration) string { + t.Helper() + c := issueTestClient(t, srv.URL) + c.SetAppBotLogin("hive-app[bot]") + c.SetContributorGrace(grace) + got, err := c.IssueContributorDispatchBlockReason(context.Background(), "o/r", 42) + if err != nil { + t.Fatalf("IssueContributorDispatchBlockReason: %v", err) + } + return got +} + +func TestContributorGrace_RefusesOwnerFiledIssueInsideWindow(t *testing.T) { + for _, tc := range []struct{ name, author, association string }{ + {"owner", "andy", "OWNER"}, + {"member", "andy", "MEMBER"}, + {"collaborator", "andy", "COLLABORATOR"}, + {"hive app", "hive-app[bot]", "CONTRIBUTOR"}, + {"hive app without suffix", "hive-app", "CONTRIBUTOR"}, + } { + t.Run(tc.name, func(t *testing.T) { + srv := graceIssueServer(t, tc.author, tc.association, 3*time.Minute, nil, nil) + defer srv.Close() + got := graceReason(t, srv, 15*time.Minute) + if !strings.HasPrefix(got, ClaimBlockReasonOwnerGracePrefix) || !strings.Contains(got, "3m ago") || !strings.Contains(got, tc.author) { + t.Fatalf("reason = %q, want an owner grace refusal naming %s and 3m", got, tc.author) + } + if strings.Contains(got, "@") { + t.Fatalf("reason %q must not carry a raw @mention", got) + } + }) + } +} + +func TestContributorGrace_AdmitsAfterWindowOutsideAuthorAndWhenOff(t *testing.T) { + cases := []struct { + name string + author string + association string + age time.Duration + grace time.Duration + }{ + {"after the window", "andy", "OWNER", 20 * time.Minute, 15 * time.Minute}, + {"outside reporter", "stranger", "NONE", time.Minute, 15 * time.Minute}, + {"contributor association", "stranger", "CONTRIBUTOR", time.Minute, 15 * time.Minute}, + {"grace off", "andy", "OWNER", time.Minute, 0}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + srv := graceIssueServer(t, tc.author, tc.association, tc.age, nil, nil) + defer srv.Close() + if got := graceReason(t, srv, tc.grace); got != "" { + t.Fatalf("reason = %q, want the claim admitted", got) + } + }) + } +} + +func TestContributorGrace_HelpWantedFromAPersonWaives(t *testing.T) { + labels := []string{"help wanted"} + // A person added it after filing: the grace is waived. + srv := graceIssueServer(t, "andy", "OWNER", time.Minute, labels, [][3]string{{"help wanted", "andy", "User"}}) + defer srv.Close() + if got := graceReason(t, srv, 15*time.Minute); got != "" { + t.Fatalf("reason = %q, want the person-added help wanted to waive the grace", got) + } + + // A bot added it (the hive's own triage): the grace stands. + srv2 := graceIssueServer(t, "andy", "OWNER", time.Minute, labels, [][3]string{{"help wanted", "hive-app[bot]", "Bot"}}) + defer srv2.Close() + if got := graceReason(t, srv2, 15*time.Minute); !strings.HasPrefix(got, ClaimBlockReasonOwnerGracePrefix) { + t.Fatalf("reason = %q, want a bot-applied help wanted to keep the grace", got) + } + + // The label is on the issue but the timeline shows no person applying it. + srv3 := graceIssueServer(t, "andy", "OWNER", time.Minute, labels, nil) + defer srv3.Close() + if got := graceReason(t, srv3, 15*time.Minute); !strings.HasPrefix(got, ClaimBlockReasonOwnerGracePrefix) { + t.Fatalf("reason = %q, want no waiver without a person's labeled event", got) + } +} + +func TestContributorGraceGuard_SkipsTheForgeReadForAnOldIssue(t *testing.T) { + reads := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + reads++ + http.NotFound(w, r) + })) + defer srv.Close() + c := issueTestClient(t, srv.URL) + c.SetContributorGrace(15 * time.Minute) + if got := c.ContributorGraceGuard(context.Background(), "o/r", 42, time.Now().Add(-time.Hour)); got != "" || reads != 0 { + t.Fatalf("old issue: reason %q after %d forge reads, want none", got, reads) + } +} + +func TestContributorGraceGuard_RefusesAFreshOwnerIssue(t *testing.T) { + srv := graceIssueServer(t, "andy", "OWNER", 2*time.Minute, nil, nil) + defer srv.Close() + c := issueTestClient(t, srv.URL) + c.SetContributorGrace(15 * time.Minute) + got := c.ContributorGraceGuard(context.Background(), "o/r", 42, time.Now().Add(-2*time.Minute)) + if !strings.HasPrefix(got, ClaimBlockReasonOwnerGracePrefix) { + t.Fatalf("reason = %q, want an owner grace refusal", got) + } +} From 9857e7617a0fbb2c7a906cee4847a37f52a26608 Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Wed, 18 Nov 2026 00:29:41 -0500 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=90=9B=20Fix=20CI:=20register=20SetCo?= =?UTF-8?q?ntributorGrace=20as=20a=20resync=20setter,=20drop=20the=20setti?= =?UTF-8?q?ngs=20allowlist=20entry=20the=20UI=20already=20covers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refs #18898 Signed-off-by: Andrew Anderson --- src/cmd/hive/github_client_config_test.go | 1 + src/pkg/dashboard/settings_parity_allowlist.txt | 1 - 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cmd/hive/github_client_config_test.go b/src/cmd/hive/github_client_config_test.go index f39fe87356..0a7da12f4f 100644 --- a/src/cmd/hive/github_client_config_test.go +++ b/src/cmd/hive/github_client_config_test.go @@ -84,6 +84,7 @@ var clientResyncSetters = map[string]bool{ "SetRepos": true, "SetHoldLabels": true, "SetNeverClaimLabels": true, + "SetContributorGrace": true, "SetSkipIssuesWithOpenPR": true, "SetSentinelAlertLabel": true, "SetExemptLabels": true, diff --git a/src/pkg/dashboard/settings_parity_allowlist.txt b/src/pkg/dashboard/settings_parity_allowlist.txt index 5fade9193b..b530de75ae 100644 --- a/src/pkg/dashboard/settings_parity_allowlist.txt +++ b/src/pkg/dashboard/settings_parity_allowlist.txt @@ -306,7 +306,6 @@ governor.claims.contributor_flap_threshold # contributor flap cool-off (#13579); governor.claims.contributor_flap_window_s # contributor flap cool-off (#13579); yaml-only governor.claims.contributor_flap_cooloff_s # contributor flap cool-off (#13579); yaml-only governor.claims.contributor_starvation_s # contributor starvation guard (#13579); yaml-only -governor.claims.contributor_grace_s # owner/hive-filed issue grace before the contributor lane may claim (#18898); yaml-only governor.auto_close_superseded # superseded hive-PR auto-close; yaml-only governor.cadence_owners. # TODO #11854 governor.gateways[].api_key_env # TODO #11854