Skip to content
1 change: 1 addition & 0 deletions changelog.d/fixed-orphaned-adoption.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- Recover supersede adoptions whose hive copy closed unmerged, restore ownership from PR markers, and show recovery (or a repeated-close pause) plainly in the tracker and delegated decisions.
17 changes: 15 additions & 2 deletions src/docs/labels-and-control-signals.md
Original file line number Diff line number Diff line change
Expand Up @@ -1091,8 +1091,21 @@ When a clanker-authored contributor PR goes red the hive does not just relabel i
its attempt before touching GitHub, so a failed `hive/adopt-<n>` push is
not retried on the next sweep. While in 074 the hive polls the superseder at most
every 10 minutes: merged → one `<!-- hive:adopted-merged -->` note and the
original is closed; closed unmerged (a maintainer declined) → the adoption
is forgotten and the original returns to 072 (not a regression).
original is closed; closed unmerged (a maintainer declined, or an old
sweep lost the copy) → the adoption is orphaned and recovered, not
forgotten: if the contributor head is still the adopted head, adoption is
still enabled and no hold label blocks takeover, the hive re-adopts on a
fresh `hive/adopt-<n>-retry-<m>` copy (`<m>` is the closed superseder's
number) and the original stays 074. Otherwise — the head moved, adoption
is off, a hold label is present, or the fresh copy could not be opened —
the hive posts one `<!-- hive:adoption-reverted -->` note, releases
ownership (the closed copy's `hive:adopted` marker is no longer evidence)
and the original returns to its pre-adoption flow (not a regression).
Loop guard: a retry copy closed again within an hour parks the original
at 085 with reason `adoption-child-closed-twice` and one
`<!-- hive:adoption-orphan-parked -->` note; a person decides whether to
resume. A transient fence fault (unreadable diff) defers the re-adoption
to the next sweep rather than reverting.
If an adopted head is DCO-red, an empty signed commit is never enough.
"Hive-authored" is decided the same way as head attribution above: an
unsigned commit is the hive's own only when GitHub links its author or
Expand Down
52 changes: 52 additions & 0 deletions src/pkg/dashboard/adoption_orphan_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package dashboard

import (
"net/http"
"strings"
"testing"
"time"

"github.com/hivecommons/hive/pkg/delegatedecision"
"github.com/hivecommons/hive/pkg/stagelabels"
)

func TestDelegatedOrphanDoesNotDeduplicateDeadDecision(t *testing.T) {
mock := &repoItemDecisionMock{prForeign: true, prRedCI: true, adoptionChildClosed: true}
mock.priorComments = []string{
delegatedecision.CommentBody(delegatedecision.Decision{Verdict: delegatedecision.VerdictAdoptSupersede, Rule: "contributor-offline"}, "h1", "writer"),
"<!-- hive:adopted mode=supersede superseded_by=90 head=feedfacefeedfacefeedfacefeedfacefeedface -->",
}
srv := newDelegatedServer(t, mock)
w := postDelegated(t, srv, 8, "writer", `{"type":"pr","reason":"requires_human"}`, nil)
if w.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
}
job := decodeDelegatedJob(t, w)
if job.Status != delegatedJobStatusDone || job.Result == nil || job.Result.Action == rowActionNoop {
t.Fatalf("orphan was a noop: %+v", job)
}
if !strings.Contains(job.Result.Outcome, "Re-adopting: hive's earlier copy #90") || !strings.Contains(strings.Join(mock.added, ","), delegatedecision.LabelAdoptSupersede) {
t.Fatalf("re-adoption not queued / explained: %+v labels=%v", job.Result, mock.added)
}
}

