From 9c6f7cb17ef8c986bf4c0f3ed0f7773a9c7721ac Mon Sep 17 00:00:00 2001 From: mendezr Date: Wed, 28 Oct 2026 18:56:33 +0000 Subject: [PATCH 1/7] =?UTF-8?q?=F0=9F=90=9B=20fix:=20recover=20orphaned=20?= =?UTF-8?q?supersede=20adoptions?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Recover closed-unmerged adoption children before deriving stage labels, restore missing ownership from trusted markers, and park repeated child closures. Refresh delegated decisions and tracker wording for dead copies while preserving publishing fences and merged-child settlement. Co-authored-by: clubanderson <407614+clubanderson@users.noreply.github.com> Hive-Run: hivecommons/hive#15052 Hive-Plan: orphaned-adoption-recovery Hive-Spec: issue-15052#expected-1-4 Signed-off-by: mendezr --- changelog.d/fixed-orphaned-adoption.md | 1 + src/pkg/dashboard/adoption_orphan_test.go | 49 ++++++++ .../api_repo_item_decide_delegated.go | 28 ++++- .../dashboard/api_repo_item_decision_test.go | 9 +- src/pkg/dashboard/stage_tracker.go | 26 ++++- src/pkg/dashboard/static/index.html | 5 +- src/pkg/github/adoption_marker.go | 61 ++++++++++ src/pkg/github/adoption_marker_test.go | 42 +++++++ .../automerge/automerge_adoption_orphan.go | 76 +++++++++++++ .../automerge_adoption_orphan_test.go | 105 ++++++++++++++++++ .../automerge/automerge_contributor_adopt.go | 37 +++--- .../automerge_contributor_adopt_test.go | 15 +-- .../automerge/automerge_stage_labels.go | 31 ++++-- .../automerge/automerge_stage_labels_test.go | 2 + src/pkg/stageengine/derive_pr.go | 6 + .../derive_pr_adoption_yield_test.go | 9 ++ src/pkg/stagelabels/adoption_orphan_test.go | 29 +++++ src/pkg/stagelabels/store.go | 54 ++++++++- 18 files changed, 542 insertions(+), 43 deletions(-) create mode 100644 changelog.d/fixed-orphaned-adoption.md create mode 100644 src/pkg/dashboard/adoption_orphan_test.go create mode 100644 src/pkg/github/adoption_marker.go create mode 100644 src/pkg/github/adoption_marker_test.go create mode 100644 src/pkg/github/automerge/automerge_adoption_orphan.go create mode 100644 src/pkg/github/automerge/automerge_adoption_orphan_test.go create mode 100644 src/pkg/stagelabels/adoption_orphan_test.go diff --git a/changelog.d/fixed-orphaned-adoption.md b/changelog.d/fixed-orphaned-adoption.md new file mode 100644 index 0000000000..1172b12661 --- /dev/null +++ b/changelog.d/fixed-orphaned-adoption.md @@ -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. diff --git a/src/pkg/dashboard/adoption_orphan_test.go b/src/pkg/dashboard/adoption_orphan_test.go new file mode 100644 index 0000000000..7bb33fc799 --- /dev/null +++ b/src/pkg/dashboard/adoption_orphan_test.go @@ -0,0 +1,49 @@ +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"), + "", + } + 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) + 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) + } +} diff --git a/src/pkg/dashboard/api_repo_item_decide_delegated.go b/src/pkg/dashboard/api_repo_item_decide_delegated.go index 181bb97198..6da9152628 100644 --- a/src/pkg/dashboard/api_repo_item_decide_delegated.go +++ b/src/pkg/dashboard/api_repo_item_decide_delegated.go @@ -473,12 +473,33 @@ func (s *Server) decideDelegatedOne(ctx context.Context, repoFull string, number 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 @@ -501,6 +522,9 @@ func (s *Server) decideDelegatedOne(ctx context.Context, repoFull string, number 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)) diff --git a/src/pkg/dashboard/api_repo_item_decision_test.go b/src/pkg/dashboard/api_repo_item_decision_test.go index ee485e1bcd..cdb4da528a 100644 --- a/src/pkg/dashboard/api_repo_item_decision_test.go +++ b/src/pkg/dashboard/api_repo_item_decision_test.go @@ -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"). @@ -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") { @@ -103,7 +106,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"): diff --git a/src/pkg/dashboard/stage_tracker.go b/src/pkg/dashboard/stage_tracker.go index c3d87fdd34..898c625f66 100644 --- a/src/pkg/dashboard/stage_tracker.go +++ b/src/pkg/dashboard/stage_tracker.go @@ -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" @@ -1618,6 +1619,18 @@ func (s *Server) buildStageTracker(status *StatusPayload, store *stagelabels.Sto it.LastNudgeAt = &t2 } it.AdoptedBy = rec.AdoptedBy + it.AdoptChildClosed = rec.AdoptChildClosed + if rec.AdoptedBy > 0 && s.deps != nil && s.deps.GHClient != nil && s.deps.GHClient.GoGitHub() != nil { + owner, repo, ok := strings.Cut(it.Repo, "/") + if ok { + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + child, _, err := s.deps.GHClient.GoGitHub().PullRequests.Get(ctx, owner, repo, rec.AdoptedBy) + cancel() + if err == nil { + it.AdoptChildClosed = child.GetState() == "closed" && !child.GetMerged() + } + } + } it.SoakRemainingSeconds = int64(stageTrackerSoakRemaining(rec, now) / time.Second) } it.Hold = stageTrackerHoldFrom(rec, hasRec, labels) @@ -1652,6 +1665,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 { diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 33140c3241..1334c6250d 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -13944,7 +13944,8 @@

