From 56c36e5e9b86608cfbda379215289f12de597ee2 Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Wed, 18 Nov 2026 00:29:54 -0500 Subject: [PATCH 1/5] =?UTF-8?q?=F0=9F=90=9B=20Human=20claim=20or=20assigne?= =?UTF-8?q?e=20releases=20a=20contributor=20lease=20and=20blocks=20contrib?= =?UTF-8?q?utor=20adoption?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes #18899 Signed-off-by: Andrew Anderson --- ...-18899-human-claim-releases-contributor.md | 1 + src/cmd/hive/claims_admission_test.go | 77 +++++ src/cmd/hive/claimswire.go | 36 ++- src/docs/contributor-relay.md | 1 + .../labels-and-control-signals/reference.md | 2 +- .../stage-labels.md | 14 + src/docs/maintainer-commands.md | 12 + src/pkg/claims/claims.go | 31 ++ src/pkg/dashboard/claims_api.go | 49 ++- .../dashboard/claims_human_release_test.go | 130 ++++++++ src/pkg/dashboard/stage_tracker_adoption.go | 2 + .../automerge_adoption_human_claim.go | 42 +++ .../automerge_adoption_human_claim_test.go | 76 +++++ .../automerge/automerge_contributor_adopt.go | 9 + src/pkg/github/client.go | 3 + src/pkg/github/issue_human_claim.go | 288 ++++++++++++++++++ src/pkg/github/issue_human_claim_test.go | 196 ++++++++++++ src/pkg/stagelabels/store.go | 8 + 18 files changed, 964 insertions(+), 13 deletions(-) create mode 100644 changelog.d/fixed-18899-human-claim-releases-contributor.md create mode 100644 src/pkg/dashboard/claims_human_release_test.go create mode 100644 src/pkg/github/automerge/automerge_adoption_human_claim.go create mode 100644 src/pkg/github/automerge/automerge_adoption_human_claim_test.go create mode 100644 src/pkg/github/issue_human_claim.go create mode 100644 src/pkg/github/issue_human_claim_test.go diff --git a/changelog.d/fixed-18899-human-claim-releases-contributor.md b/changelog.d/fixed-18899-human-claim-releases-contributor.md new file mode 100644 index 0000000000..db0d88d6b1 --- /dev/null +++ b/changelog.d/fixed-18899-human-claim-releases-contributor.md @@ -0,0 +1 @@ +- **An owner's claim now releases a live contributor lease and stops the contributor lane.** The ledger always ranked a person over a contributor, but a claim made outside it (the assignee an owner or maintainer sets, a `/claim` comment, `hive/claimed-by-human` applied by hand) never displaced one: on #18866 the owner claimed at 03:21Z and the contributor still opened #18870 at 03:32Z. The contributor claim's admission check now reads those signals (the operator dispatcher's `gh issue edit --add-assignee` plus a plain "Claimed; fix in progress." comment counts); a renewal that meets one releases the claim at once and the five-minute release tick catches the rest, with release reason `human claim: assigned by `. The relay task is yanked (a disconnected relay's lease is revoked), the lane is handed other work, the person is recorded as the ledger holder, a fresh contributor claim is refused while the claim stands, and the hive no longer adopts a contributor PR for an issue a person holds (tracker row: "an owner or maintainer has claimed the issue"; stage record `human-claim`). `/claim` and `/unclaim` are documented in the maintainer commands. ([#18899](https://github.com/hivecommons/hive/issues/18899), 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 4fc26890f4..003aaa587e 100644 --- a/src/cmd/hive/claims_admission_test.go +++ b/src/cmd/hive/claims_admission_test.go @@ -331,3 +331,80 @@ func TestContributorClaimRefusedInsideOwnerGrace(t *testing.T) { t.Fatalf("claim after the grace = %+v, %v; want claimed", res, err) } } + +// hivecommons/hive#18899: the operator's dispatcher claims with an assignee +// plus a plain comment and no ledger entry. A contributor's live lease is +// released on the release tick with the human-claim reason, a renewal and a +// fresh claim are refused, and the contributor's own assignment is not a claim +// against it. +func TestContributorLeaseReleasedByOutOfLedgerHumanClaim(t *testing.T) { + var assigned atomic.Bool + api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/repos/o/r/issues/9": + if assigned.Load() { + fmt.Fprint(w, `{"number":9,"state":"open","assignees":[{"login":"andy"}],"labels":[]}`) + return + } + fmt.Fprint(w, `{"number":9,"state":"open","assignees":[],"labels":[]}`) + case "/repos/o/r/issues/9/timeline": + fmt.Fprint(w, `[{"event":"assigned","assignee":{"login":"andy"},"actor":{"login":"andy"}}]`) + case "/repos/o/r/issues/9/comments": + fmt.Fprint(w, `[{"user":{"login":"andy"},"author_association":"MEMBER","body":"Claimed; fix in progress."}]`) + case "/repos/o/r/collaborators/andy/permission": + fmt.Fprint(w, `{"permission":"admin","role_name":"admin","user":{"login":"andy"}}`) + default: + http.NotFound(w, r) + } + })) + defer api.Close() + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + client := github.NewClientForTest(api.URL, "o", []string{"r"}, logger) + var released atomic.Value + ledger, err := claims.New(filepath.Join(t.TempDir(), "claims.json"), claims.DefaultPolicy(), claims.Hooks{ + OnReleased: func(c claims.Claim, reason string) { released.Store(reason) }, + }) + if err != nil { + t.Fatal(err) + } + installClaimAdmissionCheck(context.Background(), ledger, func() *github.Client { return client }) + + req := claims.Request{Repo: "o/r", Issue: 9, Holder: "karibhou", HolderID: "c-1", Kind: claims.KindContributor} + if res, err := ledger.Claim(req); err != nil || res.Outcome != claims.OutcomeClaimed { + t.Fatalf("claim before the owner acts = %+v, %v; want claimed", res, err) + } + if n := ledger.ReleaseBlocked(); n != 0 { + t.Fatalf("released %d claims with no human claim on the forge", n) + } + + // The owner assigns the issue and posts "Claimed; fix in progress.". + assigned.Store(true) + // The verdict cache would still answer "no claim" for a minute in + // production; this client has not asked since, but use a fresh one so the + // test does not depend on that window. + client = github.NewClientForTest(api.URL, "o", []string{"r"}, logger) + res, err := ledger.Claim(req) + if err != nil || res.Outcome != claims.OutcomeRefused { + t.Fatalf("renewal after the owner claimed = %+v, %v; want refused", res, err) + } + if login, ok := claims.ParseHumanClaimReason(res.Reason); !ok || login != "andy" { + t.Fatalf("renewal refusal reason = %q, want a human-claim reason naming andy", res.Reason) + } + if n := ledger.ReleaseBlocked(); n != 1 { + t.Fatalf("release tick released %d claims, want 1", n) + } + if reason, _ := released.Load().(string); !strings.HasPrefix(reason, claims.ReasonHumanClaim) { + t.Fatalf("release reason = %q, want the human-claim reason", reason) + } + if _, held := ledger.Lookup("o/r", 9); held { + t.Fatal("contributor claim survived the release tick") + } + // A fresh contributor claim is refused while the person's claim stands. + if res, err := ledger.Claim(claims.Request{Repo: "o/r", Issue: 9, Holder: "other", HolderID: "c-2", Kind: claims.KindContributor}); err != nil || res.Outcome != claims.OutcomeRefused { + t.Fatalf("fresh contributor claim = %+v, %v; want refused", res, err) + } + // The person's own ledger claim is unaffected. + if res, err := ledger.Claim(claims.Request{Repo: "o/r", Issue: 9, Holder: "andy", Kind: claims.KindHuman}); err != nil || res.Outcome != claims.OutcomeClaimed { + t.Fatalf("human claim = %+v, %v; want claimed", res, err) + } +} diff --git a/src/cmd/hive/claimswire.go b/src/cmd/hive/claimswire.go index 9749b3c8ec..c689af1e79 100644 --- a/src/cmd/hive/claimswire.go +++ b/src/cmd/hive/claimswire.go @@ -220,19 +220,35 @@ func installClaimAdmissionCheck(ctx context.Context, ledger *claims.Ledger, clie // claims do not — the holder's own PR is the open PR. A hive // agent's own dispatch (Holder is the agent name) also refuses an // issue that agent filed for outside help (hivecommons/hive#17299). - if _, held := ledger.Lookup(req.Repo, req.Issue); !held && !req.PRStarted { - if req.Kind == claims.KindAgent { - return gh.IssueStartBlockReason(ctx, req.Repo, req.Issue, req.Holder) - } + _, held := ledger.Lookup(req.Repo, req.Issue) + var reason string + var err error + switch { + case !held && !req.PRStarted && req.Kind == claims.KindAgent: + reason, err = gh.IssueStartBlockReason(ctx, req.Repo, req.Issue, req.Holder) + case !held && !req.PRStarted && req.Kind == claims.KindContributor: // 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) + reason, err = gh.IssueContributorDispatchBlockReason(ctx, req.Repo, req.Issue) + case !held && !req.PRStarted: + reason, err = gh.IssueDispatchBlockReason(ctx, req.Repo, req.Issue) + default: + reason, err = gh.IssueClaimBlockReason(ctx, req.Repo, req.Issue) + } + if err != nil || reason != "" || req.Kind != claims.KindContributor { + return reason, err + } + // A person's claim outside the ledger (assignee, `/claim` comment, + // hand-applied hive/claimed-by-human) outranks a contributor: it + // refuses a fresh claim and a renewal, and the release tick then + // drops the live lease and yanks the task (hivecommons/hive#18899). + // A lookup failure keeps the claim held: unknown is not a verdict. + human, herr := gh.IssueHumanClaimReason(ctx, req.Repo, req.Issue, req.Holder) + if herr != nil { + return "", nil + } + return human, nil }) } diff --git a/src/docs/contributor-relay.md b/src/docs/contributor-relay.md index cdfe67823c..067db0bdad 100644 --- a/src/docs/contributor-relay.md +++ b/src/docs/contributor-relay.md @@ -1533,6 +1533,7 @@ A resume that is genuinely refused — an operator yanked the task, or the relay - **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. +- **A person's claim outside the ledger releases the contributor and yanks the task.** An owner or maintainer who assigns the issue (the operator's dispatcher runs `gh issue edit --add-assignee` plus a plain "Claimed; fix in progress." comment), comments `/claim`, or applies `hive/claimed-by-human` by hand outranks a live contributor lease even though none of it goes through the ledger ([#18899](https://github.com/hivecommons/hive/issues/18899), child of #18890: the owner claimed #18866 at 03:21Z and the contributor opened #18870 at 03:32Z). The contributor claim's admission check reads those signals: a renewal meeting one releases the claim at once and the five-minute release tick catches the rest, with release reason `human claim: assigned by `; the relay task is yanked like a takeover (or a disconnected relay's lease is revoked so a reconnect cannot resume it), the lane is handed other work, and the person is recorded as the ledger holder. While the claim stands a fresh contributor claim is refused and the hive does not adopt a contributor PR for the issue (stage tracker: "an owner or maintainer has claimed the issue"). The contributor's own assignment or comment never counts against it; the claim lifts when the person unassigns, removes the label or comments `/unclaim`. See [maintainer commands](maintainer-commands.md#claiming-an-issue). **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/labels-and-control-signals/reference.md b/src/docs/labels-and-control-signals/reference.md index c4b71de76f..835a104116 100644 --- a/src/docs/labels-and-control-signals/reference.md +++ b/src/docs/labels-and-control-signals/reference.md @@ -1017,7 +1017,7 @@ Retired ([#12683](https://github.com/hivecommons/hive/issues/12683)): nothing wr **Applies to:** Issues. **Kind:** Display-only. -A claim is a comment; the `claimed` label is a mirror Hive keeps in sync. Go claim gates use comments/assignees/ledger, not these labels. +A claim is a comment; the `claimed` label is a mirror Hive keeps in sync. Go claim gates use comments/assignees/ledger, not these labels. The one exception is a `hive/claimed-by-human` applied by hand (not by the hive App): the contributor claim gate reads it as a person's claim, like a human assignee or `/claim` comment, and releases a live contributor lease for it ([#18899](https://github.com/hivecommons/hive/issues/18899)). **Who applies it:** Hive/claim flows. diff --git a/src/docs/labels-and-control-signals/stage-labels.md b/src/docs/labels-and-control-signals/stage-labels.md index bb2911fd1a..8bd6f1b4a1 100644 --- a/src/docs/labels-and-control-signals/stage-labels.md +++ b/src/docs/labels-and-control-signals/stage-labels.md @@ -1425,6 +1425,20 @@ comment and the dashboard claim detail (`@login` next to the claim). | A relay contributor or external bot | `kind=contributor` / `kind=external`, `who=` | `hive/claimed-by-human` | | A hive agent with no human principal | `kind=agent who=` | `hive/claimed-by-` (e.g. `hive/claimed-by-scanner`) | +**A person outranks a contributor, ledger entry or not.** The ledger ranks +`kind=human` over `kind=contributor`, but an owner's claim made outside it +(the assignee set by an owner or maintainer, a `/claim` comment, or +`hive/claimed-by-human` applied by hand rather than by the hive) used to leave +a live contributor lease untouched (#18866: the owner claimed at 03:21Z and the +contributor still opened a PR at 03:32Z). Since +[#18899](https://github.com/hivecommons/hive/issues/18899) the contributor +claim's admission check reads those signals, so the next renewal or the +five-minute release tick releases the lease (reason `human claim: ...`), yanks +the relay task and records the person as the claim holder; see +[Maintainer commands](../maintainer-commands.md#claiming-an-issue). The hive's +own `hive/claimed-by-human` label (applied for a person's or a contributor's +ledger claim) is never read as a person's claim; only a hand-applied one is. + A backend or model name (`copilot`, `claude`, `codex`, `gemini`, `pi`) is **never** a suffix: it names the tool, not who answers for the work. A hive-agent claim whose name is a backend falls back to diff --git a/src/docs/maintainer-commands.md b/src/docs/maintainer-commands.md index 24dc873d42..1975be85c2 100644 --- a/src/docs/maintainer-commands.md +++ b/src/docs/maintainer-commands.md @@ -30,6 +30,18 @@ https://github.com/hivecommons/hive/blob/v5/src/docs/maintainer-commands.md | `/area ` | Validates or requests an area label. The Hive label helper reports invalid values and lists the accepted area names; repositories may also have Prow or other automation that applies valid labels. | Any non-bot commenter accepted by the label-helper workflow, subject to any repository label automation that applies the label. | Issues and pull requests. | GitHub Actions on the new comment. | The helper itself changes no labels for valid `/area` comments; companion repository automation may add `area/` or equivalent labels. | | `/assign` | Assigns the commenter where the repository's assignment automation supports slash-command assignment. The Hive assignment helper deliberately ignores the exact command because Prow handles it, but it points natural-language assignment requests to this command. | Repository assignment automation decides; the helper response is available to non-bot issue commenters. | Issues. | Repository assignment automation or GitHub Actions helper on the new comment. | Assignment state changes, not labels. | | `/unassign` | Removes the commenter's assignment where the repository's assignment automation supports it. | Repository assignment automation decides; the helper response is available to non-bot issue commenters. | Issues. | Repository assignment automation or GitHub Actions helper on the new comment. | Assignment state changes, not labels. | +| `/claim` | Says "I am working this issue": a contributor-lane lease on the issue is released and its relay task yanked, no new contributor claim is accepted on it and the hive will not adopt a contributor PR for it unless you release it ([#18899](https://github.com/hivecommons/hive/issues/18899)). It is read from the forge by the claim gate, not parsed by a sweep and not written to the ledger by itself: to register a claim in the ledger use the dashboard or `hivectl claim owner/repo#N`. | A commenter with author association `OWNER`, `MEMBER` or `COLLABORATOR`; bots and the contributor holding the lease are ignored. | Open issues. | The contributor claim's next lease renewal or the five-minute claim release tick. | Applies `hive/claimed-by-human` and `stage/020-claimed` when the claim is recorded in the ledger. | +| `/unclaim` | Withdraws your own `/claim` comment. | The same commenter. | Open issues. | Same as `/claim`. | None. | + +## Claiming an issue + +A person's claim outranks the contributor lane. Any of these on an open issue, made by an owner or maintainer (a person with `write`, `maintain` or `admin` repository permission, never a bot or the hive's own App), counts as a human claim even though none of them goes through the claim ledger ([#18899](https://github.com/hivecommons/hive/issues/18899), child of [#18890](https://github.com/hivecommons/hive/issues/18890)): + +- **Assigning the issue.** This is what an operator's dispatcher does: `gh issue edit --add-assignee` plus a plain "Claimed; fix in progress." comment. The assignment is the claim; the comment is courtesy. An assignee who is the contributor holding the lease is not a claim against that contributor (a maintainer handing the issue to them). +- **A `/claim` comment** (or a plain comment opening with "Claimed") from an `OWNER`, `MEMBER` or `COLLABORATOR`, until the same person comments `/unclaim`. +- **Applying `hive/claimed-by-human` by hand.** The same label applied by the hive is the ledger speaking and is not a claim. + +What a human claim does: a live contributor lease on the issue is released (release reason `human claim: assigned by `, `human claim: /claim comment by ` or `human claim: hive/claimed-by-human label by `), its relay task is yanked so the lane moves on, and the person is recorded as the ledger claim holder. While it stands a contributor's fresh claim and renewal are refused, and the hive does not adopt a contributor PR whose `Fixes #N` names the issue (the tracker row reads "an owner or maintainer has claimed the issue"). It lifts when the person unassigns, removes the label or comments `/unclaim`. The supported way to register a claim in the ledger is the dashboard or `hivectl claim owner/repo#N`; the three forge signals above are detected, not ledger entries of their own. ## Eligibility rules diff --git a/src/pkg/claims/claims.go b/src/pkg/claims/claims.go index 2eaf53aa10..3c4a296ba1 100644 --- a/src/pkg/claims/claims.go +++ b/src/pkg/claims/claims.go @@ -785,6 +785,37 @@ const ReasonExpired = "expired" // until= may still be in the future, so the hooks post a release marker. const ReasonLeaseExpired = "lease expired" +// ReasonHumanClaim is the release-reason prefix for a contributor claim that +// ended because an owner or maintainer claimed the issue outside the ledger: +// the human assignee, a `/claim` comment, or a hand-applied +// `hive/claimed-by-human` label (hivecommons/hive#18899). The full reason is +// HumanClaimReason: "human claim: assigned by andy". +const ReasonHumanClaim = "human claim" + +const humanClaimBy = " by " + +// HumanClaimReason renders the admission/release reason for a person's claim +// found on the forge: via says how ("assigned", "/claim comment", +// "hive/claimed-by-human label"), login who. +func HumanClaimReason(via, login string) string { + return ReasonHumanClaim + ": " + strings.TrimSpace(via) + humanClaimBy + strings.TrimSpace(login) +} + +// ParseHumanClaimReason reports whether reason is a HumanClaimReason and +// returns the person's login. +func ParseHumanClaimReason(reason string) (login string, ok bool) { + rest, found := strings.CutPrefix(strings.TrimSpace(reason), ReasonHumanClaim+": ") + if !found { + return "", false + } + i := strings.LastIndex(rest, humanClaimBy) + if i < 0 { + return "", false + } + login = strings.TrimSpace(rest[i+len(humanClaimBy):]) + return login, login != "" +} + // ReleaseAgentClaims drops every live KindAgent claim held by agent and fires // OnReleased for each. Unlike ReleaseByHolderID it never touches a human or // contributor claim whose login happens to spell the agent's name. diff --git a/src/pkg/dashboard/claims_api.go b/src/pkg/dashboard/claims_api.go index 2ee418bffc..89a56e95c0 100644 --- a/src/pkg/dashboard/claims_api.go +++ b/src/pkg/dashboard/claims_api.go @@ -80,6 +80,7 @@ func (s *Server) InstallClaimHooks(base claims.Hooks) { if prevReleased != nil { prevReleased(c, reason) } + s.contributorReleasedForHumanClaim(c, reason) } base.OnTakenOver = func(now, previous claims.Claim) { s.integrationRelease(previous.Key(), previous.Holder, uint64(previous.ClaimedAt.UnixNano()), "claim takeover") @@ -123,6 +124,38 @@ func (s *Server) preemptDisplacedHolder(now, previous claims.Claim) { previous.Key(), previous.Holder, previous.Kind, released, next), "") } +// contributorReleasedForHumanClaim is the "a person claimed it" half of the +// precedence rule (hivecommons/hive#18899). The admission check refuses a +// contributor on an issue an owner or maintainer claimed outside the ledger +// (assignee, `/claim` comment, hand-applied hive/claimed-by-human), the +// release tick or the next lease renewal then drops the contributor claim +// with claims.HumanClaimReason, and this hook does what a takeover does for +// a displaced contributor: yank the relay task (or revoke a disconnected +// relay's lease) so the lane stops, and record the person's claim in the +// ledger so every other producer sees it and the history says who. Any other +// release reason is not this hook's. +func (s *Server) contributorReleasedForHumanClaim(c claims.Claim, reason string) { + login, ok := claims.ParseHumanClaimReason(reason) + if !ok || c.Kind != claims.KindContributor { + return + } + released := 0 + if s.contributeHub != nil && c.HolderID != "" { + released, _ = s.contributeHub.PreemptContributorIssue(c.HolderID, c.Repo, c.Issue, "preempted: "+reason) + if released == 0 { + s.contributeHub.revokeLeaseForKey(c.HolderID, c.Key()) + } + } + if l := s.claimsLedger(); l != nil { + if _, err := l.Claim(claims.Request{Repo: c.Repo, Issue: c.Issue, Holder: login, Kind: claims.KindHuman}); err != nil { + s.logger.Warn("[claims] human claim not recorded after releasing a contributor", "issue", c.Key(), "by", login, "error", err) + } + } + s.logger.Info("[claims] contributor lease released: a person claimed the issue", + "issue", c.Key(), "holder", c.Holder, "holder_id", c.HolderID, "by", login, "reason", reason, "yanked", released) + s.AuditLog(login, "claim_preempt", fmt.Sprintf("%s released from %s (%s): %s; yanked=%d", c.Key(), c.Holder, c.Kind, reason, released), "") +} + // claimIssueForContributor records a contributor claim after the relay has // leased an item to a connection. Best-effort: a ledger error never blocks the // assignment — the lease is the source of truth for the relay; the claim is @@ -172,9 +205,21 @@ func (h *ContributeWSHub) renewClaimForLease(identity, repo string, number int) if !ok || c.HolderID != identity { return } - if _, err := l.Claim(claims.Request{Repo: c.Repo, Issue: c.Issue, Holder: c.Holder, HolderID: c.HolderID, - Kind: c.Kind, Session: c.Session, Tier: c.Tier, Verified: c.Verified}); err != nil { + res, err := l.Claim(claims.Request{Repo: c.Repo, Issue: c.Issue, Holder: c.Holder, HolderID: c.HolderID, + Kind: c.Kind, Session: c.Session, Tier: c.Tier, Verified: c.Verified}) + if err != nil { h.logger.Warn("[claims] contributor claim not renewed", "issue", c.Key(), "holder", c.Holder, "error", err) + return + } + // The renewal's admission check found a person's claim (hivecommons/hive#18899): + // release the contributor now rather than wait for the release tick. Off + // this goroutine: renewal runs inside the progress handler and the yank + // takes the connection locks. + if res.Outcome == claims.OutcomeRefused { + if _, human := claims.ParseHumanClaimReason(res.Reason); human { + reason, holderID, key := res.Reason, c.HolderID, c.Key() + go l.ReleaseByHolderID(holderID, reason, key) + } } } diff --git a/src/pkg/dashboard/claims_human_release_test.go b/src/pkg/dashboard/claims_human_release_test.go new file mode 100644 index 0000000000..ec5eb2a544 --- /dev/null +++ b/src/pkg/dashboard/claims_human_release_test.go @@ -0,0 +1,130 @@ +package dashboard + +import ( + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/claims" +) + +// An owner's claim outside the ledger releases the contributor's live lease +// and yanks the relay task (hivecommons/hive#18899): the release tick drops +// the claim with claims.HumanClaimReason, the hook moves the session to other +// work and records the person's claim in the ledger. +func TestClaims_HumanClaimReleaseYanksContributorAndRecordsPerson(t *testing.T) { + hub, s, l := claimsHub(t) + setStatusIssues(s, + intgIssue(1, "claimed by the owner out of band", "someone", nil), + intgIssue(2, "other work", "someone", nil), + ) + profile := &ContributorProfile{GitHubUsername: "worker", ContributorID: "c-worker", TrustTier: "contributor"} + held := &ContributorConnection{ + profile: profile, session: "a", + currentTask: &WSTaskAssign{TaskID: "t-1", Repo: "myorg/repo1", Number: 1}, + currentTaskGen: 7, lastLeaseRenew: time.Now(), lastPong: time.Now(), + } + hub.mu.Lock() + hub.connections["conn-a"] = held + hub.mu.Unlock() + if _, err := l.Claim(claims.Request{Repo: "myorg/repo1", Issue: 1, Holder: "worker", HolderID: identityOf(held), Kind: claims.KindContributor, Session: "a"}); err != nil { + t.Fatal(err) + } + + // The forge now shows a person's claim: the admission check says so for + // the live contributor claim, as the GitHub-backed check does. + humanReason := claims.HumanClaimReason("assigned", "andy") + l.SetAdmissionCheck(func(req claims.Request) (string, error) { + if req.Kind == claims.KindContributor { + return humanReason, nil + } + return "", nil + }) + if n := l.ReleaseBlocked(); n != 1 { + t.Fatalf("ReleaseBlocked released %d claims, want 1", n) + } + + held.mu.Lock() + cur, gen := held.currentTask, held.currentTaskGen + held.mu.Unlock() + if cur == nil || cur.Number != 2 { + t.Fatalf("contributor not yanked onto other work: %+v", cur) + } + if gen == 7 { + t.Fatal("assignment generation not bumped — a stale completion would not be fenced") + } + now, ok := l.Lookup("myorg/repo1", 1) + if !ok || now.Kind != claims.KindHuman || now.Holder != "andy" { + t.Fatalf("ledger claim = %+v (live %v), want the person's claim by andy", now, ok) + } +} + +// A disconnected relay has no socket to yank: the lease itself is revoked so +// a reconnect cannot resume the issue the owner claimed. +func TestClaims_HumanClaimReleaseRevokesDisconnectedRelayLease(t *testing.T) { + hub, _, l := claimsHub(t) + const identity = "c-worker#a" + if err := hub.recordLease(identity, "t-1", "myorg/repo1", 1, "contributor", 3, time.Now()); err != nil { + t.Fatal(err) + } + if _, err := l.Claim(claims.Request{Repo: "myorg/repo1", Issue: 1, Holder: "worker", HolderID: identity, Kind: claims.KindContributor, Session: "a"}); err != nil { + t.Fatal(err) + } + l.SetAdmissionCheck(func(req claims.Request) (string, error) { + return claims.HumanClaimReason("/claim comment", "andy"), nil + }) + if n := l.ReleaseBlocked(); n != 1 { + t.Fatalf("ReleaseBlocked released %d claims, want 1", n) + } + if hub.lookupLease(identity, "t-1", "myorg/repo1", 1, 3, time.Now()) != nil { + t.Fatal("disconnected relay's lease survived the owner's claim — it could resume #1") + } +} + +// A lease renewal that meets the person's claim releases the contributor at +// once, without waiting for the five-minute release tick. +func TestClaims_RenewalMeetingAHumanClaimReleasesTheContributor(t *testing.T) { + hub, _, l := claimsHub(t) + const identity = "c-worker#a" + now := time.Now() + if err := hub.recordLease(identity, "t-1", "myorg/repo1", 1, "contributor", 3, now); err != nil { + t.Fatal(err) + } + if _, err := l.Claim(claims.Request{Repo: "myorg/repo1", Issue: 1, Holder: "worker", HolderID: identity, Kind: claims.KindContributor, Session: "a"}); err != nil { + t.Fatal(err) + } + l.SetAdmissionCheck(func(req claims.Request) (string, error) { + return claims.HumanClaimReason("assigned", "andy"), nil + }) + if err := hub.renewLease(identity, "t-1", now.Add(time.Minute)); err != nil { + t.Fatal(err) + } + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) { + if c, ok := l.Lookup("myorg/repo1", 1); ok && c.Kind == claims.KindHuman && c.Holder == "andy" { + return + } + time.Sleep(10 * time.Millisecond) + } + c, ok := l.Lookup("myorg/repo1", 1) + t.Fatalf("renewal did not hand the issue to the person: claim %+v (live %v)", c, ok) +} + +// Only a human-claim release is this hook's: an ordinary release leaves the +// ledger alone. +func TestClaims_OtherReleaseReasonsDoNotRecordAPerson(t *testing.T) { + _, _, l := claimsHub(t) + if _, err := l.Claim(claims.Request{Repo: "myorg/repo1", Issue: 1, Holder: "worker", HolderID: "c-worker#a", Kind: claims.KindContributor}); err != nil { + t.Fatal(err) + } + l.ForceRelease("myorg/repo1", 1, "lease expired") + if c, ok := l.Lookup("myorg/repo1", 1); ok { + t.Fatalf("ordinary release left a claim: %+v", c) + } + if login, ok := claims.ParseHumanClaimReason("lease expired"); ok || login != "" { + t.Fatalf("parsed %q from an ordinary reason", login) + } + if got, ok := claims.ParseHumanClaimReason(claims.HumanClaimReason("assigned", "andy")); !ok || got != "andy" || !strings.HasPrefix(claims.HumanClaimReason("assigned", "andy"), claims.ReasonHumanClaim) { + t.Fatalf("round trip = %q, %v", got, ok) + } +} diff --git a/src/pkg/dashboard/stage_tracker_adoption.go b/src/pkg/dashboard/stage_tracker_adoption.go index f9049a7890..64e9e3d652 100644 --- a/src/pkg/dashboard/stage_tracker_adoption.go +++ b/src/pkg/dashboard/stage_tracker_adoption.go @@ -213,6 +213,8 @@ func stageTrackerAdoptionText(author string, a StageTrackerAdoption, now time.Ti text += " — maintainer-owned: automatic adoption is disabled by maintainer_policy=never" case a.BlockedBy == stagelabels.AdoptBlockedOperatorAdmission: text += " — contributor-managed: operator approval recorded for this head; existing review/CI requirements still apply" + case a.BlockedBy == stagelabels.AdoptBlockedHumanClaim: + text += " — an owner or maintainer has claimed the issue: the hive will not adopt this PR unless they release the claim" case a.BlockedBy != "": text += " — adoption blocked: " + a.BlockedBy case a.AutoDue: diff --git a/src/pkg/github/automerge/automerge_adoption_human_claim.go b/src/pkg/github/automerge/automerge_adoption_human_claim.go new file mode 100644 index 0000000000..3afaa7f088 --- /dev/null +++ b/src/pkg/github/automerge/automerge_adoption_human_claim.go @@ -0,0 +1,42 @@ +package automerge + +import ( + "context" + "strings" + + hgithub "github.com/hivecommons/hive/pkg/github" +) + +// humanClaimTransport is the optional transport hook that reports a claim an +// owner or maintainer holds on an issue outside the ledger +// (hgithub.Client.IssueHumanClaimReason; hivecommons/hive#18899). +type humanClaimTransport interface { + IssueHumanClaimReason(ctx context.Context, repo string, number int, holder string) (string, error) +} + +// adoptionHumanClaim returns the claim reason ("human claim: assigned by +// andy") when an owner or maintainer holds a claim on an issue the contributor +// PR closes, "" otherwise. The PR's own author is the holder: their assignment +// or comment is the contributor's own and never counts against them. A +// transport that cannot answer, or a lookup failure, is "no claim": adoption +// is a timing decision and the next sweep asks again. +func (c *Engine) adoptionHumanClaim(ctx context.Context, obs stageObservation) string { + t, ok := c.transport.(humanClaimTransport) + if !ok { + return "" + } + for _, ref := range hgithub.ParseClaimedIssues(obs.Title+"\n"+obs.Body, obs.Display) { + if ref.Issue <= 0 || (ref.Repo != "" && !strings.EqualFold(ref.Repo, obs.Display)) { + continue + } + reason, err := t.IssueHumanClaimReason(ctx, obs.Display, ref.Issue, obs.Author) + if err != nil { + c.debug("stage labels: human-claim lookup failed; not blocking adoption", "repo", obs.Display, "pr", obs.Number, "issue", ref.Issue, "error", err) + continue + } + if reason != "" { + return reason + } + } + return "" +} diff --git a/src/pkg/github/automerge/automerge_adoption_human_claim_test.go b/src/pkg/github/automerge/automerge_adoption_human_claim_test.go new file mode 100644 index 0000000000..44eb211aed --- /dev/null +++ b/src/pkg/github/automerge/automerge_adoption_human_claim_test.go @@ -0,0 +1,76 @@ +package automerge + +import ( + "context" + "sync" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/claims" + "github.com/hivecommons/hive/pkg/stagelabels" +) + +// humanClaimStub answers Engine.adoptionHumanClaim in place of the forge. +type humanClaimStub struct { + Transport + mu sync.Mutex + reason string + asked []string +} + +func (s *humanClaimStub) IssueHumanClaimReason(_ context.Context, _ string, _ int, holder string) (string, error) { + s.mu.Lock() + defer s.mu.Unlock() + s.asked = append(s.asked, holder) + return s.reason, nil +} + +func (s *humanClaimStub) set(reason string) { + s.mu.Lock() + s.reason = reason + s.mu.Unlock() +} + +// An owner's claim on an issue the contributor PR closes keeps the hive from +// adopting it, however long the contributor has been offline +// (hivecommons/hive#18899); the block is on the record for the tracker row +// and lifts the moment the person releases the claim. +func TestAdoptionRefusedWhileAPersonHoldsAClaimOnTheIssue(t *testing.T) { + h, done := newAdoptHarness(t, ContributorNudgeOutcome{Mode: "queued"}, adoptPolicy()) + defer done() + stub := &humanClaimStub{Transport: h.e.transport} + h.e.transport = stub + start := h.clock.at + h.sink.presence = &ContributorPresence{Registered: true, Online: false} + h.observe(adoptPR(7, "aaa"), "conflicting") + if len(nudgeComments(h.api)) != 1 { + t.Fatalf("no nudge: %v", h.api.comments) + } + labels := []string{"stage/072-returned-to-contributor", "role/contributor", "author/clanker"} + key := stageKey("acme", "widget", 7) + + // Offline past the 15m wait, but the owner claimed the issue. + stub.set(claims.HumanClaimReason("assigned", "andy")) + h.api.reset() + h.clock.at = start.Add(31 * time.Minute) + h.observe(adoptPR(7, "aaa", labels...), "conflicting") + if len(h.adopt.pulls) != 0 || len(adoptionComments(h.api)) != 0 { + t.Fatalf("adopted over a person's claim: pulls=%v comments=%v", h.adopt.pulls, h.api.comments) + } + rec, _ := h.e.stageStoreOrShared().Get(key) + if rec.AdoptionBlocked("aaa") != stagelabels.AdoptBlockedHumanClaim { + t.Fatalf("block not recorded: %+v", rec) + } + if len(stub.asked) == 0 || stub.asked[0] != "mallory" { + t.Fatalf("the claim check must name the PR author as the holder, asked %v", stub.asked) + } + + // The person releases the claim: the next pass adopts. + stub.set("") + h.api.reset() + h.clock.at = start.Add(46 * time.Minute) + h.observe(adoptPR(7, "aaa", labels...), "conflicting") + if len(h.adopt.pulls) != 1 { + t.Fatalf("adoption did not resume after the claim lifted: pulls=%v comments=%v", h.adopt.pulls, h.api.comments) + } +} diff --git a/src/pkg/github/automerge/automerge_contributor_adopt.go b/src/pkg/github/automerge/automerge_contributor_adopt.go index 887a3c8329..84f84bb06f 100644 --- a/src/pkg/github/automerge/automerge_contributor_adopt.go +++ b/src/pkg/github/automerge/automerge_contributor_adopt.go @@ -696,6 +696,15 @@ func (c *Engine) adoptContributorPR(ctx context.Context, store *stagelabels.Stor c.info("stage labels: operator forced adoption; maintainer policy, admission and presence bypassed", "repo", obs.Display, "pr", obs.Number, "author", obs.Author, "by", forcedBy, "online", presence.Online, "policy", policy.maintainerPolicy()) } else if c.adoptionRefusedByAdmission(ctx, store, key, obs, requested, now) { return 0, nil + } else if claim := c.adoptionHumanClaim(ctx, obs); claim != "" { + // An owner or maintainer claimed an issue this PR closes + // (hivecommons/hive#18899): the person's claim outranks the + // contributor lane, so the hive does not open a copy beside it. + // Recorded so the tracker row says why; it lifts the moment the + // claim does. + store.NoteAdoptionBlocked(key, obs.HeadSHA, stagelabels.AdoptBlockedHumanClaim, now) + c.info("stage labels: adoption due but a person holds a claim on the issue; not adopting", "repo", obs.Display, "pr", obs.Number, "author", obs.Author, "claim", claim, "requested", requested) + return 0, nil } else if held, deferred := c.maintainerHoldsAdoption(ctx, obs, policy, requested, now); held || deferred { if held && !deferred { // Recorded so the activity monitor says why (hivecommons/hive#14524): diff --git a/src/pkg/github/client.go b/src/pkg/github/client.go index 83d879dfd2..5a797d038f 100644 --- a/src/pkg/github/client.go +++ b/src/pkg/github/client.go @@ -119,6 +119,9 @@ type Client struct { // contributorGraceNanos is governor.claims.contributor_grace_s as a // duration in nanoseconds (0 = off; see SetContributorGrace). contributorGraceNanos atomic.Int64 + // humanClaims caches the out-of-ledger human-claim verdicts and the + // maintainer lookups behind them (IssueHumanClaimReason). + humanClaims humanClaimState // 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_human_claim.go b/src/pkg/github/issue_human_claim.go new file mode 100644 index 0000000000..a2a2a7ab2f --- /dev/null +++ b/src/pkg/github/issue_human_claim.go @@ -0,0 +1,288 @@ +package github + +import ( + "context" + "fmt" + "regexp" + "strings" + "sync" + "time" + + gh "github.com/google/go-github/v72/github" + + "github.com/hivecommons/hive/pkg/claims" +) + +// claimedByHumanLabel is the label the hive itself writes for a person's (or +// contributor's) ledger claim (claims.ClaimedByLabel). A bot applying it is +// the ledger speaking; a person applying it by hand is a claim. +const claimedByHumanLabel = "hive/claimed-by-human" + +// humanClaimCacheTTL bounds how long one issue's human-claim verdict is +// reused. The contributor claim's renewal and the release tick both ask, so +// the cache keeps a live lease from costing a timeline read per progress +// report. +const humanClaimCacheTTL = time.Minute + +// maintainerPermissionTTL bounds how long a login's repository permission +// is reused. +const maintainerPermissionTTL = 10 * time.Minute + +// Via phrases of claims.HumanClaimReason. +const ( + humanClaimViaAssignee = "assigned" + humanClaimViaComment = "/claim comment" + humanClaimViaLabel = claimedByHumanLabel + " label" + humanClaimViaLedger = "claimed in the ledger" +) + +var ( + // humanClaimCommentRe is a person's claim comment: the `/claim` command, + // or the plain "Claimed; fix in progress." an owner's dispatcher posts + // beside `gh issue edit --add-assignee`. + humanClaimCommentRe = regexp.MustCompile(`(?i)^\s*(?:/claim\b|claimed\b)`) + // humanUnclaimCommentRe withdraws a person's earlier claim comment. + humanUnclaimCommentRe = regexp.MustCompile(`(?i)^\s*/unclaim\b`) +) + +type humanClaimCacheEntry struct { + reason string + expires time.Time +} + +type maintainerCacheEntry struct { + ok bool + expires time.Time +} + +// humanClaimState holds the client's human-claim caches. +type humanClaimState struct { + mu sync.Mutex + verdicts map[string]humanClaimCacheEntry + maintainer map[string]maintainerCacheEntry +} + +// IssueHumanClaimReason reports a claim an owner or maintainer holds on the +// issue OUTSIDE the ledger, as a claims.HumanClaimReason, or "" when there is +// none (hivecommons/hive#18899). The ledger already ranks a person over a +// contributor, but a claim that never went through it (the operator's +// dispatcher runs `gh issue edit --add-assignee` plus a plain "Claimed; fix in +// progress." comment) never displaced a live contributor lease: #18866's +// contributor opened #18870 eleven minutes after the owner claimed it. +// +// Three signals count, each only from a person with write access to the +// repository, never from a bot or the hive's own App: +// - an assignee the person assigned (the assigner is a maintainer; an +// assignee who is the contributor holder is the maintainer handing the +// issue to that contributor, not a claim against them); +// - a `/claim` (or plain "Claimed...") comment from an OWNER, MEMBER or +// COLLABORATOR, not later withdrawn by `/unclaim`; +// - `hive/claimed-by-human` applied by hand rather than by the hive. +// +// holder is the contributor login whose claim is being checked ("" for a +// fresh claim by anyone): that login's own assignment or comment never +// counts against it. An open issue only; a closed issue holds nothing. +// A lookup error is returned so the caller keeps the claim it has. +func (c *Client) IssueHumanClaimReason(ctx context.Context, repo string, number int, holder string) (string, error) { + if c == nil || c.client == nil { + return "", ErrNoGitHubClient + } + key := strings.ToLower(repo) + "#" + fmt.Sprint(number) + "|" + strings.ToLower(strings.TrimSpace(holder)) + now := time.Now() + c.humanClaims.mu.Lock() + if e, ok := c.humanClaims.verdicts[key]; ok && now.Before(e.expires) { + c.humanClaims.mu.Unlock() + return e.reason, nil + } + c.humanClaims.mu.Unlock() + + reason, err := c.readHumanClaim(ctx, repo, number, holder) + if err != nil { + return "", err + } + c.humanClaims.mu.Lock() + if c.humanClaims.verdicts == nil { + c.humanClaims.verdicts = map[string]humanClaimCacheEntry{} + } + if len(c.humanClaims.verdicts) > humanClaimCacheMax { + c.humanClaims.verdicts = map[string]humanClaimCacheEntry{} + } + c.humanClaims.verdicts[key] = humanClaimCacheEntry{reason: reason, expires: now.Add(humanClaimCacheTTL)} + c.humanClaims.mu.Unlock() + return reason, nil +} + +// humanClaimCacheMax bounds the verdict cache. +const humanClaimCacheMax = 512 + +func (c *Client) readHumanClaim(ctx context.Context, repo string, number int, holder string) (string, error) { + owner, name := c.splitRepo(repo) + // A person's claim the ledger already holds (dashboard, hivectl) counts + // for the readers that do not consult the ledger themselves (adoption). + if claim, ok := c.ledgerClaimFor(owner, name, number, time.Now()); ok && strings.EqualFold(claim.Kind, string(claims.KindHuman)) && + !strings.EqualFold(claim.Identity, strings.TrimSpace(holder)) { + return claims.HumanClaimReason(humanClaimViaLedger, claim.Identity), nil + } + issue, _, err := c.client.Issues.Get(ctx, owner, name, number) + if err != nil { + return "", fmt.Errorf("checking issue for a human claim: %w", err) + } + if issue.IsPullRequest() || strings.EqualFold(issue.GetState(), "closed") { + return "", nil + } + holder = strings.TrimSpace(holder) + assignees := map[string]bool{} + for _, login := range extractAssignees(issue.Assignees) { + if login = strings.TrimSpace(login); login != "" && !strings.EqualFold(login, holder) && !c.isBotLogin(login) { + assignees[strings.ToLower(login)] = true + } + } + hasLabel := graceHasLabel(extractLabels(issue.Labels), claimedByHumanLabel) + + assigner, labeler, err := c.timelineClaimActors(ctx, owner, name, number, assignees, hasLabel) + if err != nil { + return "", err + } + for login := range assignees { + by := assigner[login] + if by == "" || strings.EqualFold(by, holder) || c.isBotLogin(by) { + continue + } + ok, err := c.isMaintainerLogin(ctx, owner, name, by) + if err != nil { + return "", err + } + if ok { + return claims.HumanClaimReason(humanClaimViaAssignee, by), nil + } + } + if labeler != "" && !strings.EqualFold(labeler, holder) && !c.isBotLogin(labeler) { + ok, err := c.isMaintainerLogin(ctx, owner, name, labeler) + if err != nil { + return "", err + } + if ok { + return claims.HumanClaimReason(humanClaimViaLabel, labeler), nil + } + } + comments, err := c.listIssueComments(ctx, owner, name, number) + if err != nil { + return "", err + } + if who := c.humanClaimCommenter(comments, holder); who != "" { + return claims.HumanClaimReason(humanClaimViaComment, who), nil + } + return "", nil +} + +// timelineClaimActors reads the issue timeline once and returns, per current +// assignee (lower-cased login), who last assigned them, and who last applied +// `hive/claimed-by-human` when that label is still on the issue. It reads +// nothing when there is no assignee and no such label. +func (c *Client) timelineClaimActors(ctx context.Context, owner, repo string, number int, assignees map[string]bool, hasLabel bool) (assigner map[string]string, labeler string, err error) { + assigner = map[string]string{} + if len(assignees) == 0 && !hasLabel { + return assigner, "", nil + } + opts := &gh.ListOptions{PerPage: 100} + for { + events, resp, lerr := c.client.Issues.ListIssueTimeline(ctx, owner, repo, number, opts) + if lerr != nil { + return nil, "", fmt.Errorf("listing timeline for %s/%s#%d: %w", owner, repo, number, lerr) + } + for _, ev := range events { + if ev == nil { + continue + } + actor := strings.TrimSpace(ev.GetActor().GetLogin()) + switch strings.ToLower(ev.GetEvent()) { + case "assigned": + if login := strings.ToLower(strings.TrimSpace(ev.GetAssignee().GetLogin())); assignees[login] { + assigner[login] = actor + } + case "unassigned": + delete(assigner, strings.ToLower(strings.TrimSpace(ev.GetAssignee().GetLogin()))) + case "labeled": + if strings.EqualFold(ev.GetLabel().GetName(), claimedByHumanLabel) { + labeler = actor + } + case "unlabeled": + if strings.EqualFold(ev.GetLabel().GetName(), claimedByHumanLabel) { + labeler = "" + } + } + } + if resp == nil || resp.NextPage == 0 { + return assigner, labeler, nil + } + opts.Page = resp.NextPage + } +} + +// humanClaimCommenter returns the login of an OWNER/MEMBER/COLLABORATOR whose +// latest claim comment is standing (not followed by their own `/unclaim`), +// skipping bots and the contributor holder; "" when there is none. +func (c *Client) humanClaimCommenter(comments []*gh.IssueComment, holder string) string { + standing := map[string]bool{} + var order []string + for _, cm := range comments { + if cm == nil || !ownerGraceAssociations[strings.ToUpper(cm.GetAuthorAssociation())] { + continue + } + login := strings.TrimSpace(cm.GetUser().GetLogin()) + if login == "" || strings.EqualFold(login, holder) || c.isBotLogin(login) { + continue + } + key := strings.ToLower(login) + switch { + case humanUnclaimCommentRe.MatchString(cm.GetBody()): + standing[key] = false + case humanClaimCommentRe.MatchString(cm.GetBody()): + if _, seen := standing[key]; !seen { + order = append(order, login) + } + standing[key] = true + } + } + for _, login := range order { + if standing[strings.ToLower(login)] { + return login + } + } + return "" +} + +// isBotLogin reports whether login is an App/bot account: the "[bot]" suffix +// GitHub puts on every App, or one of this hive's own configured logins. +func (c *Client) isBotLogin(login string) bool { + login = strings.TrimSpace(login) + return strings.HasSuffix(login, botLoginSuffix) || c.isHiveBotAccount(login) +} + +// isMaintainerLogin reports whether login has write access (write, maintain +// or admin) to the repository. A lookup error is returned, never read as +// "not a maintainer": the caller keeps the claim it holds. +func (c *Client) isMaintainerLogin(ctx context.Context, owner, repo, login string) (bool, error) { + key := strings.ToLower(owner + "/" + repo + "|" + login) + now := time.Now() + c.humanClaims.mu.Lock() + if e, ok := c.humanClaims.maintainer[key]; ok && now.Before(e.expires) { + c.humanClaims.mu.Unlock() + return e.ok, nil + } + c.humanClaims.mu.Unlock() + level, _, err := c.client.Repositories.GetPermissionLevel(ctx, owner, repo, login) + if err != nil { + return false, fmt.Errorf("permission lookup for %s on %s/%s: %w", login, owner, repo, err) + } + role := strings.ToLower(strings.TrimSpace(level.GetRoleName())) + perm := strings.ToLower(strings.TrimSpace(level.GetPermission())) + ok := unparkPermissionLevels[perm] || unparkPermissionLevels[role] + c.humanClaims.mu.Lock() + if c.humanClaims.maintainer == nil { + c.humanClaims.maintainer = map[string]maintainerCacheEntry{} + } + c.humanClaims.maintainer[key] = maintainerCacheEntry{ok: ok, expires: now.Add(maintainerPermissionTTL)} + c.humanClaims.mu.Unlock() + return ok, nil +} diff --git a/src/pkg/github/issue_human_claim_test.go b/src/pkg/github/issue_human_claim_test.go new file mode 100644 index 0000000000..73ea279805 --- /dev/null +++ b/src/pkg/github/issue_human_claim_test.go @@ -0,0 +1,196 @@ +package github + +import ( + "context" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/hivecommons/hive/pkg/claims" +) + +// humanClaimIssue describes the forge state behind IssueHumanClaimReason. +type humanClaimIssue struct { + state string + assignees []string + labels []string + // timeline events, as [event, subject, actor]: subject is the assignee + // for (un)assigned and the label for (un)labeled. + timeline [][3]string + // comments, as [login, association, body]. + comments [][3]string + // write maps a login to its repository permission. + write map[string]string +} + +func humanClaimServer(t *testing.T, in humanClaimIssue) *httptest.Server { + t.Helper() + if in.state == "" { + in.state = "open" + } + return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.URL.Path == "/repos/o/r/issues/42": + var as, ls []string + for _, a := range in.assignees { + as = append(as, fmt.Sprintf(`{"login":%q}`, a)) + } + for _, l := range in.labels { + ls = append(ls, fmt.Sprintf(`{"name":%q}`, l)) + } + fmt.Fprintf(w, `{"number":42,"state":%q,"assignees":[%s],"labels":[%s]}`, in.state, strings.Join(as, ","), strings.Join(ls, ",")) + case r.URL.Path == "/repos/o/r/issues/42/timeline": + var evs []string + for _, e := range in.timeline { + switch e[0] { + case "assigned", "unassigned": + evs = append(evs, fmt.Sprintf(`{"event":%q,"assignee":{"login":%q},"actor":{"login":%q}}`, e[0], e[1], e[2])) + default: + evs = append(evs, fmt.Sprintf(`{"event":%q,"label":{"name":%q},"actor":{"login":%q}}`, e[0], e[1], e[2])) + } + } + fmt.Fprintf(w, `[%s]`, strings.Join(evs, ",")) + case r.URL.Path == "/repos/o/r/issues/42/comments": + var cs []string + for _, c := range in.comments { + cs = append(cs, fmt.Sprintf(`{"user":{"login":%q},"author_association":%q,"body":%q}`, c[0], c[1], c[2])) + } + fmt.Fprintf(w, `[%s]`, strings.Join(cs, ",")) + case strings.HasPrefix(r.URL.Path, "/repos/o/r/collaborators/") && strings.HasSuffix(r.URL.Path, "/permission"): + login := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/repos/o/r/collaborators/"), "/permission") + perm := in.write[login] + if perm == "" { + perm = "read" + } + fmt.Fprintf(w, `{"permission":%q,"role_name":%q,"user":{"login":%q}}`, perm, perm, login) + default: + http.NotFound(w, r) + } + })) +} + +func humanClaimReasonFor(t *testing.T, in humanClaimIssue, holder string) string { + t.Helper() + srv := humanClaimServer(t, in) + defer srv.Close() + c := issueTestClient(t, srv.URL) + c.SetAppBotLogin("hive-app[bot]") + got, err := c.IssueHumanClaimReason(context.Background(), "o/r", 42, holder) + if err != nil { + t.Fatalf("IssueHumanClaimReason: %v", err) + } + return got +} + +// The operator's dispatcher claims with `gh issue edit --add-assignee` plus a +// plain "Claimed; fix in progress." comment and no ledger entry: an assignee +// set by an owner/maintainer on an open issue is a human claim. +func TestIssueHumanClaim_AssigneeSetByMaintainerPlusPlainComment(t *testing.T) { + got := humanClaimReasonFor(t, humanClaimIssue{ + assignees: []string{"andy"}, + timeline: [][3]string{{"assigned", "andy", "andy"}}, + comments: [][3]string{{"andy", "MEMBER", "Claimed; fix in progress."}}, + write: map[string]string{"andy": "admin"}, + }, "karibhou") + want := claims.HumanClaimReason("assigned", "andy") + if got != want { + t.Fatalf("reason = %q, want %q", got, want) + } + if login, ok := claims.ParseHumanClaimReason(got); !ok || login != "andy" { + t.Fatalf("reason %q does not parse back to the person", got) + } +} + +func TestIssueHumanClaim_AssigneeAlonePlusCommentAloneAndLabel(t *testing.T) { + // The assignee alone (no comment) is enough. + if got := humanClaimReasonFor(t, humanClaimIssue{ + assignees: []string{"andy"}, + timeline: [][3]string{{"assigned", "andy", "andy"}}, + write: map[string]string{"andy": "write"}, + }, "karibhou"); got != claims.HumanClaimReason("assigned", "andy") { + t.Fatalf("assignee alone: %q", got) + } + // A `/claim` comment from a maintainer (no assignee). + if got := humanClaimReasonFor(t, humanClaimIssue{ + comments: [][3]string{{"andy", "OWNER", "/claim\nworking on this"}}, + }, "karibhou"); got != claims.HumanClaimReason("/claim comment", "andy") { + t.Fatalf("/claim comment: %q", got) + } + // hive/claimed-by-human applied by hand by a maintainer. + if got := humanClaimReasonFor(t, humanClaimIssue{ + labels: []string{"hive/claimed-by-human"}, + timeline: [][3]string{{"labeled", "hive/claimed-by-human", "andy"}}, + write: map[string]string{"andy": "maintain"}, + }, "karibhou"); got != claims.HumanClaimReason("hive/claimed-by-human label", "andy") { + t.Fatalf("hand-applied label: %q", got) + } +} + +func TestIssueHumanClaim_NotAClaim(t *testing.T) { + cases := map[string]humanClaimIssue{ + "the hive's own App assigned it": { + assignees: []string{"someone"}, + timeline: [][3]string{{"assigned", "someone", "hive-app[bot]"}}, + }, + "the contributor's own assignment": { + assignees: []string{"karibhou"}, + timeline: [][3]string{{"assigned", "karibhou", "andy"}}, + write: map[string]string{"andy": "admin"}, + }, + "assigned by a user without write access": { + assignees: []string{"stranger"}, + timeline: [][3]string{{"assigned", "stranger", "stranger"}}, + }, + "label applied by the hive": { + labels: []string{"hive/claimed-by-human"}, + timeline: [][3]string{{"labeled", "hive/claimed-by-human", "hive-app[bot]"}}, + }, + "claim comment from an outside commenter": { + comments: [][3]string{{"stranger", "NONE", "/claim"}}, + }, + "claim comment withdrawn": { + comments: [][3]string{{"andy", "OWNER", "/claim"}, {"andy", "OWNER", "/unclaim"}}, + }, + "unassigned since": { + assignees: nil, + timeline: [][3]string{{"assigned", "andy", "andy"}, {"unassigned", "andy", "andy"}}, + write: map[string]string{"andy": "admin"}, + }, + "closed issue": { + state: "closed", + assignees: []string{"andy"}, + timeline: [][3]string{{"assigned", "andy", "andy"}}, + write: map[string]string{"andy": "admin"}, + }, + "the contributor's own claim comment": { + comments: [][3]string{{"karibhou", "COLLABORATOR", "/claim"}}, + }, + } + for name, in := range cases { + t.Run(name, func(t *testing.T) { + if got := humanClaimReasonFor(t, in, "karibhou"); got != "" { + t.Fatalf("reason = %q, want none", got) + } + }) + } +} + +func TestIssueHumanClaim_VerdictIsCached(t *testing.T) { + reads := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + reads++ + fmt.Fprint(w, `{"number":42,"state":"open"}`) + })) + defer srv.Close() + c := issueTestClient(t, srv.URL) + for i := 0; i < 3; i++ { + if _, err := c.IssueHumanClaimReason(context.Background(), "o/r", 42, "karibhou"); err != nil { + t.Fatal(err) + } + } + if reads != 1 { + t.Fatalf("forge reads = %d, want 1 (cached for %s)", reads, humanClaimCacheTTL) + } +} diff --git a/src/pkg/stagelabels/store.go b/src/pkg/stagelabels/store.go index e6099c9b7e..5f1bbd958d 100644 --- a/src/pkg/stagelabels/store.go +++ b/src/pkg/stagelabels/store.go @@ -1845,6 +1845,14 @@ const AdoptBlockedAuthorMaintainer = "author-is-maintainer" // re-home, so the request is consumed with one note instead of looping. const AdoptBlockedSelfAuthored = "self-authored" +// AdoptBlockedHumanClaim is the AdoptBlockedBy reason for a due adoption +// held because an owner or maintainer holds a claim on an issue the PR +// closes (assignee, `/claim` comment, hand-applied hive/claimed-by-human; +// hivecommons/hive#18899). The PR stays the contributor's until the person +// releases the claim, so the hive never opens a copy beside the owner's +// work. +const AdoptBlockedHumanClaim = "human-claim" + // AdoptBlockedSupersedeConflict is the AdoptBlockedBy reason (and the 07x // lane reason) for a supersession whose head could not be replayed onto a // fresh base: the hive copy would open conflicting, so the attempt is From 28d4dbf5c98755e5921d29d515cf98e8f39477cb Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Wed, 18 Nov 2026 00:59:49 -0500 Subject: [PATCH 2/5] =?UTF-8?q?=F0=9F=93=9D=20Re-anchor=20the=20scale-enve?= =?UTF-8?q?lope=20citation=20after=20the=20client.go=20insertions?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refs #18899 Signed-off-by: Andrew Anderson --- src/docs/scale-envelope.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/docs/scale-envelope.md b/src/docs/scale-envelope.md index 0753118509..8df6526d9c 100644 --- a/src/docs/scale-envelope.md +++ b/src/docs/scale-envelope.md @@ -34,7 +34,7 @@ ones to: 2. **Truncation must preserve the prioritization signal, not cut an arbitrary slice.** This holds today and is easy to assume backwards: - Issues are sorted by actionable rank tier, then **oldest first** within each tier before any cap is applied - (`RankActionableIssues`, `src/pkg/github/client.go:5369-5379`, descending `AgeMinutes` within each tier). + (`RankActionableIssues`, `src/pkg/github/client.go:5375-5385`, descending `AgeMinutes` within each tier). - PRs are sorted by **review class then oldest-first within class** (`SortPullRequestsForReview`, `src/pkg/github/review_priority.go:334`; fixes → refactors/docs → tests). From 8097901f4aa31f49c99f54b4cd90f059b7b23b4d Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Wed, 18 Nov 2026 01:09:09 -0500 Subject: [PATCH 3/5] =?UTF-8?q?=F0=9F=90=9B=20Fix=20test=20fixtures:=20no?= =?UTF-8?q?=20claim=20comment=20before=20the=20owner=20acts,=20no=20time.S?= =?UTF-8?q?leep?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refs #18899 Signed-off-by: Andrew Anderson --- src/cmd/hive/claims_admission_test.go | 6 +++++- src/pkg/dashboard/claims_human_release_test.go | 2 +- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/cmd/hive/claims_admission_test.go b/src/cmd/hive/claims_admission_test.go index 003aaa587e..5881978388 100644 --- a/src/cmd/hive/claims_admission_test.go +++ b/src/cmd/hive/claims_admission_test.go @@ -350,7 +350,11 @@ func TestContributorLeaseReleasedByOutOfLedgerHumanClaim(t *testing.T) { case "/repos/o/r/issues/9/timeline": fmt.Fprint(w, `[{"event":"assigned","assignee":{"login":"andy"},"actor":{"login":"andy"}}]`) case "/repos/o/r/issues/9/comments": - fmt.Fprint(w, `[{"user":{"login":"andy"},"author_association":"MEMBER","body":"Claimed; fix in progress."}]`) + if assigned.Load() { + fmt.Fprint(w, `[{"user":{"login":"andy"},"author_association":"MEMBER","body":"Claimed; fix in progress."}]`) + return + } + fmt.Fprint(w, `[]`) case "/repos/o/r/collaborators/andy/permission": fmt.Fprint(w, `{"permission":"admin","role_name":"admin","user":{"login":"andy"}}`) default: diff --git a/src/pkg/dashboard/claims_human_release_test.go b/src/pkg/dashboard/claims_human_release_test.go index ec5eb2a544..c7ed24e0b3 100644 --- a/src/pkg/dashboard/claims_human_release_test.go +++ b/src/pkg/dashboard/claims_human_release_test.go @@ -104,7 +104,7 @@ func TestClaims_RenewalMeetingAHumanClaimReleasesTheContributor(t *testing.T) { if c, ok := l.Lookup("myorg/repo1", 1); ok && c.Kind == claims.KindHuman && c.Holder == "andy" { return } - time.Sleep(10 * time.Millisecond) + <-time.After(10 * time.Millisecond) } c, ok := l.Lookup("myorg/repo1", 1) t.Fatalf("renewal did not hand the issue to the person: claim %+v (live %v)", c, ok) From 6f2bc5ba5cfc84f14b9418583cbe59b6a7b1760a Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Wed, 18 Nov 2026 01:16:22 -0500 Subject: [PATCH 4/5] =?UTF-8?q?=F0=9F=90=9B=20Keep=20the=20engine's=20opti?= =?UTF-8?q?onal=20transport=20hooks=20in=20the=20human-claim=20adoption=20?= =?UTF-8?q?test?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refs #18899 Signed-off-by: Andrew Anderson --- .../automerge/automerge_adoption_human_claim_test.go | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/pkg/github/automerge/automerge_adoption_human_claim_test.go b/src/pkg/github/automerge/automerge_adoption_human_claim_test.go index 44eb211aed..e147d96f63 100644 --- a/src/pkg/github/automerge/automerge_adoption_human_claim_test.go +++ b/src/pkg/github/automerge/automerge_adoption_human_claim_test.go @@ -7,12 +7,15 @@ import ( "time" "github.com/hivecommons/hive/pkg/claims" + hgithub "github.com/hivecommons/hive/pkg/github" "github.com/hivecommons/hive/pkg/stagelabels" ) -// humanClaimStub answers Engine.adoptionHumanClaim in place of the forge. +// humanClaimStub answers Engine.adoptionHumanClaim in place of the forge. It +// embeds the concrete client so every optional transport hook the engine type +// asserts for (the stage writer, the write-back gate) is still provided. type humanClaimStub struct { - Transport + *hgithub.Client mu sync.Mutex reason string asked []string @@ -38,7 +41,7 @@ func (s *humanClaimStub) set(reason string) { func TestAdoptionRefusedWhileAPersonHoldsAClaimOnTheIssue(t *testing.T) { h, done := newAdoptHarness(t, ContributorNudgeOutcome{Mode: "queued"}, adoptPolicy()) defer done() - stub := &humanClaimStub{Transport: h.e.transport} + stub := &humanClaimStub{Client: h.e.transport.(*hgithub.Client)} h.e.transport = stub start := h.clock.at h.sink.presence = &ContributorPresence{Registered: true, Online: false} From 4f4e466b1c9bb57c852c586a0664e615a3a108f2 Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Wed, 18 Nov 2026 01:25:13 -0500 Subject: [PATCH 5/5] =?UTF-8?q?=F0=9F=90=9B=20Serve=20an=20empty=20comment?= =?UTF-8?q?=20list=20in=20the=20verdict-cache=20test?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refs #18899 Signed-off-by: Andrew Anderson --- src/pkg/github/issue_human_claim_test.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/pkg/github/issue_human_claim_test.go b/src/pkg/github/issue_human_claim_test.go index 73ea279805..d7d874714e 100644 --- a/src/pkg/github/issue_human_claim_test.go +++ b/src/pkg/github/issue_human_claim_test.go @@ -180,6 +180,10 @@ func TestIssueHumanClaim_NotAClaim(t *testing.T) { func TestIssueHumanClaim_VerdictIsCached(t *testing.T) { reads := 0 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasSuffix(r.URL.Path, "/comments") { + fmt.Fprint(w, `[]`) + return + } reads++ fmt.Fprint(w, `{"number":42,"state":"open"}`) }))