func TestTrackerOrphanAndLoopGuardArePlain(t *testing.T) {
now := time.Now()
s, store, status := adoptionFixture(t, now, "adopt", nil)
key := stagelabels.Key("hivecommons/hive", 14524)
store.MarkAdopted(key, "feed", 90, now)
store.Observe(key, stagelabels.NeedsDecision, "requires_human")
store.NoteAdoptionOrphan(key, 90, now, false)
pr := status.Repos[0].OpenPrs[0].(FrontendPR)
pr.Labels = []string{"stage/085-needs-decision", "needs-human", "author/clanker", "role/contributor"}
status.Repos[0].OpenPrs[0] = pr
it := trackerItem(t, s.buildStageTracker(status, store, now), "pr", 14524)
if !it.AdoptChildClosed || it.Caption != "Adopted → #90 (closed) · recovering" {
t.Fatalf("orphan hidden: %+v", it)
}
store.MarkAdoptionEscalated(key, "feed", "adoption-child-closed-twice")
it = trackerItem(t, s.buildStageTracker(status, store, now), "pr", 14524)
if !strings.Contains(it.Caption, "adoption-child-closed-twice") {
t.Fatalf("loop guard hidden: %+v", it)
}
}
28 changes: 26 additions & 2 deletions src/pkg/dashboard/api_repo_item_decide_delegated.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
package dashboard