Where to get help

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) { @@ -14408,7 +14409,7 @@

Where to get help

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'; diff --git a/src/pkg/github/adoption_marker.go b/src/pkg/github/adoption_marker.go new file mode 100644 index 0000000000..d90c105fab --- /dev/null +++ b/src/pkg/github/adoption_marker.go @@ -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.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, "") || strings.HasPrefix(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 + } +} diff --git a/src/pkg/github/adoption_marker_test.go b/src/pkg/github/adoption_marker_test.go new file mode 100644 index 0000000000..154dfba773 --- /dev/null +++ b/src/pkg/github/adoption_marker_test.go @@ -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]", "") + add("hive[bot]", "") + add("attacker", "") + if reverted { + add("hive[bot]", "\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) + } + }) + } +} diff --git a/src/pkg/github/automerge/automerge_adoption_orphan.go b/src/pkg/github/automerge/automerge_adoption_orphan.go new file mode 100644 index 0000000000..2129851921 --- /dev/null +++ b/src/pkg/github/automerge/automerge_adoption_orphan.go @@ -0,0 +1,76 @@ +package automerge + +import ( + "context" + "fmt" + "time" + + gh "github.com/google/go-github/v72/github" + hgithub "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/stagelabels" +) + +const adoptionChildClosedTwice = "adoption-child-closed-twice" + +// Restore ownership from public evidence when an old sweep cleared the store. +// A marker's head is retained even when the contributor subsequently pushed: +// the merged-child path must still check whether it carried that new head. +func (c *Engine) restoreAdoptionMarker(ctx context.Context, store *stagelabels.Store, key string, obs stageObservation, now time.Time) error { + rec, ok := store.Get(key) + if rec.AdoptedBy > 0 || rec.AdoptedInPlace() || !obs.Detail.CommentsKnown || obs.Detail.Comments == 0 || + (rec.AdoptMarkerChecked && rec.AdoptMarkerComments == obs.Detail.Comments) { + return nil + } + marker, err := hgithub.ReadSupersedeAdoption(ctx, c.gh, obs.Owner, obs.Repo, obs.Number, c.transport.IsHiveAuthorLogin) + if err != nil { + return err + } + if !ok { + store.Observe(key, stagelabels.None, "") + } + if marker.By > 0 { + store.MarkAdopted(key, marker.Head, marker.By, now) + } + store.NoteAdoptionMarkerRead(key, obs.Detail.Comments) + return nil +} + +func (c *Engine) recoverOrphanedAdoption(ctx context.Context, store *stagelabels.Store, key string, obs stageObservation, rec stagelabels.Record, policy StageLabelPolicy, now time.Time) (int, error) { + store.NoteAdoptionOrphan(key, rec.AdoptedBy, now, false) + if rec.AdoptedBy != rec.AdoptOrphanPrevious && !rec.AdoptOrphanRetriedAt.IsZero() && now.Sub(rec.AdoptOrphanRetriedAt) < time.Hour { + store.MarkAdoptionEscalated(key, obs.HeadSHA, adoptionChildClosedTwice) + body := fmt.Sprintf("\nThe hive's replacement #%d was closed again within an hour. Paused at 085: %s. A person must decide whether to resume adoption.", rec.AdoptedBy, adoptionChildClosedTwice) + _, _, err := c.gh.Issues.CreateComment(ctx, obs.Owner, obs.Repo, obs.Number, &gh.IssueComment{Body: gh.Ptr(body)}) + if err != nil { + return 0, err + } + return 1, nil + } + if obs.HeadSHA != rec.AdoptedHead || !policy.Adoption || adoptionBlocked(obs.Labels) != "" { + return c.revertOrphanedAdoption(ctx, store, key, obs, rec.AdoptedBy, "the contributor head changed, adoption is disabled, or a hold label prevents takeover") + } + store.NoteAdoptionOrphan(key, rec.AdoptedBy, now, true) + retry, _ := store.Get(key) + // All publishing fences and mutation gates remain in supersedeAdoptedPR. + n, err := c.supersedeAdoptedPR(ctx, store, key, obs, retry, policy, nonEmpty(rec.AdoptReason, AdoptReasonOffline), 0, false, false, now) + after, _ := store.Get(key) + if after.AdoptedBy > 0 && after.AdoptedBy != rec.AdoptedBy { + c.info("stage labels: adoption orphaned, re-adopting", "repo", obs.Display, "pr", obs.Number, "old", rec.AdoptedBy, "new", after.AdoptedBy) + return n, err + } + reverted, revertErr := c.revertOrphanedAdoption(ctx, store, key, obs, rec.AdoptedBy, "the hive could not open a fresh copy; the original is back in its pre-adoption flow") + if err != nil { + return n + reverted, err + } + return n + reverted, revertErr +} + +func (c *Engine) revertOrphanedAdoption(ctx context.Context, store *stagelabels.Store, key string, obs stageObservation, previous int, reason string) (int, error) { + body := fmt.Sprintf("\nThe hive's earlier copy #%d was closed without merging. Adoption reverted: %s. This PR remains open for its author and normal review.", previous, reason) + if _, _, err := c.gh.Issues.CreateComment(ctx, obs.Owner, obs.Repo, obs.Number, &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { + return 0, err + } + rec, _ := store.Get(key) + store.RevertOrphanAdoption(key, nonEmpty(rec.AdoptedHead, obs.HeadSHA)) + return 1, nil +} diff --git a/src/pkg/github/automerge/automerge_adoption_orphan_test.go b/src/pkg/github/automerge/automerge_adoption_orphan_test.go new file mode 100644 index 0000000000..760dac1ec8 --- /dev/null +++ b/src/pkg/github/automerge/automerge_adoption_orphan_test.go @@ -0,0 +1,105 @@ +package automerge + +import ( + "encoding/json" + "net/http" + "strings" + "testing" + "time" + + gh "github.com/google/go-github/v72/github" + "github.com/hivecommons/hive/pkg/stagelabels" +) + +func TestOrphanRecoversAt085AndParksSecondClosedCopy(t *testing.T) { + h, done := adoptThenLeave074(t) + defer done() + key := stageKey("acme", "widget", 7) + h.adopt.setSuperseder(90, "closed", false) + h.api.reset() + labels := []string{"stage/085-needs-decision", "needs-human", "role/contributor", "author/clanker"} + h.observe(adoptPR(7, "aaa", labels...), stageReasonDecisionRequested) + rec, _ := h.e.stageStoreOrShared().Get(key) + if rec.AdoptedBy != 91 || len(h.adopt.pulls) != 2 { + t.Fatalf("085 orphan not recovered: %+v", rec) + } + // No ten-minute polling delay; a closed replacement is noticed immediately. + h.adopt.setSuperseder(91, "closed", false) + h.api.reset() + h.clock.advance(time.Minute) + h.observe(adoptPR(7, "aaa", labels...), stageReasonDecisionRequested) + rec, _ = h.e.stageStoreOrShared().Get(key) + if rec.Stage != stagelabels.NeedsDecision || rec.Reason != adoptionChildClosedTwice || len(h.adopt.pulls) != 2 { + t.Fatalf("loop not parked: %+v", rec) + } + h.api.reset() + h.observe(adoptPR(7, "aaa", labels...), stageReasonDecisionRequested) + if len(h.adopt.pulls) != 2 || len(h.api.comments) != 0 { + t.Fatalf("park churned: pulls=%v notes=%v", h.adopt.pulls, h.api.comments) + } +} + +func TestOrphanRevertsChangedHeadOrFailedPublish(t *testing.T) { + for _, changed := range []bool{false, true} { + t.Run(map[bool]string{true: "head moved", false: "publish failed"}[changed], func(t *testing.T) { + h, done := adoptThenLeave074(t) + defer done() + h.adopt.setSuperseder(90, "closed", false) + head := "aaa" + if changed { + head = "bbb" + } else { + h.adopt.failRefs = true + } + h.api.reset() + // Publish failure is returned, but must still release the original and + // leave a durable, plain-language reversion marker. + pr := adoptPR(7, head, "stage/074-adopted-by-hive", "author/clanker") + h.adopt.heads[7] = head + h.e.recordStage(stageLaneContributor, "acme/widget", "acme", "widget", pr, "check-failing:unit", false, nil) + _, _ = h.e.ApplyStageLabels(t.Context()) + rec, _ := h.e.stageStoreOrShared().Get(stageKey("acme", "widget", 7)) + if rec.AdoptedBy != 0 || rec.AdoptOrphanRevertedHead != "aaa" { + t.Fatalf("orphan not reverted: %+v", rec) + } + found := false + for _, note := range h.api.comments { + found = found || strings.HasPrefix(note, "") + } + if !found || len(h.adopt.pulls) != 1 { + t.Fatalf("missing reversion / duplicate attempt: %v %v", h.api.comments, h.adopt.pulls) + } + }) + } +} + +func TestOrphanMarkerRestoresLostStoreForClosedAndMergedCopy(t *testing.T) { + for _, merged := range []bool{false, true} { + t.Run(map[bool]string{false: "closed", true: "merged"}[merged], func(t *testing.T) { + h, done := adoptThenLeave074(t) + defer done() + h.e.stageStoreOrShared().ClearAdoption(stageKey("acme", "widget", 7)) + h.adopt.setSuperseder(90, "closed", merged) + prior := h.api.extra + h.api.extra = func(w http.ResponseWriter, r *http.Request) bool { + if r.Method == http.MethodGet && r.URL.Path == "/repos/acme/widget/issues/7/comments" { + _ = json.NewEncoder(w).Encode([]any{map[string]any{"body": "", "user": map[string]string{"login": testHiveAppBotLogin}}}) + return true + } + return prior(w, r) + } + pr := adoptPR(7, "aaa", "stage/085-needs-decision", "needs-human", "author/clanker") + pr.Comments = gh.Ptr(1) + h.api.reset() + h.observe(pr, stageReasonDecisionRequested) + rec, _ := h.e.stageStoreOrShared().Get(stageKey("acme", "widget", 7)) + if merged { + if rec.SupersededBy != 90 || len(h.adopt.prEdits) != 1 { + t.Fatalf("merged marker not settled: %+v edits=%v", rec, h.adopt.prEdits) + } + } else if rec.AdoptedBy != 91 || len(h.adopt.pulls) != 2 { + t.Fatalf("lost-store orphan not recovered: %+v", rec) + } + }) + } +} diff --git a/src/pkg/github/automerge/automerge_contributor_adopt.go b/src/pkg/github/automerge/automerge_contributor_adopt.go index c01af38c99..d2fdc60a89 100644 --- a/src/pkg/github/automerge/automerge_contributor_adopt.go +++ b/src/pkg/github/automerge/automerge_contributor_adopt.go @@ -38,7 +38,7 @@ import ( // existing red-PR repair route for hive-authored PRs) rebases it on the base // and fixes CI on that branch — no second kick mechanism. Once the App PR // merges the original is closed with a note; if the App PR is closed -// unmerged the adoption is forgotten and the original falls back to 072. +// unmerged orphan recovery opens a fresh copy or explicitly reverts adoption. // // One attempt per contributor head, whatever the outcome; a new head from // the author before adoption re-arms the nudge instead. @@ -150,6 +150,9 @@ func (c *Engine) contributorPresence(ctx context.Context, login string) (Contrib // no profile here (another hive posted the PR) is adopted after // AdoptAfterUnregistered. Without presence the nudge-time graces apply. func adoptionDue(rec stagelabels.Record, head string, policy StageLabelPolicy, now time.Time, presence ContributorPresence, hasPresence bool) (bool, string) { + if head != "" && rec.AdoptOrphanRevertedHead == head { + return false, "" + } start := rec.NudgeStart() if head == "" || rec.NudgeHead != head || rec.NudgeCount == 0 || start.IsZero() { return false, "" @@ -705,6 +708,9 @@ func (c *Engine) supersedeAdoptedPR(ctx context.Context, store *stagelabels.Stor return 0, err } branch := adoptBranchPrefix + strconv.Itoa(number) + if rec.AdoptOrphanPrevious > 0 { + branch += "-retry-" + strconv.Itoa(rec.AdoptOrphanPrevious) + } fullRepo := owner + "/" + repo // resignedTip stays "" when the branch falls back to the unsigned // contributor head; the body then keeps the manual DCO repair steps. @@ -977,21 +983,17 @@ func (c *Engine) settleAdoption(ctx context.Context, store *stagelabels.Store, k return c.supersedeAdoptedPR(ctx, store, key, obs, rec, policy, AdoptReasonDCORehome, 0, false, true, now) } } - if rec.AdoptedBy <= 0 { - return 0, nil - } - return c.settleSuperseder(ctx, store, key, obs, rec, now) + // Superseding children are settled before stage derivation, even when + // the lane does not put the original at 074. + return 0, nil } // settleSuperseder polls the superseding App PR recorded on an adoption (at -// most every adoptCheckInterval) and settles the original: merged → close -// note + close; closed unmerged → forget the adoption. It runs for a PR at -// 074 and, since hivecommons/hive#14471, for any other stage the lane -// derives while the superseder is on record: a `needs-human` label (085) or -// a contributor push after the adoption (072) used to stop the poll, and the -// original stayed open with "closed automatically once #N merges" on it. -func (c *Engine) settleSuperseder(ctx context.Context, store *stagelabels.Store, key string, obs stageObservation, rec stagelabels.Record, now time.Time) (int, error) { - if obs.Merged || !rec.SupersederPollDue(now, adoptCheckInterval) { +// every stage pass) and settles the original: merged → close +// note + close; closed unmerged → recover or explicitly revert ownership. +// This runs before stage derivation on every pass, including at 085. +func (c *Engine) settleSuperseder(ctx context.Context, store *stagelabels.Store, key string, obs stageObservation, rec stagelabels.Record, policy StageLabelPolicy, now time.Time) (int, error) { + if obs.Merged || rec.AdoptedBy <= 0 { return 0, nil } store.MarkAdoptChecked(key, now) @@ -1004,8 +1006,10 @@ func (c *Engine) settleSuperseder(ctx context.Context, store *stagelabels.Store, case sup.GetMerged(): return c.closeSupersededOriginal(ctx, store, key, obs, rec, sup, now) case strings.EqualFold(sup.GetState(), "closed"): - c.warn("stage labels: adoption superseder closed unmerged; returning PR to the contributor", "repo", obs.Display, "pr", obs.Number, "superseded_by", rec.AdoptedBy) - store.ClearAdoption(key) + if rec.AdoptEscalatedReason == adoptionChildClosedTwice { + return 0, nil + } + return c.recoverOrphanedAdoption(ctx, store, key, obs, rec, policy, now) } return 0, nil } @@ -1547,6 +1551,9 @@ func (c *Engine) escapeStalledAdoption(ctx context.Context, store *stagelabels.S if !ok { return adoptionEscape{}, 0, nil } + if rec.AdoptEscalatedReason == adoptionChildClosedTwice { + return adoptionEscape{Escalated: true, Reason: adoptionChildClosedTwice}, 0, nil + } if store.StampAdoptedHeadAt(key, obs.HeadSHA) { // Pre-#13040 record: the head clock starts now, not at AdoptedAt. c.info("stage labels: adopted head had no clock; starting the 074 dwell from this sweep", "repo", obs.Display, "pr", obs.Number, "head", obs.HeadSHA, "adopted_at", rec.AdoptedAt) diff --git a/src/pkg/github/automerge/automerge_contributor_adopt_test.go b/src/pkg/github/automerge/automerge_contributor_adopt_test.go index cacaf9dd95..f70e1ff8e2 100644 --- a/src/pkg/github/automerge/automerge_contributor_adopt_test.go +++ b/src/pkg/github/automerge/automerge_contributor_adopt_test.go @@ -697,9 +697,8 @@ func TestAdoptionOfflineGraceThenSupersederMergedClosesOriginal(t *testing.T) { } } -// Superseder closed unmerged: the adoption is forgotten and the PR falls -// back to 072 (a maintainer declined the takeover). -func TestAdoptionSupersederClosedUnmergedReturnsTo072(t *testing.T) { +// A closed copy must not orphan the original, even without a new head. +func TestAdoptionSupersederClosedUnmergedReadopts(t *testing.T) { h, done := newAdoptHarness(t, ContributorNudgeOutcome{Mode: "comment"}, adoptPolicy()) defer done() h.observe(adoptPR(7, "aaa"), "check-failing:unit") @@ -714,10 +713,12 @@ func TestAdoptionSupersederClosedUnmergedReturnsTo072(t *testing.T) { if len(h.adopt.prEdits) != 0 { t.Fatalf("original closed although superseder was abandoned: %v", h.adopt.prEdits) } - h.api.reset() - h.observe(adoptPR(7, "aaa", "stage/074-adopted-by-hive", "role/contributor", "author/clanker"), "check-failing:unit") - if added := h.addedLabels(); len(added) != 1 || added[0] != "stage/072-returned-to-contributor" { - t.Fatalf("fallback to 072: added=%v removed=%v", h.api.added, h.api.removed) + rec, _ := h.e.stageStoreOrShared().Get(stageKey("acme", "widget", 7)) + if rec.AdoptedBy != 91 || len(h.adopt.pulls) != 2 || h.adopt.pulls[1]["head"] != "hive/adopt-7-retry-90" { + t.Fatalf("orphan not re-adopted: rec=%+v pulls=%v", rec, h.adopt.pulls) + } + if notes := adoptionComments(h.api); len(notes) != 1 || !strings.Contains(notes[0], "superseded_by=91") { + t.Fatalf("fresh adoption marker missing: %v", notes) } } diff --git a/src/pkg/github/automerge/automerge_stage_labels.go b/src/pkg/github/automerge/automerge_stage_labels.go index b0b66b899b..8cb3151144 100644 --- a/src/pkg/github/automerge/automerge_stage_labels.go +++ b/src/pkg/github/automerge/automerge_stage_labels.go @@ -840,6 +840,24 @@ func (c *Engine) ApplyStageLabels(ctx context.Context) (StageLabelResult, error) if verdict.Reason != "" { obs.Reason = verdict.Reason } + // Settle supersession before deriving ANY stage. A stale reviewer + // verdict must not hide a dead child (or a merged one). + if !verdict.Terminal && obs.Lane != stageLaneSelf && !obs.Merged { + if err := c.restoreAdoptionMarker(ctx, store, key, obs, now); err != nil && firstErr == nil { + firstErr = err + } + if rec, ok := store.Get(key); ok && rec.AdoptedBy > 0 { + n, err := c.settleSuperseder(ctx, store, key, obs, rec, policy, now) + result.Comments += n + store.CountOwnComments(key, n) + if err != nil && firstErr == nil { + firstErr = err + } + if after, _ := store.Get(key); after.SupersededBy > 0 { + continue + } + } + } prevRec, hadPrev := store.Get(key) // pass is what this pass learns past resolveStage; it rides on the // Facts so the engine's DerivePR reproduces the stage written here. @@ -1010,6 +1028,10 @@ func (c *Engine) ApplyStageLabels(ctx context.Context) (StageLabelResult, error) pass.EscalationReason = esc.Reason } } + if rec, ok := store.Get(key); ok && rec.AdoptEscalatedReason == adoptionChildClosedTwice { + verdict.Stage, verdict.Rank = stagelabels.NeedsDecision, stageRankOwned + obs.Reason, pass.EscalationReason = adoptionChildClosedTwice, adoptionChildClosedTwice + } tr = store.Observe(key, verdict.Stage, obs.Reason) // hivecommons/hive#12502: remember the author so the dashboard can // list "PRs returned to this contributor" from the store alone. @@ -1212,15 +1234,6 @@ func (c *Engine) ApplyStageLabels(ctx context.Context) (StageLabelResult, error) if err != nil && firstErr == nil { firstErr = err } - } else if rec, ok := store.Get(key); ok && rec.AdoptedBy > 0 && !obs.Merged { - // hivecommons/hive#14471: the superseder is still on record while - // the lane derives 085 (needs-human) or 072 (a later contributor - // head). Its merge must still close this PR. - n, err := c.settleSuperseder(ctx, store, key, obs, rec, now) - result.Comments += n - if err != nil && firstErr == nil { - firstErr = err - } } if tr.Regressed { // Keyed by head SHA: a gate flapping between two stages on one diff --git a/src/pkg/github/automerge/automerge_stage_labels_test.go b/src/pkg/github/automerge/automerge_stage_labels_test.go index 44761dca7d..89ccf1a547 100644 --- a/src/pkg/github/automerge/automerge_stage_labels_test.go +++ b/src/pkg/github/automerge/automerge_stage_labels_test.go @@ -155,6 +155,8 @@ func newStageAPI(t *testing.T, api *stageAPI) *httptest.Server { case r.Method == http.MethodDelete && strings.Contains(path, "/labels/"): api.removed = append(api.removed, path[strings.LastIndex(path, "/labels/")+len("/labels/"):]) w.WriteHeader(http.StatusNoContent) + case r.Method == http.MethodGet && strings.HasSuffix(path, "/comments"): + _ = json.NewEncoder(w).Encode([]any{}) case r.Method == http.MethodPost && strings.HasSuffix(path, "/comments"): var body map[string]string _ = json.NewDecoder(r.Body).Decode(&body) diff --git a/src/pkg/stageengine/derive_pr.go b/src/pkg/stageengine/derive_pr.go index 8db356632b..73f59f568e 100644 --- a/src/pkg/stageengine/derive_pr.go +++ b/src/pkg/stageengine/derive_pr.go @@ -285,6 +285,12 @@ func passDecision(verdict stageVerdict, role stagelabels.Role, obs stageObservat obs.Reason = pass.EscalationReason } } + // Repeatedly closed adoption children are an ownership loop, not a + // reviewer verdict; explicit human routing must retain that reason. + if !verdict.Terminal && pass.EscalationReason == "adoption-child-closed-twice" { + verdict.Stage, verdict.Rank = stagelabels.NeedsDecision, stageRankOwned + obs.Reason = pass.EscalationReason + } d := Decision{ Stage: verdict.Stage, Role: role, diff --git a/src/pkg/stageengine/derive_pr_adoption_yield_test.go b/src/pkg/stageengine/derive_pr_adoption_yield_test.go index e6145639a9..fac812b222 100644 --- a/src/pkg/stageengine/derive_pr_adoption_yield_test.go +++ b/src/pkg/stageengine/derive_pr_adoption_yield_test.go @@ -66,6 +66,15 @@ func TestDerivePR_NeedsDecisionKeepsParkUnderHoldOrSentinel(t *testing.T) { } } +func TestDerivePR_ClosedChildLoopKeepsReasonUnderHumanRouting(t *testing.T) { + f := supersededAdoptionFacts(stagelabels.VerdictRequiresHuman, "requires_human") + f.PR.Pass = &PRPassFacts{Route: &stagelabels.Evidence{HeadFresh: true, Holds: []string{"needs-human"}}, EscalationReason: "adoption-child-closed-twice"} + d := DerivePR(f) + if d.Stage != stagelabels.NeedsDecision || d.Reason != "adoption-child-closed-twice" { + t.Fatalf("loop guard reason lost: %+v", d) + } +} + func TestDerivePR_EscalatedAdoptionStaysAtNeedsDecision(t *testing.T) { f := supersededAdoptionFacts(stagelabels.VerdictRequiresHuman, "requires_human") f.PR.Pass = &PRPassFacts{Route: &stagelabels.Evidence{HeadFresh: true, Verdict: stagelabels.VerdictRequiresHuman}, AdoptionLive: true, EscalationReason: "adoption-escalated:dco"} diff --git a/src/pkg/stagelabels/adoption_orphan_test.go b/src/pkg/stagelabels/adoption_orphan_test.go new file mode 100644 index 0000000000..8b890518fb --- /dev/null +++ b/src/pkg/stagelabels/adoption_orphan_test.go @@ -0,0 +1,29 @@ +package stagelabels + +import ( + "path/filepath" + "testing" + "time" +) + +func TestOrphanRetryGuardSurvivesReversionAndReload(t *testing.T) { + now := time.Now().UTC() + path := filepath.Join(t.TempDir(), "stages.json") + store := NewStore(path, func() time.Time { return now }) + key := Key("o/r", 7) + store.Observe(key, AdoptedByHive, "adopted") + store.MarkAdopted(key, "aaa", 90, now) + store.NoteAdoptionOrphan(key, 90, now, true) + store.RevertOrphanAdoption(key, "aaa") + if err := store.Save(); err != nil { + t.Fatal(err) + } + reloaded := NewStore(path, func() time.Time { return now }) + if err := reloaded.Load(); err != nil { + t.Fatal(err) + } + rec, ok := reloaded.Get(key) + if !ok || rec.AdoptedBy != 0 || rec.AdoptOrphanPrevious != 90 || !rec.AdoptOrphanRetriedAt.Equal(now) || rec.AdoptOrphanRevertedHead != "aaa" { + t.Fatalf("lost orphan retry guard: %+v", rec) + } +} diff --git a/src/pkg/stagelabels/store.go b/src/pkg/stagelabels/store.go index 412ec1be16..0a2f4352fa 100644 --- a/src/pkg/stagelabels/store.go +++ b/src/pkg/stagelabels/store.go @@ -163,6 +163,14 @@ type Record struct { // than reading the dwell from AdoptedAt, which may be a head or more // behind. AdoptedHeadSince resolves it. AdoptedHeadAt time.Time `json:"adopted_head_at,omitempty"` + // Orphan recovery survives ClearAdoption and process restarts. A unique + // predecessor also gives the replacement its own mutation identity. + AdoptOrphanRetriedAt time.Time `json:"adopt_orphan_retried_at,omitempty"` + AdoptOrphanPrevious int `json:"adopt_orphan_previous,omitempty"` + AdoptOrphanRevertedHead string `json:"adopt_orphan_reverted_head,omitempty"` + AdoptChildClosed bool `json:"adopt_child_closed,omitempty"` + AdoptMarkerComments int `json:"adopt_marker_comments,omitempty"` + AdoptMarkerChecked bool `json:"adopt_marker_checked,omitempty"` // AdoptEscalatedHead / AdoptEscalatedReason record that the adoption // sits at this head past the 074 dwell with nothing the hive can push // and is a person's (stage 085) for that lane reason. The escalation @@ -1076,6 +1084,7 @@ func (s *Store) MarkAdopted(key, head string, by int, now time.Time) { if !ok { return } + r.AdoptChildClosed = false r.AdoptedHead, r.AdoptedBy, r.AdoptedAt, r.AdoptCheckedAt = head, by, now, now r.AdoptMode = AdoptModeSupersede r.AdoptBlockedHead, r.AdoptBlockedBy, r.AdoptBlockedAt = "", "", time.Time{} @@ -1231,7 +1240,49 @@ func (s *Store) ClearAdoptionEscalation(key string) { s.dirty = true } -// ClearAdoption forgets the adoption (the superseding PR closed unmerged). +// NoteAdoptionOrphan records the dead child and, for a retry, its time. +func (s *Store) NoteAdoptionOrphan(key string, previous int, now time.Time, retry bool) { + s.mu.Lock() + defer s.mu.Unlock() + r, ok := s.items[key] + if !ok { + return + } + r.AdoptChildClosed = true + if retry { + r.AdoptOrphanPrevious, r.AdoptOrphanRetriedAt = previous, now + } + s.items[key], s.dirty = r, true +} + +// RevertOrphanAdoption releases ownership without automatically re-trying +// the same failed takeover on the next stage pass. An explicit request or +// a new contributor head can still start a new adoption. +func (s *Store) RevertOrphanAdoption(key, head string) { + s.ClearAdoption(key) + s.mu.Lock() + defer s.mu.Unlock() + r, ok := s.items[key] + if !ok { + return + } + r.AdoptOrphanRevertedHead = head + s.items[key], s.dirty = r, true +} + +// NoteAdoptionMarkerRead avoids re-listing unchanged comment history. +func (s *Store) NoteAdoptionMarkerRead(key string, comments int) { + s.mu.Lock() + defer s.mu.Unlock() + r, ok := s.items[key] + if !ok { + return + } + r.AdoptMarkerChecked, r.AdoptMarkerComments = true, comments + s.items[key], s.dirty = r, true +} + +// ClearAdoption forgets the adoption, preserving the orphan retry guard. func (s *Store) ClearAdoption(key string) { s.mu.Lock() defer s.mu.Unlock() @@ -1243,6 +1294,7 @@ func (s *Store) ClearAdoption(key string) { r.AdoptMode, r.AdoptReason, r.AdoptDiffFence = "", "", "" r.AdoptedHeadAt, r.AdoptEscalatedHead, r.AdoptEscalatedReason, r.AdoptEscalationNotedHead = time.Time{}, "", "", "" r.AdoptRecoveryAttempt, r.AdoptRecoveryCount = "", 0 + r.AdoptChildClosed = false r.SupersededBy, r.SupersededAt, r.SupersededOpen, r.SupersederMergedNotedHead = 0, time.Time{}, false, "" s.items[key] = r s.dirty = true From 46dcd7f837c44eb23ea3bea728b5394fcd75d500 Mon Sep 17 00:00:00 2001 From: mendezr Date: Wed, 28 Oct 2026 19:00:27 +0000 Subject: [PATCH 2/7] =?UTF-8?q?=F0=9F=90=9B=20fix:=20use=20issue=20comment?= =?UTF-8?q?=20list=20options=20for=20adoption=20markers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: mendezr --- src/pkg/github/adoption_marker.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pkg/github/adoption_marker.go b/src/pkg/github/adoption_marker.go index d90c105fab..a6086fbd80 100644 --- a/src/pkg/github/adoption_marker.go +++ b/src/pkg/github/adoption_marker.go @@ -18,7 +18,7 @@ type SupersedeAdoption struct { // 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.ListOptions{PerPage: 100} + opts := &gh.IssueListCommentsOptions{ListOptions: gh.ListOptions{PerPage: 100}} for { comments, resp, err := client.Issues.ListComments(ctx, owner, repo, number, opts) if err != nil { From 59188fb9742b5b9dd8575f620046190a4cc1976f Mon Sep 17 00:00:00 2001 From: mendezr Date: Wed, 28 Oct 2026 19:04:41 +0000 Subject: [PATCH 3/7] =?UTF-8?q?=F0=9F=90=9B=20fix:=20expose=20hive=20autho?= =?UTF-8?q?r=20identity=20on=20automerge=20transport?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: mendezr --- src/pkg/github/automerge/automerge_sweep.go | 3 +++ src/pkg/github/automerge/repo_pause_test.go | 3 +++ src/pkg/github/automerge/self_authorization_release_test.go | 3 +++ 3 files changed, 9 insertions(+) diff --git a/src/pkg/github/automerge/automerge_sweep.go b/src/pkg/github/automerge/automerge_sweep.go index 5010d46851..aa12882138 100644 --- a/src/pkg/github/automerge/automerge_sweep.go +++ b/src/pkg/github/automerge/automerge_sweep.go @@ -32,6 +32,9 @@ type Transport interface { SplitRepo(repo string) (owner, repoName string) AutoMergeLabel() string AppBotLogin() string + // IsHiveAuthorLogin authenticates adoption markers against this hive's + // configured posting identities, not arbitrary bot accounts. + IsHiveAuthorLogin(login string) bool IsExemptLabels(labels []string) bool // IsHeldLabels reports whether labels carry a hold the transport's owner // configured: the generic hold substrings plus the exact hive-scoped diff --git a/src/pkg/github/automerge/repo_pause_test.go b/src/pkg/github/automerge/repo_pause_test.go index d3038e29c7..b0fa618bd4 100644 --- a/src/pkg/github/automerge/repo_pause_test.go +++ b/src/pkg/github/automerge/repo_pause_test.go @@ -47,6 +47,9 @@ func (p pauseBlindTransport) IsExemptLabels([]string) bool func (p pauseBlindTransport) IsHeldLabels(labels []string) bool { return hgithub.HasHoldLabel(labels) } func (p pauseBlindTransport) UpdateBranch(context.Context, string, int) error { return nil } func (p pauseBlindTransport) RecordPRMergedAudit(string, int, string, string, string) {} +func (p pauseBlindTransport) IsHiveAuthorLogin(login string) bool { + return stubTransport{}.IsHiveAuthorLogin(login) +} func TestEngineActiveRepos_FallsBackWithoutCapability(t *testing.T) { transport := pauseBlindTransport{repos: []string{"widget", "gadget"}} diff --git a/src/pkg/github/automerge/self_authorization_release_test.go b/src/pkg/github/automerge/self_authorization_release_test.go index 6be0dee522..b5d427e58a 100644 --- a/src/pkg/github/automerge/self_authorization_release_test.go +++ b/src/pkg/github/automerge/self_authorization_release_test.go @@ -29,6 +29,9 @@ func (stubTransport) UpdateBranch(context.Context, string, int) error { return nil } func (stubTransport) RecordPRMergedAudit(string, int, string, string, string) {} +func (s stubTransport) IsHiveAuthorLogin(login string) bool { + return strings.EqualFold(strings.TrimSpace(login), s.AppBotLogin()) +} func TestSelfAuthorizationReleaseBudget(t *testing.T) { var nilEngine *Engine From c86fe3b54ce2110b9c573f7c622079b14169a084 Mon Sep 17 00:00:00 2001 From: mendezr Date: Wed, 28 Oct 2026 19:13:34 +0000 Subject: [PATCH 4/7] =?UTF-8?q?=F0=9F=90=9B=20fix:=20preserve=20adoption?= =?UTF-8?q?=20settlement=20guards=20and=20repair=20CI=20fixtures?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: mendezr --- src/pkg/dashboard/adoption_orphan_test.go | 3 +++ src/pkg/dashboard/api_repo_item_decision_test.go | 2 ++ .../github/automerge/automerge_adoption_orphan_test.go | 8 ++++---- src/pkg/github/automerge/automerge_contributor_adopt.go | 9 ++++++++- 4 files changed, 17 insertions(+), 5 deletions(-) diff --git a/src/pkg/dashboard/adoption_orphan_test.go b/src/pkg/dashboard/adoption_orphan_test.go index 7bb33fc799..1a5f3f700f 100644 --- a/src/pkg/dashboard/adoption_orphan_test.go +++ b/src/pkg/dashboard/adoption_orphan_test.go @@ -37,6 +37,9 @@ func TestTrackerOrphanAndLoopGuardArePlain(t *testing.T) { 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) diff --git a/src/pkg/dashboard/api_repo_item_decision_test.go b/src/pkg/dashboard/api_repo_item_decision_test.go index cdb4da528a..70111605c7 100644 --- a/src/pkg/dashboard/api_repo_item_decision_test.go +++ b/src/pkg/dashboard/api_repo_item_decision_test.go @@ -98,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")): diff --git a/src/pkg/github/automerge/automerge_adoption_orphan_test.go b/src/pkg/github/automerge/automerge_adoption_orphan_test.go index 760dac1ec8..d8725e55d0 100644 --- a/src/pkg/github/automerge/automerge_adoption_orphan_test.go +++ b/src/pkg/github/automerge/automerge_adoption_orphan_test.go @@ -18,7 +18,7 @@ func TestOrphanRecoversAt085AndParksSecondClosedCopy(t *testing.T) { h.adopt.setSuperseder(90, "closed", false) h.api.reset() labels := []string{"stage/085-needs-decision", "needs-human", "role/contributor", "author/clanker"} - h.observe(adoptPR(7, "aaa", labels...), stageReasonDecisionRequested) + h.observe(adoptPR(7, "aaa", labels...), "label:needs-human") rec, _ := h.e.stageStoreOrShared().Get(key) if rec.AdoptedBy != 91 || len(h.adopt.pulls) != 2 { t.Fatalf("085 orphan not recovered: %+v", rec) @@ -27,13 +27,13 @@ func TestOrphanRecoversAt085AndParksSecondClosedCopy(t *testing.T) { h.adopt.setSuperseder(91, "closed", false) h.api.reset() h.clock.advance(time.Minute) - h.observe(adoptPR(7, "aaa", labels...), stageReasonDecisionRequested) + h.observe(adoptPR(7, "aaa", labels...), "label:needs-human") rec, _ = h.e.stageStoreOrShared().Get(key) if rec.Stage != stagelabels.NeedsDecision || rec.Reason != adoptionChildClosedTwice || len(h.adopt.pulls) != 2 { t.Fatalf("loop not parked: %+v", rec) } h.api.reset() - h.observe(adoptPR(7, "aaa", labels...), stageReasonDecisionRequested) + h.observe(adoptPR(7, "aaa", labels...), "label:needs-human") if len(h.adopt.pulls) != 2 || len(h.api.comments) != 0 { t.Fatalf("park churned: pulls=%v notes=%v", h.adopt.pulls, h.api.comments) } @@ -91,7 +91,7 @@ func TestOrphanMarkerRestoresLostStoreForClosedAndMergedCopy(t *testing.T) { pr := adoptPR(7, "aaa", "stage/085-needs-decision", "needs-human", "author/clanker") pr.Comments = gh.Ptr(1) h.api.reset() - h.observe(pr, stageReasonDecisionRequested) + h.observe(pr, "label:needs-human") rec, _ := h.e.stageStoreOrShared().Get(stageKey("acme", "widget", 7)) if merged { if rec.SupersededBy != 90 || len(h.adopt.prEdits) != 1 { diff --git a/src/pkg/github/automerge/automerge_contributor_adopt.go b/src/pkg/github/automerge/automerge_contributor_adopt.go index d2fdc60a89..2bb771bd21 100644 --- a/src/pkg/github/automerge/automerge_contributor_adopt.go +++ b/src/pkg/github/automerge/automerge_contributor_adopt.go @@ -993,9 +993,16 @@ func (c *Engine) settleAdoption(ctx context.Context, store *stagelabels.Store, k // note + close; closed unmerged → recover or explicitly revert ownership. // This runs before stage derivation on every pass, including at 085. func (c *Engine) settleSuperseder(ctx context.Context, store *stagelabels.Store, key string, obs stageObservation, rec stagelabels.Record, policy StageLabelPolicy, now time.Time) (int, error) { - if obs.Merged || rec.AdoptedBy <= 0 { + if obs.Merged || rec.AdoptedBy <= 0 || rec.Superseded() { return 0, nil } + // Preserve the maintainer hand-back policy before settling a child, + // just as the 074 path does. Unknown permissions defer all mutation. + if maintainer, deferred := c.maintainerReleasesAdoption(ctx, obs, policy, now); deferred { + return 0, nil + } else if maintainer { + return c.releaseMaintainerAdoption(ctx, store, key, obs, rec.AdoptedBy) + } store.MarkAdoptChecked(key, now) sup, _, err := c.gh.PullRequests.Get(ctx, obs.Owner, obs.Repo, rec.AdoptedBy) if err != nil { From 00f95b2a4409b7e2622610300e380c0d6a03b0e6 Mon Sep 17 00:00:00 2001 From: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Wed, 28 Oct 2026 15:55:50 -0400 Subject: [PATCH 5/7] =?UTF-8?q?=F0=9F=90=9B=20fix:=20read=20adoption=20mar?= =?UTF-8?q?ker=20without=20a=20comment-count=20gate;=20defer=20orphan=20re?= =?UTF-8?q?-adoption=20on=20fence=20faults?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - restoreAdoptionMarker no longer waits for a deep-fetch comment count: it reads the marker once per record and again on head change (or a changed known count). The parked-085 path never learns the count, so the ClearAdoption'd original in #14947 was never recovered. - recoverOrphanedAdoption pre-checks adoptionDiffRefusal and returns without a public reversion on an error or deferring fence; a transient GitHub fault no longer posts hive:adoption-reverted and blocks the head. - buildStageTracker drops the live PullRequests.Get per adopted record; AdoptChildClosed comes from the persisted record only (#14952). Hive-Fix-Attempt: 1/6 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- src/pkg/dashboard/stage_tracker.go | 13 ++----- .../automerge/automerge_adoption_orphan.go | 36 +++++++++++++++---- .../automerge_adoption_orphan_test.go | 35 ++++++++++++++++++ src/pkg/stagelabels/store.go | 8 +++-- 4 files changed, 72 insertions(+), 20 deletions(-) diff --git a/src/pkg/dashboard/stage_tracker.go b/src/pkg/dashboard/stage_tracker.go index 898c625f66..ba2a928acd 100644 --- a/src/pkg/dashboard/stage_tracker.go +++ b/src/pkg/dashboard/stage_tracker.go @@ -1619,18 +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 - if rec.AdoptedBy > 0 && s.deps != nil && s.deps.GHClient != nil && s.deps.GHClient.GoGitHub() != nil { - owner, repo, ok := strings.Cut(it.Repo, "/") - if ok { - ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) - child, _, err := s.deps.GHClient.GoGitHub().PullRequests.Get(ctx, owner, repo, rec.AdoptedBy) - cancel() - if err == nil { - it.AdoptChildClosed = child.GetState() == "closed" && !child.GetMerged() - } - } - } it.SoakRemainingSeconds = int64(stageTrackerSoakRemaining(rec, now) / time.Second) } it.Hold = stageTrackerHoldFrom(rec, hasRec, labels) diff --git a/src/pkg/github/automerge/automerge_adoption_orphan.go b/src/pkg/github/automerge/automerge_adoption_orphan.go index 2129851921..498a3e6e69 100644 --- a/src/pkg/github/automerge/automerge_adoption_orphan.go +++ b/src/pkg/github/automerge/automerge_adoption_orphan.go @@ -6,6 +6,7 @@ import ( "time" gh "github.com/google/go-github/v72/github" + "github.com/hivecommons/hive/pkg/authorkind" hgithub "github.com/hivecommons/hive/pkg/github" "github.com/hivecommons/hive/pkg/stagelabels" ) @@ -15,23 +16,37 @@ const adoptionChildClosedTwice = "adoption-child-closed-twice" // Restore ownership from public evidence when an old sweep cleared the store. // A marker's head is retained even when the contributor subsequently pushed: // the merged-child path must still check whether it carried that new head. +// +// The marker is read once per record and again when the head moves or a +// known comment count changes. It is not gated on the comment count being +// known: only a lane's deep PullRequests.Get learns it (noteStagePR), and a +// PR parked at 085 may never take that path (hivecommons/hive#14947). func (c *Engine) restoreAdoptionMarker(ctx context.Context, store *stagelabels.Store, key string, obs stageObservation, now time.Time) error { rec, ok := store.Get(key) - if rec.AdoptedBy > 0 || rec.AdoptedInPlace() || !obs.Detail.CommentsKnown || obs.Detail.Comments == 0 || - (rec.AdoptMarkerChecked && rec.AdoptMarkerComments == obs.Detail.Comments) { + // Adoption is clanker-only: a human's PR never carried a marker. + if rec.AdoptedBy > 0 || rec.AdoptedInPlace() || obs.AuthorKind == authorkind.Human { return nil } - marker, err := hgithub.ReadSupersedeAdoption(ctx, c.gh, obs.Owner, obs.Repo, obs.Number, c.transport.IsHiveAuthorLogin) - if err != nil { - return err + if rec.AdoptMarkerChecked && rec.AdoptMarkerHead == obs.HeadSHA && + (!obs.Detail.CommentsKnown || rec.AdoptMarkerComments == obs.Detail.Comments) { + return nil } if !ok { store.Observe(key, stagelabels.None, "") } + if obs.Detail.CommentsKnown && obs.Detail.Comments == 0 { + // Nothing to list: a marker is a comment. + store.NoteAdoptionMarkerRead(key, obs.HeadSHA, 0) + return nil + } + marker, err := hgithub.ReadSupersedeAdoption(ctx, c.gh, obs.Owner, obs.Repo, obs.Number, c.transport.IsHiveAuthorLogin) + if err != nil { + return err + } if marker.By > 0 { store.MarkAdopted(key, marker.Head, marker.By, now) } - store.NoteAdoptionMarkerRead(key, obs.Detail.Comments) + store.NoteAdoptionMarkerRead(key, obs.HeadSHA, obs.Detail.Comments) return nil } @@ -49,6 +64,15 @@ func (c *Engine) recoverOrphanedAdoption(ctx context.Context, store *stagelabels if obs.HeadSHA != rec.AdoptedHead || !policy.Adoption || adoptionBlocked(obs.Labels) != "" { return c.revertOrphanedAdoption(ctx, store, key, obs, rec.AdoptedBy, "the contributor head changed, adoption is disabled, or a hold label prevents takeover") } + // supersedeAdoptedPR defers (no child, nil error) on an unreadable or + // deferring diff fence; that is a retry-next-sweep, not a failed copy. + // Check it here so a transient GitHub fault does not post a permanent + // public reversion. The retry guard above still allows the next attempt + // because AdoptOrphanPrevious stays equal to AdoptedBy. + if fence, err := c.adoptionDiffRefusal(ctx, obs); err != nil || adoptionFenceDefers(fence) { + c.info("stage labels: orphan re-adoption deferred before publishing", "repo", obs.Display, "pr", obs.Number, "head", obs.HeadSHA, "reason", fence, "error", err) + return 0, err + } store.NoteAdoptionOrphan(key, rec.AdoptedBy, now, true) retry, _ := store.Get(key) // All publishing fences and mutation gates remain in supersedeAdoptedPR. diff --git a/src/pkg/github/automerge/automerge_adoption_orphan_test.go b/src/pkg/github/automerge/automerge_adoption_orphan_test.go index d8725e55d0..1964763c57 100644 --- a/src/pkg/github/automerge/automerge_adoption_orphan_test.go +++ b/src/pkg/github/automerge/automerge_adoption_orphan_test.go @@ -103,3 +103,38 @@ func TestOrphanMarkerRestoresLostStoreForClosedAndMergedCopy(t *testing.T) { }) } } + +// A transient fence read fault (GitHub 5xx on the files list) while +// re-adopting an orphan is a retry-next-sweep, not a failed copy: no public +// reversion, no AdoptOrphanRevertedHead, and the next clean sweep re-adopts. +func TestOrphanDefersOnTransientFenceFaultWithoutReverting(t *testing.T) { + h, done := adoptThenLeave074(t) + defer done() + key := stageKey("acme", "widget", 7) + h.adopt.setSuperseder(90, "closed", false) + h.adopt.failPRFiles = true + h.api.reset() + pr := adoptPR(7, "aaa", "stage/085-needs-decision", "needs-human", "role/contributor", "author/clanker") + h.adopt.heads[7] = "aaa" + h.e.recordStage(stageLaneContributor, "acme/widget", "acme", "widget", pr, "label:needs-human", false, nil) + h.e.noteStageRole("acme", "widget", 7, stagelabels.RoleContributor) + if _, err := h.e.ApplyStageLabels(t.Context()); err == nil { + t.Fatal("transient files fault must surface so the sweep retries") + } + rec, _ := h.e.stageStoreOrShared().Get(key) + if rec.AdoptedBy != 90 || rec.AdoptOrphanRevertedHead != "" || !rec.AdoptChildClosed || len(h.adopt.pulls) != 1 { + t.Fatalf("transient fault reverted the adoption: %+v pulls=%v", rec, h.adopt.pulls) + } + for _, note := range h.api.comments { + if strings.HasPrefix(note, "") { + t.Fatalf("public reversion posted on a transient fault: %q", note) + } + } + h.adopt.failPRFiles = false + h.api.reset() + h.observe(pr, "label:needs-human") + rec, _ = h.e.stageStoreOrShared().Get(key) + if rec.AdoptedBy != 91 || len(h.adopt.pulls) != 2 { + t.Fatalf("deferred orphan not re-adopted on the next sweep: %+v pulls=%v", rec, h.adopt.pulls) + } +} diff --git a/src/pkg/stagelabels/store.go b/src/pkg/stagelabels/store.go index 0a2f4352fa..bc39dc24a9 100644 --- a/src/pkg/stagelabels/store.go +++ b/src/pkg/stagelabels/store.go @@ -171,6 +171,7 @@ type Record struct { AdoptChildClosed bool `json:"adopt_child_closed,omitempty"` AdoptMarkerComments int `json:"adopt_marker_comments,omitempty"` AdoptMarkerChecked bool `json:"adopt_marker_checked,omitempty"` + AdoptMarkerHead string `json:"adopt_marker_head,omitempty"` // AdoptEscalatedHead / AdoptEscalatedReason record that the adoption // sits at this head past the 074 dwell with nothing the hive can push // and is a person's (stage 085) for that lane reason. The escalation @@ -1270,15 +1271,16 @@ func (s *Store) RevertOrphanAdoption(key, head string) { s.items[key], s.dirty = r, true } -// NoteAdoptionMarkerRead avoids re-listing unchanged comment history. -func (s *Store) NoteAdoptionMarkerRead(key string, comments int) { +// NoteAdoptionMarkerRead records that the ownership marker was read at this +// head so unchanged comment history is not re-listed every pass. +func (s *Store) NoteAdoptionMarkerRead(key, head string, comments int) { s.mu.Lock() defer s.mu.Unlock() r, ok := s.items[key] if !ok { return } - r.AdoptMarkerChecked, r.AdoptMarkerComments = true, comments + r.AdoptMarkerChecked, r.AdoptMarkerHead, r.AdoptMarkerComments = true, head, comments s.items[key], s.dirty = r, true } From 7aafaef6a1ff4dbdea5ca090bec162465d8e5d6b Mon Sep 17 00:00:00 2001 From: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Wed, 28 Oct 2026 17:06:43 -0400 Subject: [PATCH 6/7] =?UTF-8?q?=F0=9F=90=9B=20fix:=20reset=20the=20adoptio?= =?UTF-8?q?n=20marker=20cache=20on=20ClearAdoption;=20ignore=20a=20release?= =?UTF-8?q?d=20child's=20marker?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ClearAdoption left AdoptMarkerChecked/AdoptMarkerHead set, so with the contributor head unchanged and the comment count unknown (no deep Get at 085) restoreAdoptionMarker returned early forever and a lost-store orphan was never re-read. Resetting the cache alone would let RevertOrphanAdoption (and the maintainer hand-back) loop: the stale hive:adopted marker naming the closed child is still on the PR. Record the released superseder (AdoptMarkerReleasedBy) and skip MarkAdopted for a marker that names it. Hive-Fix-Attempt: 2/6 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- .../automerge/automerge_adoption_orphan.go | 7 ++- .../automerge_adoption_orphan_test.go | 44 +++++++++++++++++++ .../automerge/automerge_contributor_adopt.go | 3 ++ src/pkg/stagelabels/adoption_orphan_test.go | 29 +++++++++++- src/pkg/stagelabels/store.go | 31 ++++++++++++- 5 files changed, 108 insertions(+), 6 deletions(-) diff --git a/src/pkg/github/automerge/automerge_adoption_orphan.go b/src/pkg/github/automerge/automerge_adoption_orphan.go index 498a3e6e69..5c28a10865 100644 --- a/src/pkg/github/automerge/automerge_adoption_orphan.go +++ b/src/pkg/github/automerge/automerge_adoption_orphan.go @@ -43,7 +43,10 @@ func (c *Engine) restoreAdoptionMarker(ctx context.Context, store *stagelabels.S if err != nil { return err } - if marker.By > 0 { + // A marker naming a child this hive already released (reverted orphan, + // maintainer hand-back) is stale evidence: re-adopting it would loop + // revert → re-read → revert on every pass. + if marker.By > 0 && marker.By != rec.AdoptMarkerReleasedBy { store.MarkAdopted(key, marker.Head, marker.By, now) } store.NoteAdoptionMarkerRead(key, obs.HeadSHA, obs.Detail.Comments) @@ -95,6 +98,6 @@ func (c *Engine) revertOrphanedAdoption(ctx context.Context, store *stagelabels. return 0, err } rec, _ := store.Get(key) - store.RevertOrphanAdoption(key, nonEmpty(rec.AdoptedHead, obs.HeadSHA)) + store.RevertOrphanAdoption(key, nonEmpty(rec.AdoptedHead, obs.HeadSHA), previous) return 1, nil } diff --git a/src/pkg/github/automerge/automerge_adoption_orphan_test.go b/src/pkg/github/automerge/automerge_adoption_orphan_test.go index 1964763c57..a6356f4762 100644 --- a/src/pkg/github/automerge/automerge_adoption_orphan_test.go +++ b/src/pkg/github/automerge/automerge_adoption_orphan_test.go @@ -104,6 +104,50 @@ func TestOrphanMarkerRestoresLostStoreForClosedAndMergedCopy(t *testing.T) { } } +// After a reversion the stale `hive:adopted … superseded_by=90` marker is +// still on the PR (and a listing may lag the reversion note). Resetting the +// marker cache on ClearAdoption must not turn that into a revert → re-read → +// MarkAdopted → revert loop: a marker naming the released child is ignored. +func TestOrphanRevertDoesNotReadoptFromStaleMarker(t *testing.T) { + h, done := adoptThenLeave074(t) + defer done() + key := stageKey("acme", "widget", 7) + h.adopt.setSuperseder(90, "closed", false) + prior := h.api.extra + h.api.extra = func(w http.ResponseWriter, r *http.Request) bool { + if r.Method == http.MethodGet && r.URL.Path == "/repos/acme/widget/issues/7/comments" { + _ = json.NewEncoder(w).Encode([]any{map[string]any{"body": "", "user": map[string]string{"login": testHiveAppBotLogin}}}) + return true + } + return prior(w, r) + } + pr := adoptPR(7, "bbb", "stage/074-adopted-by-hive", "author/clanker") + pr.Comments = gh.Ptr(1) + h.api.reset() + h.observe(pr, "check-failing:unit") + rec, _ := h.e.stageStoreOrShared().Get(key) + if rec.AdoptedBy != 0 || rec.AdoptMarkerReleasedBy != 90 || rec.AdoptMarkerChecked { + t.Fatalf("orphan not reverted with released marker: %+v", rec) + } + for i := 0; i < 3; i++ { + h.clock.advance(time.Minute) + h.observe(pr, "check-failing:unit") + } + rec, _ = h.e.stageStoreOrShared().Get(key) + if rec.AdoptedBy != 0 || len(h.adopt.pulls) != 1 { + t.Fatalf("stale marker re-adopted after reversion: %+v pulls=%v", rec, h.adopt.pulls) + } + reverted := 0 + for _, note := range h.api.comments { + if strings.HasPrefix(note, "") { + reverted++ + } + } + if reverted != 1 { + t.Fatalf("reversion note posted %d times: %v", reverted, h.api.comments) + } +} + // A transient fence read fault (GitHub 5xx on the files list) while // re-adopting an orphan is a retry-next-sweep, not a failed copy: no public // reversion, no AdoptOrphanRevertedHead, and the next clean sweep re-adopts. diff --git a/src/pkg/github/automerge/automerge_contributor_adopt.go b/src/pkg/github/automerge/automerge_contributor_adopt.go index 2bb771bd21..760790c53a 100644 --- a/src/pkg/github/automerge/automerge_contributor_adopt.go +++ b/src/pkg/github/automerge/automerge_contributor_adopt.go @@ -1205,6 +1205,9 @@ func (c *Engine) releaseMaintainerAdoption(ctx context.Context, store *stagelabe } } store.ClearAdoption(key) + // The hive:adopted marker stays on the maintainer's PR; without this + // the marker re-read would re-adopt and hand back again every pass. + store.NoteAdoptionMarkerReleased(key, superseding) return comments, nil } diff --git a/src/pkg/stagelabels/adoption_orphan_test.go b/src/pkg/stagelabels/adoption_orphan_test.go index 8b890518fb..bea9035546 100644 --- a/src/pkg/stagelabels/adoption_orphan_test.go +++ b/src/pkg/stagelabels/adoption_orphan_test.go @@ -14,7 +14,7 @@ func TestOrphanRetryGuardSurvivesReversionAndReload(t *testing.T) { store.Observe(key, AdoptedByHive, "adopted") store.MarkAdopted(key, "aaa", 90, now) store.NoteAdoptionOrphan(key, 90, now, true) - store.RevertOrphanAdoption(key, "aaa") + store.RevertOrphanAdoption(key, "aaa", 90) if err := store.Save(); err != nil { t.Fatal(err) } @@ -23,7 +23,32 @@ func TestOrphanRetryGuardSurvivesReversionAndReload(t *testing.T) { t.Fatal(err) } rec, ok := reloaded.Get(key) - if !ok || rec.AdoptedBy != 0 || rec.AdoptOrphanPrevious != 90 || !rec.AdoptOrphanRetriedAt.Equal(now) || rec.AdoptOrphanRevertedHead != "aaa" { + if !ok || rec.AdoptedBy != 0 || rec.AdoptOrphanPrevious != 90 || !rec.AdoptOrphanRetriedAt.Equal(now) || rec.AdoptOrphanRevertedHead != "aaa" || rec.AdoptMarkerReleasedBy != 90 { t.Fatalf("lost orphan retry guard: %+v", rec) } } + +// ClearAdoption must drop the marker-read cache: with nothing on record the +// public marker is the only evidence left and a lost-store orphan would +// otherwise never be re-read while the head and comment count hold still. +func TestClearAdoptionResetsMarkerReadCache(t *testing.T) { + now := time.Now().UTC() + store := NewStore(filepath.Join(t.TempDir(), "stages.json"), func() time.Time { return now }) + key := Key("o/r", 7) + store.Observe(key, AdoptedByHive, "adopted") + store.MarkAdopted(key, "aaa", 90, now) + store.NoteAdoptionMarkerRead(key, "aaa", 3) + store.ClearAdoption(key) + rec, _ := store.Get(key) + if rec.AdoptMarkerChecked || rec.AdoptMarkerHead != "" || rec.AdoptMarkerComments != 0 { + t.Fatalf("marker cache survived ClearAdoption: %+v", rec) + } + if rec.AdoptMarkerReleasedBy != 0 { + t.Fatalf("plain ClearAdoption must not mark the marker released: %+v", rec) + } + store.NoteAdoptionMarkerReleased(key, 90) + rec, _ = store.Get(key) + if rec.AdoptMarkerReleasedBy != 90 { + t.Fatalf("released superseder not recorded: %+v", rec) + } +} diff --git a/src/pkg/stagelabels/store.go b/src/pkg/stagelabels/store.go index bc39dc24a9..e04b3e8357 100644 --- a/src/pkg/stagelabels/store.go +++ b/src/pkg/stagelabels/store.go @@ -172,6 +172,10 @@ type Record struct { AdoptMarkerComments int `json:"adopt_marker_comments,omitempty"` AdoptMarkerChecked bool `json:"adopt_marker_checked,omitempty"` AdoptMarkerHead string `json:"adopt_marker_head,omitempty"` + // AdoptMarkerReleasedBy is the superseder whose adoption this hive + // explicitly released (reverted orphan, maintainer hand-back). Its + // stale hive:adopted marker on the PR must not re-adopt on a re-read. + AdoptMarkerReleasedBy int `json:"adopt_marker_released_by,omitempty"` // AdoptEscalatedHead / AdoptEscalatedReason record that the adoption // sits at this head past the 074 dwell with nothing the hive can push // and is a person's (stage 085) for that lane reason. The escalation @@ -1258,8 +1262,9 @@ func (s *Store) NoteAdoptionOrphan(key string, previous int, now time.Time, retr // RevertOrphanAdoption releases ownership without automatically re-trying // the same failed takeover on the next stage pass. An explicit request or -// a new contributor head can still start a new adoption. -func (s *Store) RevertOrphanAdoption(key, head string) { +// a new contributor head can still start a new adoption. The reverted +// child's marker is remembered so a marker re-read does not re-adopt it. +func (s *Store) RevertOrphanAdoption(key, head string, previous int) { s.ClearAdoption(key) s.mu.Lock() defer s.mu.Unlock() @@ -1268,6 +1273,23 @@ func (s *Store) RevertOrphanAdoption(key, head string) { return } r.AdoptOrphanRevertedHead = head + if previous > 0 { + r.AdoptMarkerReleasedBy = previous + } + s.items[key], s.dirty = r, true +} + +// NoteAdoptionMarkerReleased records that the hive gave up superseder `by` +// on purpose: its hive:adopted marker still on the PR is no longer evidence +// of ownership and restoreAdoptionMarker must ignore it. +func (s *Store) NoteAdoptionMarkerReleased(key string, by int) { + s.mu.Lock() + defer s.mu.Unlock() + r, ok := s.items[key] + if !ok || by <= 0 { + return + } + r.AdoptMarkerReleasedBy = by s.items[key], s.dirty = r, true } @@ -1285,6 +1307,10 @@ func (s *Store) NoteAdoptionMarkerRead(key, head string, comments int) { } // ClearAdoption forgets the adoption, preserving the orphan retry guard. +// The marker-read cache is reset too: with no adoption on record the +// public hive:adopted marker is the only ownership evidence left, and a +// lost-store orphan must be re-read on the next pass even when the +// contributor head and comment count have not moved. func (s *Store) ClearAdoption(key string) { s.mu.Lock() defer s.mu.Unlock() @@ -1297,6 +1323,7 @@ func (s *Store) ClearAdoption(key string) { r.AdoptedHeadAt, r.AdoptEscalatedHead, r.AdoptEscalatedReason, r.AdoptEscalationNotedHead = time.Time{}, "", "", "" r.AdoptRecoveryAttempt, r.AdoptRecoveryCount = "", 0 r.AdoptChildClosed = false + r.AdoptMarkerChecked, r.AdoptMarkerHead, r.AdoptMarkerComments = false, "", 0 r.SupersededBy, r.SupersededAt, r.SupersededOpen, r.SupersederMergedNotedHead = 0, time.Time{}, false, "" s.items[key] = r s.dirty = true From 3c6bdc656e0ed4b76eefa8b5eec1153dbc361e8a Mon Sep 17 00:00:00 2001 From: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Wed, 28 Oct 2026 17:27:28 -0400 Subject: [PATCH 7/7] =?UTF-8?q?=F0=9F=93=9D=20docs:=20describe=20orphaned?= =?UTF-8?q?=20supersede=20adoption=20recovery,=20reversion=20and=20loop=20?= =?UTF-8?q?guard?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit labels-and-control-signals.md still said a closed-unmerged superseder forgets the adoption and returns the PR to 072. Document the behaviour this PR introduces instead: re-adoption on hive/adopt--retry-, the note when the head moved or the copy could not be opened, and the 085 park with reason adoption-child-closed-twice when a retry copy is closed again. Hive-Fix-Attempt: 3/6 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- src/docs/labels-and-control-signals.md | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/docs/labels-and-control-signals.md b/src/docs/labels-and-control-signals.md index b257624457..d0c2213f4e 100644 --- a/src/docs/labels-and-control-signals.md +++ b/src/docs/labels-and-control-signals.md @@ -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-` push is not retried on the next sweep. While in 074 the hive polls the superseder at most every 10 minutes: merged → one `` 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--retry-` copy (`` 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 `` 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 + `` 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