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/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 diff --git a/src/pkg/dashboard/adoption_orphan_test.go b/src/pkg/dashboard/adoption_orphan_test.go new file mode 100644 index 0000000000..1a5f3f700f --- /dev/null +++ b/src/pkg/dashboard/adoption_orphan_test.go @@ -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"), + "", + } + 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) + } +} 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..70111605c7 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") { @@ -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")): @@ -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"): diff --git a/src/pkg/dashboard/stage_tracker.go b/src/pkg/dashboard/stage_tracker.go index c3d87fdd34..ba2a928acd 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,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) @@ -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 { 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..a6086fbd80 --- /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.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, "") || 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..5c28a10865 --- /dev/null +++ b/src/pkg/github/automerge/automerge_adoption_orphan.go @@ -0,0 +1,103 @@ +package automerge + +import ( + "context" + "fmt" + "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" +) + +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) + // Adoption is clanker-only: a human's PR never carried a marker. + if rec.AdoptedBy > 0 || rec.AdoptedInPlace() || obs.AuthorKind == authorkind.Human { + return nil + } + 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 + } + // 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) + 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") + } + // 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. + 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), 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 new file mode 100644 index 0000000000..a6356f4762 --- /dev/null +++ b/src/pkg/github/automerge/automerge_adoption_orphan_test.go @@ -0,0 +1,184 @@ +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...), "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) + } + // 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...), "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...), "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) + } +} + +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, "label:needs-human") + 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) + } + }) + } +} + +// 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. +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/github/automerge/automerge_contributor_adopt.go b/src/pkg/github/automerge/automerge_contributor_adopt.go index c01af38c99..760790c53a 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,22 +983,25 @@ 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 || 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) @@ -1004,8 +1013,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 } @@ -1194,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 } @@ -1547,6 +1561,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/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 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..bea9035546 --- /dev/null +++ b/src/pkg/stagelabels/adoption_orphan_test.go @@ -0,0 +1,54 @@ +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", 90) + 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" || 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 412ec1be16..e04b3e8357 100644 --- a/src/pkg/stagelabels/store.go +++ b/src/pkg/stagelabels/store.go @@ -163,6 +163,19 @@ 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"` + 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 @@ -1076,6 +1089,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 +1245,72 @@ 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. 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() + r, ok := s.items[key] + if !ok { + 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 +} + +// 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.AdoptMarkerHead, r.AdoptMarkerComments = true, head, comments + s.items[key], s.dirty = r, true +} + +// 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() @@ -1243,6 +1322,8 @@ 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.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