import (
Expand Down Expand Up @@ -473,12 +473,33 @@
return delegatedOutcome{Err: err}
}
d, deciderNotes := s.decideDelegated(ctx, in)
orphan := 0
if in.Kind == delegatedecision.KindPR && !in.HiveAuthored && !d.KeepsPark {
owner, repo, _ := strings.Cut(repoFull, "/")
client := s.deps.GHClient
marker, readErr := ghpkg.ReadSupersedeAdoption(ctx, client.GoGitHub(), owner, repo, number, client.IsHiveAuthorLogin)
if readErr == nil && marker.By > 0 {
child, _, childErr := client.GoGitHub().PullRequests.Get(ctx, owner, repo, marker.By)
if childErr == nil && child.GetState() == "closed" && !child.GetMerged() {
orphan = marker.By
text := fmt.Sprintf("Re-adopting: hive's earlier copy #%d was closed by mistake; opening a fresh copy", orphan)
d = delegatedecision.Decision{Verdict: delegatedecision.VerdictAdoptSupersede, Rule: "adoption-orphaned", Text: text,
Actions: []delegatedecision.Action{{Kind: delegatedecision.ActionCommentDecision}, {Kind: delegatedecision.ActionAdoptSupersede}}}
if rec, ok := s.stageStoreOrShared().Get(stagelabels.Key(repoFull, number)); ok && rec.AdoptEscalatedReason == "adoption-child-closed-twice" {
d.KeepsPark = true
d.Text = "Adoption paused: adoption-child-closed-twice — the replacement was closed again within an hour; a person must decide whether to resume."
d.Actions = []delegatedecision.Action{{Kind: delegatedecision.ActionRecommendOnly}}
}
}
}
}
// The same rule firing again on an item the hive already decided would
// only repeat the comment: report it as a no-op instead of writing —
// unless the recorded decision never took effect, in which case say so
// in plain words with the options (hivecommons/hive#14822), or the
// operator asked to re-run it.
if prior := s.delegatedPriorDecisionState(ctx, repoFull, number, d.Rule); prior.Found && !req.Force {
// operator asked to re-run it. An orphaned adoption (the hive's earlier
// copy was closed unmerged) is re-run regardless of the prior record.
if prior := s.delegatedPriorDecisionState(ctx, repoFull, number, d.Rule); prior.Found && !req.Force && orphan == 0 {
kind := rowActionTargetIssue
if in.Kind == delegatedecision.KindPR {
kind = rowActionTargetPR
Expand All @@ -501,6 +522,9 @@
notes, execErr := s.executeDelegatedDecision(ctx, in, d, user, mergerRole)
notes = append(deciderNotes, notes...)
result := delegatedRowActionResult(in, d, notes)
if orphan > 0 && execErr == nil {
result.Outcome = d.Text
}
kinds := make([]string, 0, len(d.Actions))
for _, a := range d.Actions {
kinds = append(kinds, string(a.Kind))
Expand Down
11 changes: 8 additions & 3 deletions src/pkg/dashboard/api_repo_item_decision_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,9 @@ type repoItemDecisionMock struct {
edits []map[string]any
// prForeign makes PR #8 look like a human opened it; prLabels are the
// labels pulls/8 reports.
prForeign bool
prLabels []string
prForeign bool
prLabels []string
adoptionChildClosed bool
// prMergeState is PR #8's mergeable_state ("" = clean); prRedCI and
// prNoCI shape the head's combined status when the state alone does not
// settle CI (e.g. "blocked").
Expand Down Expand Up @@ -58,6 +59,8 @@ func newRepoItemDecisionServer(t *testing.T, m *repoItemDecisionMock) *Server {
labels = append(labels, map[string]string{"name": label})
}
_ = json.NewEncoder(w).Encode(map[string]any{"number": 7, "state": "open", "labels": labels, "user": map[string]any{"login": "hive[bot]", "type": "Bot"}})
case r.Method == http.MethodGet && strings.HasSuffix(path, "/pulls/90") && m.adoptionChildClosed:
_, _ = io.WriteString(w, `{"number":90,"state":"closed","merged":false}`)
case r.Method == http.MethodGet && (strings.HasSuffix(path, "/issues/8") || strings.HasSuffix(path, "/issues/9")):
n := 8
if strings.HasSuffix(path, "/issues/9") {
Expand Down Expand Up @@ -95,6 +98,8 @@ func newRepoItemDecisionServer(t *testing.T, m *repoItemDecisionMock) *Server {
}
case r.Method == http.MethodGet && strings.HasSuffix(path, "/commits/feedfacefeedfacefeedfacefeedfacefeedface/check-runs"):
_, _ = io.WriteString(w, `{"total_count":0,"check_runs":[]}`)
case r.Method == http.MethodGet && (strings.HasSuffix(path, "/pulls/8/commits") || strings.HasSuffix(path, "/pulls/8/reviews") || strings.HasSuffix(path, "/pulls/8/files")):
_, _ = io.WriteString(w, `[]`)
case r.Method == http.MethodGet && strings.Contains(path, "/timeline"):
_, _ = io.WriteString(w, `[]`)
case r.Method == http.MethodGet && (strings.HasSuffix(path, "/pulls/8/commits") || strings.HasSuffix(path, "/pulls/8/reviews")):
Expand All @@ -103,7 +108,7 @@ func newRepoItemDecisionServer(t *testing.T, m *repoItemDecisionMock) *Server {
case r.Method == http.MethodGet && strings.HasSuffix(path, "/comments"):
prior := make([]map[string]any, 0, len(m.priorComments))
for i, body := range m.priorComments {
prior = append(prior, map[string]any{"id": i + 1, "body": body, "created_at": "2026-10-28T12:01:00Z"})
prior = append(prior, map[string]any{"id": i + 1, "body": body, "created_at": "2026-10-28T12:01:00Z", "user": map[string]string{"login": "hive[bot]"}})
}
_ = json.NewEncoder(w).Encode(prior)
case r.Method == http.MethodPost && strings.HasSuffix(path, "/comments"):
Expand Down
17 changes: 13 additions & 4 deletions src/pkg/dashboard/stage_tracker.go
Original file line number Diff line number Diff line change
Expand Up @@ -398,10 +398,11 @@ type StageTrackerItem struct {
// reads "blocked on #N" and links to it; the caption says what lifts
// the block. State comes from the hive's caches only, never a fresh
// GitHub call (hivecommons/hive#14952; #14863 wore a bare grey `blocked`).
BlockedOnPR *StageTrackerBlockedOnPR `json:"blocked_on_pr,omitempty"`
NudgeCount int `json:"nudge_count,omitempty"`
LastNudgeAt *time.Time `json:"last_nudge_at,omitempty"`
AdoptedBy int `json:"adopted_by,omitempty"`
BlockedOnPR *StageTrackerBlockedOnPR `json:"blocked_on_pr,omitempty"`
NudgeCount int `json:"nudge_count,omitempty"`
LastNudgeAt *time.Time `json:"last_nudge_at,omitempty"`
AdoptedBy int `json:"adopted_by,omitempty"`
AdoptChildClosed bool `json:"adopt_child_closed,omitempty"`
// Adoption is, on a nudged PR at stage/072, whether adoption is due,
// what holds it, and the author's live presence, with the plain-words
// line the row shows instead of a bare "Returned to contributor"
Expand Down Expand Up @@ -1618,6 +1619,9 @@ func (s *Server) buildStageTracker(status *StatusPayload, store *stagelabels.Sto
it.LastNudgeAt = &t2
}
it.AdoptedBy = rec.AdoptedBy
// Cache-only (hivecommons/hive#14952): the engine persists the
// child's closed state via NoteAdoptionOrphan; no live GET here.
it.AdoptChildClosed = rec.AdoptChildClosed
it.SoakRemainingSeconds = int64(stageTrackerSoakRemaining(rec, now) / time.Second)
}
it.Hold = stageTrackerHoldFrom(rec, hasRec, labels)
Expand Down Expand Up @@ -1652,6 +1656,11 @@ func (s *Server) buildStageTracker(status *StatusPayload, store *stagelabels.Sto
it.Modifiers = slices.DeleteFunc(it.Modifiers, func(m string) bool { return m == modNeedsTriage })
}
it.Caption, it.Actor = stageTrackerCaption(stage, it.Reason, it.Author, it.Kind, it.Mirrored, rec, hasRec, it.LinkedPR, it.Head)
if rec.AdoptEscalatedReason == "adoption-child-closed-twice" {
it.Caption = "Adoption paused: adoption-child-closed-twice — the replacement was closed again within an hour"
} else if it.AdoptChildClosed {
it.Caption = fmt.Sprintf("Adopted → #%d (closed) · recovering", it.AdoptedBy)
}
// Adoption is clanker-only (a human's PR is never adopted), so a
// human-authored 072 row keeps its plain caption.
if stage == stagelabels.ReturnedToContributor && it.Kind == "pr" && it.AuthorKind != authorKindHuman {
Expand Down
5 changes: 3 additions & 2 deletions src/pkg/dashboard/static/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -13944,7 +13944,8 @@ <h3 class="faq-group-title">Where to get help</h3>
const STAGE_TRACKER_ADOPTED_BY_HIVE = 74;
function stageTrackerAdoptedWord(item) {
const by = Number(item && item.adopted_by) || 0;
return by > 0 ? 'Adopted → #' + by : '';
if (item && item.reason === 'adoption-child-closed-twice') return 'Adoption paused · adoption-child-closed-twice';
return by > 0 ? 'Adopted → #' + by + (item.adopt_child_closed ? ' (closed) · recovering' : '') : '';
}
const STAGE_TRACKER_UNAUTHORIZED_WORD = 'Awaiting human';
function stageTrackerUnauthorizedWord(item) {
Expand Down Expand Up @@ -14408,7 +14409,7 @@ <h3 class="faq-group-title">Where to get help</h3>
const terminal = anchor >= STAGE_TRACKER_TERMINAL;
const sentinelLane = stageTrackerSentinelInLane(item);
const detour = (!terminal && STAGE_TRACKER_PATH.indexOf(cur) < 0 && cur !== STAGE_TRACKER_TRIAGE_NEEDED && cur !== STAGE_TRACKER_POSSIBLY_EXISTS && cur !== 40 && cur !== 60 && cur !== STAGE_TRACKER_PRE_MERGE_SOAK && cur !== 100)
? { text: sentinelLane ? STAGE_TRACKER_SENTINEL_WORD : (cur === STAGE_TRACKER_READY_FOR_HUMAN_MERGE && item.manual_merge ? stageTrackerManualMergeWord(item) : (cur === STAGE_TRACKER_HUMAN_GATED && stageTrackerUnauthorizedWord(item)) || (cur === STAGE_TRACKER_ADOPTED_BY_HIVE && stageTrackerAdoptedWord(item)) || (cur === STAGE_TRACKER_READY_FOR_HUMAN_MERGE && stageTrackerReadyForHumanWord(item, STAGE_TRACKER_ACTIVE_WORD[cur] || curStage.short || curStage.label || String(cur))) || (STAGE_TRACKER_ACTIVE_WORD[cur] || curStage.short || curStage.label || String(cur))), sentinel: sentinelLane } : null;
? { text: sentinelLane ? STAGE_TRACKER_SENTINEL_WORD : (cur === STAGE_TRACKER_READY_FOR_HUMAN_MERGE && item.manual_merge ? stageTrackerManualMergeWord(item) : (cur === STAGE_TRACKER_HUMAN_GATED && stageTrackerUnauthorizedWord(item)) || ((cur === STAGE_TRACKER_ADOPTED_BY_HIVE || item.adopt_child_closed) && stageTrackerAdoptedWord(item)) || (cur === STAGE_TRACKER_READY_FOR_HUMAN_MERGE && stageTrackerReadyForHumanWord(item, STAGE_TRACKER_ACTIVE_WORD[cur] || curStage.short || curStage.label || String(cur))) || (STAGE_TRACKER_ACTIVE_WORD[cur] || curStage.short || curStage.label || String(cur))), sentinel: sentinelLane } : null;
const segs = STAGE_TRACKER_PATH.map(n => {
const st = n === 0 ? { label: 'Open', short: 'Open', description: 'Open, not yet in a stage' } : (byNum[n] || {});
let state = 'todo';
Expand Down
61 changes: 61 additions & 0 deletions src/pkg/github/adoption_marker.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package github

import (
"context"
"strconv"
"strings"

gh "github.com/google/go-github/v72/github"
)

// SupersedeAdoption is the durable ownership evidence on the original PR.
type SupersedeAdoption struct {
By int
Head string
}

// ReadSupersedeAdoption reads the latest hive-authored ownership marker, not
// merely the first adoption: a release invalidates earlier markers.
func ReadSupersedeAdoption(ctx context.Context, client *gh.Client, owner, repo string, number int, trusted func(string) bool) (SupersedeAdoption, error) {
var latest SupersedeAdoption
opts := &gh.IssueListCommentsOptions{ListOptions: gh.ListOptions{PerPage: 100}}
for {
comments, resp, err := client.Issues.ListComments(ctx, owner, repo, number, opts)
if err != nil {
return latest, err
}
for _, comment := range comments {
if !trusted(comment.GetUser().GetLogin()) {
continue
}
body := comment.GetBody()
if strings.HasPrefix(body, "<!-- hive:adoption-reverted -->") || strings.HasPrefix(body, "<!-- hive:adoption-yield") {
latest = SupersedeAdoption{}
continue
}
if !strings.HasPrefix(body, "<!-- hive:adopted ") {
continue
}
end := strings.Index(body, "-->")
if end < 0 {
continue
}
values := map[string]string{}
for _, field := range strings.Fields(body[:end]) {
k, v, ok := strings.Cut(field, "=")
if ok {
values[k] = v
}
}
by, _ := strconv.Atoi(values["superseded_by"])
latest = SupersedeAdoption{}
if by > 0 && values["head"] != "" && values["mode"] == "supersede" {
latest = SupersedeAdoption{By: by, Head: values["head"]}
}
}
if resp == nil || resp.NextPage == 0 {
return latest, nil
}
opts.Page = resp.NextPage
}
}
42 changes: 42 additions & 0 deletions src/pkg/github/adoption_marker_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package github

import (
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"testing"

gh "github.com/google/go-github/v72/github"
)

func TestReadSupersedeAdoptionLatestTrustedOwnership(t *testing.T) {
for _, reverted := range []bool{false, true} {
t.Run(map[bool]string{false: "latest adoption", true: "reverted"}[reverted], func(t *testing.T) {
comments := []map[string]any{}
add := func(author, body string) {
comments = append(comments, map[string]any{"user": map[string]string{"login": author}, "body": body})
}
add("hive[bot]", "<!-- hive:adopted mode=supersede superseded_by=90 head=aaa -->")
add("hive[bot]", "<!-- hive:adopted mode=supersede superseded_by=91 head=aaa -->")
add("attacker", "<!-- hive:adopted mode=supersede superseded_by=999 head=evil -->")
if reverted {
add("hive[bot]", "<!-- hive:adoption-reverted -->\nThe earlier copy closed unmerged.")
}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _ = json.NewEncoder(w).Encode(comments) }))
defer srv.Close()
client := gh.NewClient(srv.Client())
client.BaseURL, _ = url.Parse(srv.URL + "/")
marker, err := ReadSupersedeAdoption(t.Context(), client, "o", "r", 7, func(login string) bool { return login == "hive[bot]" })
if err != nil {
t.Fatal(err)
}
if reverted && marker.By != 0 {
t.Fatalf("reverted adoption restored: %+v", marker)
}
if !reverted && (marker.By != 91 || marker.Head != "aaa") {
t.Fatalf("wrong ownership: %+v", marker)
}
})
}
}
Loading
Loading