diff --git a/changelog.d/changed-writeback-gate-close-first.md b/changelog.d/changed-writeback-gate-close-first.md new file mode 100644 index 0000000000..39f3fb81d0 --- /dev/null +++ b/changelog.d/changed-writeback-gate-close-first.md @@ -0,0 +1 @@ +- Adoption close-first now asks the write-back gate before it closes, labels or reopens a contributor's original PR ([#15272](https://github.com/hivecommons/hive/issues/15272)). These writes land on a PR the hive did not author, but they were only counted in the direct-write ratchet baseline, so they ignored a repo pause, the per-repo mode and the `contributor_adopt` kind policy (default L6 + opt-in label). When the gate refuses, the original stays open and closes when the hive's copy merges, and the refusal shows up in the write-back drill-down. A reopen that is due waits for the next poll, for example until an operator lifts a pause; a refusal for any other reason (the kind policy changed after the hive closed the PR) is logged at warn, because it leaves a hive-closed PR shut until a person reopens it. The ratchet baseline drops `automerge_adoption_close_first.go` (7 → 0). diff --git a/src/docs/labels-and-control-signals.md b/src/docs/labels-and-control-signals.md index 50660e6805..4fc433d67b 100644 --- a/src/docs/labels-and-control-signals.md +++ b/src/docs/labels-and-control-signals.md @@ -1147,7 +1147,13 @@ When a clanker-authored contributor PR goes red the hive does not just relabel i copy exists: the stage record is superseded (no row, no chevron, no needs-human) and the copy is the one PR for the issue. A close GitHub refuses (403/404) leaves the original open with the note, superseded - all the same. `close_first: false` restores the keep-open behaviour + all the same. The note, label and close are unsolicited writes on a + contributor's PR, so the pass first asks the write-back gate as kind + `contributor_adopt` (default L6 + opt-in label; see the write-back + table in + [operator-reference.md](operator-reference.md#what-hive-writes-to-github-and-when)): + refused, nothing is written and the original stays open on the + keep-open path below until the copy merges. `close_first: false` restores the keep-open behaviour below: the note has no `close_first` field, the original moves to `stage/074-adopted-by-hive` (its linked issue mirrors the stage) and closes only when the copy merges. The hub drops the PR from the @@ -1166,7 +1172,12 @@ When a clanker-authored contributor PR goes red the hive does not just relabel i `adoption/supersede` request re-runs the takeover from the same head). **Ping-pong guard:** one reopen per original per 24h — a second failed copy inside the window leaves the original closed with a `held=true` - note saying so. The orphan recovery below never runs for a close-first + note saying so. The reopen, its note and the label removal also go + through the `contributor_adopt` write-back gate: refused, nothing is + written and the record stays due its next poll, so a lifted repo pause + lands the reopen; a policy change after the close is warned in the log + and leaves the hive-closed original shut until a person reopens it. + The orphan recovery below never runs for a close-first original (its copy being closed is a failure, not an orphan); the `hive:adoption-copy-failed` note is a settled marker, so the marker scan never re-adopts a reopened original on its own. diff --git a/src/docs/operator-reference.md b/src/docs/operator-reference.md index 56c904e1e3..da819baede 100644 --- a/src/docs/operator-reference.md +++ b/src/docs/operator-reference.md @@ -775,7 +775,14 @@ labelled `hive/superseded`, so one issue never shows two active PRs hivecommons/hive#15135). If the copy is closed unmerged or its required checks are red at two heads, the hive reopens the original, removes `hive/superseded`, and parks it at `stage/085` with `adoption-copy-failed` -("needs a person"); at most one reopen per original per 24h. `close_first: +("needs a person"); at most one reopen per original per 24h. The note, +label, close and reopen are unsolicited writes on a contributor's PR, so each +first asks the write-back gate as kind `contributor_adopt` (L6 + opt-in label +by default; see [the write-back table](#what-hive-writes-to-github-and-when)): +refused, the original is not closed and stays open on the keep-open path +until the copy merges, and a due reopen waits for the next poll (a pause +lifting lands it; a policy change after the close is warned in the log and +leaves the PR closed until a person reopens it). `close_first: false` keeps the earlier behaviour: the original moves to 074 and closes only once the superseder merges. Whether that rework reaches each agent is visible per row on Operations → Connected contributor agents: the relay's parallel capacity @@ -960,6 +967,7 @@ that level, the power the write-back exists to govern? | PR↔issue linker (`pr_issue_link.go`, `pr_contributor_link.go`, `linked_prs.go`) | PR watcher | "covered by PR" label on the issue, link comments | issues referenced by any PR | `covered_by_pr_label` → L5 + label | | Verdict / decision labels (`pr_decision_operator.go`, `human_decision_label.go`, `legacy_decision_labels.go`, `contribute_verdict_settle.go`) | review verdicts, dashboard decisions | `hive:verdict-*`, decision labels | reviewed PRs | `verdict_label` → L3 + label; dashboard-triggered decisions are solicited | | Contributor adopt / nudge / bot takeover (`automerge/automerge_contributor_*.go`, `automerge_bot_takeover.go`) | auto-merge sweep | adopt comment, update-branch push, workflow approval, nudge comments | contributor PRs in the contributor lane | `contributor_adopt` → L6 + label | +| Adoption close-first (`automerge/automerge_adoption_close_first.go`) | auto-merge sweep, when a supersede adoption opens the hive's copy; close-first poll | close-first note, `hive/superseded` label and close on the original; reopen, copy-failed note and label removal when the copy fails | the contributor's original PR | `contributor_adopt` → L6 + label; refused: the original stays open until the copy merges, and a due reopen waits for the next poll | | Claims (`prclaims.go`, `claimed_by_label.go`, `cmd/hive/claimswire.go`, `claimescalation.go`) | claim ledger changes | `claimed-by:*` labels, claim/escalation comments | claimed issues | `claim_comment` → L4 + label (hive-claimed issues are own items) | | Issue close / task-list / decomposed parents (`issue_close.go`, `task_list_sweep.go`, `decomposed_parents.go`, `close_on_merge.go`, `tracking_issue.go`) | merges, sweeps | close, body edits (checkbox ticks), `Refs` rewrites | issues linked from hive PRs | `issue_close`, `parent_issue_edit` → L5 + label; hive-filed issues are own items | | Gate comments (`pkg/scheduler/clarity_gate.go`, `prior_art_gate.go`, `triage.go`, `issue_blocked.go`, `issue_recheck_soak.go`) | scheduler intake | clarity/prior-art/triage questions, `blocked` labels | issues admitted by the issue filter | `gate_comment` → L5 + label; items carrying the intake label are opted in | diff --git a/src/pkg/github/automerge/automerge_adoption_close_first.go b/src/pkg/github/automerge/automerge_adoption_close_first.go index 0271d6ed86..2acb643cb5 100644 --- a/src/pkg/github/automerge/automerge_adoption_close_first.go +++ b/src/pkg/github/automerge/automerge_adoption_close_first.go @@ -12,6 +12,7 @@ import ( gh "github.com/google/go-github/v72/github" hgithub "github.com/hivecommons/hive/pkg/github" "github.com/hivecommons/hive/pkg/stagelabels" + "github.com/hivecommons/hive/pkg/writeback" ) // Close-first supersession (hivecommons/hive#15135). @@ -33,6 +34,13 @@ import ( // stagelabels.LaneReasonAdoptionCopyFailed. One reopen per original per // stagelabels.AdoptionReopenWindow: a copy that keeps failing after that // leaves the original closed with a note rather than flipping it. +// +// Closing, labelling and reopening a contributor's original are unsolicited +// writes on a PR the hive did not author, so every one asks the write-back +// gate (writeback.KindContributorAdopt) first. A refused close-first leaves +// the original open on the keep-open path; a refused reopen leaves the +// record due its next poll, so the reopen lands once the gate allows it +// (e.g. when an operator lifts a repo pause). // AdoptionCopyFailedMarker opens the note posted when the hive reopens (or, // past the reopen guard, declines to reopen) a close-first original. @@ -110,18 +118,23 @@ func AdoptionCopyFailedHeldComment(copy int, head, why string, redHeads int, reo // A close GitHub refuses leaves the original open with the note (as the // merge-time close does); any other close failure leaves the record on // the keep-open path, where settleSuperseder closes it when the copy merges. +// A write-back gate refusal writes nothing and leaves it on that path too. func (c *Engine) closeSupersededOriginalFirst(ctx context.Context, store *stagelabels.Store, key string, obs stageObservation, policy StageLabelPolicy, superseding int, reason, fence string, now time.Time) (int, error) { owner, repo, number := obs.Owner, obs.Repo, obs.Number logArgs := []any{"repo", obs.Display, "pr", number, "head", obs.HeadSHA, "superseded_by", superseding, "reason", reason} body := AdoptionCloseFirstComment(obs, policy.HiveID, superseding, reason) + adoptionFenceNote(fence) - if _, _, err := c.gh.Issues.CreateComment(ctx, owner, repo, number, &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { + if d := c.writebackAllowed(obs.Display, writebackItemForObservation(obs), writeback.KindContributorAdopt, body); !d.Allowed { + c.info("stage labels: close-first adoption suppressed by the write-back gate; original left open on the keep-open path", append(logArgs, "writeback_reason", d.Reason, "writeback_detail", d.Detail)...) + return 0, nil + } + if _, _, err := c.gh.Issues.CreateComment(ctx, owner, repo, number, &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { // writeback:gated c.warn("stage labels: close-first adoption note failed; original left open on the keep-open path", append(logArgs, "error", err)...) return 0, err } - if _, _, err := c.gh.Issues.AddLabelsToIssue(ctx, owner, repo, number, []string{hgithub.SupersededLabel}); err != nil { + if _, _, err := c.gh.Issues.AddLabelsToIssue(ctx, owner, repo, number, []string{hgithub.SupersededLabel}); err != nil { // writeback:gated c.warn("stage labels: close-first adoption label failed", append(logArgs, "label", hgithub.SupersededLabel, "error", err)...) } - if _, _, err := c.gh.PullRequests.Edit(ctx, owner, repo, number, &gh.PullRequest{State: gh.Ptr("closed")}); err != nil { + if _, _, err := c.gh.PullRequests.Edit(ctx, owner, repo, number, &gh.PullRequest{State: gh.Ptr("closed")}); err != nil { // writeback:gated if isGitHubStatus(err, http.StatusForbidden) || isGitHubStatus(err, http.StatusNotFound) { store.MarkSupersededClosedFirst(key, superseding, true, now) c.warn("stage labels: cannot close superseded original (permission); left open with the note", append(logArgs, "error", err)...) @@ -242,22 +255,42 @@ func (c *Engine) settleCloseFirstCopy(ctx context.Context, store *stagelabels.St // reopenSupersededOriginal gives a close-first original back to a person: // reopen, one note, `hive/superseded` off, parked at 085 with // LaneReasonAdoptionCopyFailed. Within stagelabels.AdoptionReopenWindow of -// the last reopen the original stays closed and the note says so. +// the last reopen the original stays closed and the note says so. A +// write-back gate refusal writes nothing and settles nothing: the record +// stays due its next poll. A pause is logged at info (it lifts); any other +// refusal means the policy moved under a PR the hive closed, and is warned. func (c *Engine) reopenSupersededOriginal(ctx context.Context, store *stagelabels.Store, cand closeFirstRecord, why string, redHeads int, now time.Time) (int, error) { rec, copy := cand.rec, cand.rec.AdoptedBy owner, repo, number := cand.owner, cand.repo, cand.number logArgs := []any{"repo", owner + "/" + repo, "pr", number, "head", rec.AdoptedHead, "superseded_by", copy, "why", why, "red_heads", redHeads} - if rec.AdoptionReopenedWithin(now, stagelabels.AdoptionReopenWindow) { + held := rec.AdoptionReopenedWithin(now, stagelabels.AdoptionReopenWindow) + preview := AdoptionCopyFailedComment(number, copy, rec.AdoptedHead, why, redHeads) + if held { + preview = AdoptionCopyFailedHeldComment(copy, rec.AdoptedHead, why, redHeads, rec.AdoptReopenedAt, now) + } + if d := c.writebackAllowed(owner+"/"+repo, c.closeFirstOriginalItem(ctx, cand), writeback.KindContributorAdopt, preview); !d.Allowed { + gateArgs := append(logArgs, "writeback_reason", d.Reason, "writeback_detail", d.Detail) + if d.Reason == writeback.ReasonRepoPaused { + c.info("stage labels: close-first original reopen suppressed by the write-back gate; retried at the next poll", gateArgs...) + return 0, nil + } + // Not a pause: the contributor_adopt policy changed after the hive + // closed this PR, so the reopen that would undo that close no + // longer clears the gate. The PR stays closed until the policy + // allows it again or a person reopens it; say so loudly. + c.warn("stage labels: close-first original reopen refused by the write-back gate; hive-closed PR stays closed until the contributor_adopt policy allows the reopen or a person reopens it", gateArgs...) + return 0, nil + } + if held { store.MarkCloseFirstSettled(cand.key) c.warn("stage labels: close-first copy failed again within the reopen window; original stays closed", append(logArgs, "reopened_at", rec.AdoptReopenedAt)...) - body := AdoptionCopyFailedHeldComment(copy, rec.AdoptedHead, why, redHeads, rec.AdoptReopenedAt, now) - if _, _, err := c.gh.Issues.CreateComment(ctx, owner, repo, number, &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { + if _, _, err := c.gh.Issues.CreateComment(ctx, owner, repo, number, &gh.IssueComment{Body: gh.Ptr(preview)}); err != nil { // writeback:gated c.warn("stage labels: close-first held note failed", append(logArgs, "error", err)...) return 0, err } return 1, nil } - if _, _, err := c.gh.PullRequests.Edit(ctx, owner, repo, number, &gh.PullRequest{State: gh.Ptr("open")}); err != nil { + if _, _, err := c.gh.PullRequests.Edit(ctx, owner, repo, number, &gh.PullRequest{State: gh.Ptr("open")}); err != nil { // writeback:gated c.warn("stage labels: reopening superseded original failed", append(logArgs, "error", err)...) return 0, err } @@ -268,14 +301,13 @@ func (c *Engine) reopenSupersededOriginal(ctx context.Context, store *stagelabel c.warn("stage labels: hive's copy failed; original reopened for a person", logArgs...) comments := 0 var firstErr error - body := AdoptionCopyFailedComment(number, copy, rec.AdoptedHead, why, redHeads) - if _, _, err := c.gh.Issues.CreateComment(ctx, owner, repo, number, &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { + if _, _, err := c.gh.Issues.CreateComment(ctx, owner, repo, number, &gh.IssueComment{Body: gh.Ptr(preview)}); err != nil { // writeback:gated c.warn("stage labels: reopen note failed", append(logArgs, "error", err)...) firstErr = err } else { comments++ } - if _, err := c.gh.Issues.RemoveLabelForIssue(ctx, owner, repo, number, url.PathEscape(hgithub.SupersededLabel)); err != nil && !isGitHubStatus(err, http.StatusNotFound) { + if _, err := c.gh.Issues.RemoveLabelForIssue(ctx, owner, repo, number, url.PathEscape(hgithub.SupersededLabel)); err != nil && !isGitHubStatus(err, http.StatusNotFound) { // writeback:gated c.warn("stage labels: removing superseded label failed", append(logArgs, "label", hgithub.SupersededLabel, "error", err)...) if firstErr == nil { firstErr = err @@ -283,3 +315,25 @@ func (c *Engine) reopenSupersededOriginal(ctx context.Context, store *stagelabel } return comments, firstErr } + +// closeFirstOriginalItem is the gate's view of a closed original. No lane +// lists a closed PR, so with a gate installed it is read once here (the +// labels decide the opt-in); without one, or when the read fails, the bare +// number stands in, which the gate treats as carrying no opt-in label. +func (c *Engine) closeFirstOriginalItem(ctx context.Context, cand closeFirstRecord) writeback.Item { + item := writeback.Item{Number: cand.number, IsPR: true} + if c.writebackGate() == nil { + return item + } + pr, _, err := c.gh.PullRequests.Get(ctx, cand.owner, cand.repo, cand.number) + if err != nil || pr == nil { + c.warn("stage labels: close-first original lookup for the write-back gate failed", "repo", cand.owner+"/"+cand.repo, "pr", cand.number, "error", err) + return item + } + item.Author = pr.GetUser().GetLogin() + for _, l := range pr.Labels { + item.Labels = append(item.Labels, l.GetName()) + } + item.CreatedAt = pr.GetCreatedAt().Time + return item +} diff --git a/src/pkg/github/automerge/automerge_adoption_close_first_test.go b/src/pkg/github/automerge/automerge_adoption_close_first_test.go index a672af8275..723a5f44db 100644 --- a/src/pkg/github/automerge/automerge_adoption_close_first_test.go +++ b/src/pkg/github/automerge/automerge_adoption_close_first_test.go @@ -1,7 +1,9 @@ package automerge import ( + "bytes" "context" + "log/slog" "net/http" "strings" "testing" @@ -10,6 +12,7 @@ import ( "github.com/hivecommons/hive/pkg/delegatedecision" hgithub "github.com/hivecommons/hive/pkg/github" "github.com/hivecommons/hive/pkg/stagelabels" + "github.com/hivecommons/hive/pkg/writeback" ) // Close-first supersession (hivecommons/hive#15135): the original closes as @@ -332,6 +335,178 @@ func TestAdoptionCloseFirstReopenPingPongGuard(t *testing.T) { } } +// closeFirstGateState is what a test flips on the write-back gate it +// installs: the contributor_adopt kind refused (own-only) and an operator +// repo pause. +type closeFirstGateState struct { + adoptOff bool + paused bool +} + +// installWritebackGate puts a write-back gate on the harness's client at +// L6 with stage labels allowed unlabelled, so only the adoption kind (and +// the pause) decide. +func (h *closeFirstHarness) installWritebackGate(st *closeFirstGateState) *writeback.Gate { + h.t.Helper() + gate := writeback.New(writeback.Config{}, writeback.Deps{ + LevelFor: func(string) int { return 6 }, + RepoListed: func(string) bool { return true }, + RepoPause: func(string) (writeback.RepoPauseInfo, bool) { + return writeback.RepoPauseInfo{By: "ops", Reason: "freeze"}, st.paused + }, + Config: func() writeback.Config { + one, no, yes, ownOnly := 1, false, true, st.adoptOff + return writeback.Config{ + Unsolicited: writeback.UnsolicitedConfig{Backfill: &yes}, + Kinds: map[string]writeback.KindPolicyOverride{ + string(writeback.KindStageLabel): {MinLevel: &one, RequireLabel: &no}, + string(writeback.KindContributorAdopt): {MinLevel: &one, RequireLabel: &no, OwnOnly: &ownOnly}, + }, + } + }, + Now: h.clock.now, + }, "") + client, ok := h.e.transport.(*hgithub.Client) + if !ok { + h.t.Fatalf("transport %T is not *hgithub.Client", h.e.transport) + } + client.SetWritebackGate(gate) + return gate +} + +func suppressedFor(gate *writeback.Gate, number int, kind writeback.Kind) []writeback.Suppressed { + var out []writeback.Suppressed + for _, s := range gate.Recent() { + if s.Number == number && s.Kind == kind { + out = append(out, s) + } + } + return out +} + +// The close-first note, label and close on a contributor's original are +// unsolicited writes: the write-back gate decides them (#15272). +func TestAdoptionCloseFirstWritebackGate(t *testing.T) { + t.Run("refused leaves the original open on the keep-open path", func(t *testing.T) { + h, done := newCloseFirstHarness(t, closeFirstPolicy()) + defer done() + gate := h.installWritebackGate(&closeFirstGateState{adoptOff: true}) + h.adoptCloseFirst() + if len(h.adopt.pulls) != 1 { + t.Fatalf("copy not opened: pulls=%d", len(h.adopt.pulls)) + } + if len(h.adopt.prEdits) != 0 { + t.Fatalf("original closed through a refusing gate: %v", h.adopt.prEdits) + } + for _, c := range h.api.comments { + if strings.Contains(c, "close_first=true") { + t.Fatalf("close-first note posted through a refusing gate: %v", h.api.comments) + } + } + for _, l := range h.addedLabels() { + if l == hgithub.SupersededLabel { + t.Fatalf("superseded label added through a refusing gate: %v", h.api.added) + } + } + rec := h.record() + if rec.SupersededClosedFirst || rec.AdoptedBy != 90 { + t.Fatalf("record = %+v", rec) + } + if s := suppressedFor(gate, 7, writeback.KindContributorAdopt); len(s) != 1 || s[0].Reason != writeback.ReasonOwnOnly { + t.Fatalf("suppressed = %+v", gate.Recent()) + } + }) + t.Run("allowed closes the original first", func(t *testing.T) { + h, done := newCloseFirstHarness(t, closeFirstPolicy()) + defer done() + gate := h.installWritebackGate(&closeFirstGateState{}) + h.adoptCloseFirst() + if len(h.adopt.prEdits) != 1 || h.adopt.prEdits[0] != "7:closed" { + t.Fatalf("original not closed: %v", h.adopt.prEdits) + } + if c := adoptionComments(h.api); len(c) != 1 || !strings.Contains(c[0], "close_first=true") { + t.Fatalf("comments: %v", h.api.comments) + } + if rec := h.record(); !rec.SupersededClosedFirst || rec.SupersededBy != 90 { + t.Fatalf("record = %+v", rec) + } + if s := suppressedFor(gate, 7, writeback.KindContributorAdopt); len(s) != 0 { + t.Fatalf("suppressed = %+v", s) + } + }) +} + +// A paused repo gets no reopen while paused; the record stays due its poll +// and the reopen lands once the pause lifts. +func TestAdoptionCloseFirstReopenWaitsForWritebackGate(t *testing.T) { + h, done := newCloseFirstHarness(t, closeFirstPolicy()) + defer done() + st := &closeFirstGateState{} + gate := h.installWritebackGate(st) + h.adoptCloseFirst() + if len(h.adopt.prEdits) != 1 || h.adopt.prEdits[0] != "7:closed" { + t.Fatalf("original not closed: %v", h.adopt.prEdits) + } + h.adopt.setSuperseder(90, "closed", false) + st.paused = true + h.api.reset() + h.clock.advance(adoptCheckInterval) + res := h.sweep() + if len(h.adopt.prEdits) != 1 || res.Comments != 0 || len(commentsWithPrefix(h.api, AdoptionCopyFailedMarker)) != 0 || len(h.api.removed) != 0 { + t.Fatalf("wrote while paused: edits=%v comments=%v removed=%v res=%+v", h.adopt.prEdits, h.api.comments, h.api.removed, res) + } + if rec := h.record(); !rec.SupersededClosedFirst || rec.AdoptionCopyFailed() { + t.Fatalf("record settled while paused = %+v", rec) + } + if s := suppressedFor(gate, 7, writeback.KindContributorAdopt); len(s) != 1 || s[0].Reason != writeback.ReasonRepoPaused { + t.Fatalf("suppressed = %+v", gate.Recent()) + } + + st.paused = false + h.api.reset() + h.clock.advance(adoptCheckInterval) + res = h.sweep() + if len(h.adopt.prEdits) != 2 || h.adopt.prEdits[1] != "7:open" { + t.Fatalf("original not reopened after the pause lifted: %v", h.adopt.prEdits) + } + if notes := commentsWithPrefix(h.api, AdoptionCopyFailedMarker); len(notes) != 1 || res.Comments != 1 { + t.Fatalf("reopen note: %v res=%+v", h.api.comments, res) + } +} + +// A policy refusal (not a pause) after the hive closed the original is +// warned, not merely logged at info: the PR the hive shut stays closed +// until the contributor_adopt policy allows the reopen or a person acts. +func TestAdoptionCloseFirstReopenPolicyRefusalWarns(t *testing.T) { + h, done := newCloseFirstHarness(t, closeFirstPolicy()) + defer done() + st := &closeFirstGateState{} + gate := h.installWritebackGate(st) + h.adoptCloseFirst() + if len(h.adopt.prEdits) != 1 || h.adopt.prEdits[0] != "7:closed" { + t.Fatalf("original not closed: %v", h.adopt.prEdits) + } + h.adopt.setSuperseder(90, "closed", false) + st.adoptOff = true + var logs bytes.Buffer + h.e.logger = slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelWarn})) + h.api.reset() + h.clock.advance(adoptCheckInterval) + res := h.sweep() + if len(h.adopt.prEdits) != 1 || res.Comments != 0 || len(commentsWithPrefix(h.api, AdoptionCopyFailedMarker)) != 0 { + t.Fatalf("wrote through a refusing gate: edits=%v comments=%v res=%+v", h.adopt.prEdits, h.api.comments, res) + } + if rec := h.record(); !rec.SupersededClosedFirst || rec.AdoptionCopyFailed() { + t.Fatalf("record settled through a refusing gate = %+v", rec) + } + if s := suppressedFor(gate, 7, writeback.KindContributorAdopt); len(s) != 1 || s[0].Reason != writeback.ReasonOwnOnly { + t.Fatalf("suppressed = %+v", gate.Recent()) + } + if out := logs.String(); !strings.Contains(out, "level=WARN") || !strings.Contains(out, "hive-closed PR stays closed") || !strings.Contains(out, "writeback_reason="+writeback.ReasonOwnOnly) { + t.Fatalf("policy refusal not warned: %q", out) + } +} + func TestAdoptionCopyFailedMarkerIsSettled(t *testing.T) { if !AdoptionSettledMarker(AdoptionCopyFailedComment(7, 90, "aaa", adoptionCopyFailedClosed, 0)) { t.Fatal("reopen note not a settled marker: the marker scan would re-adopt") diff --git a/src/pkg/github/automerge/automerge_writeback.go b/src/pkg/github/automerge/automerge_writeback.go new file mode 100644 index 0000000000..8bb146a92a --- /dev/null +++ b/src/pkg/github/automerge/automerge_writeback.go @@ -0,0 +1,39 @@ +package automerge + +import ( + "github.com/hivecommons/hive/pkg/writeback" +) + +// writebackGateTransport is the optional transport hook that exposes the +// process's unsolicited write-back gate (hgithub.Client.WritebackGate). A +// transport without it, or with no gate installed, allows every write, as +// the client does before cmd/hive installs one. +type writebackGateTransport interface { + WritebackGate() *writeback.Gate +} + +// writebackGate returns the transport's write-back gate (nil when none). +func (c *Engine) writebackGate() *writeback.Gate { + if c == nil { + return nil + } + t, ok := c.transport.(writebackGateTransport) + if !ok { + return nil + } + return t.WritebackGate() +} + +// writebackAllowed is the one call an unsolicited write in this package +// makes before touching GitHub (hgithub.Client.WritebackAllowed for the +// engine). A refusal is recorded by the gate for the dashboard drill-down; +// the caller skips the write. +func (c *Engine) writebackAllowed(repo string, item writeback.Item, kind writeback.Kind, preview string) writeback.Decision { + return c.writebackGate().AllowedPreview(repo, item, kind, preview) +} + +// writebackItemForObservation is the gate's view of an observed PR the hive +// did not author (adoption only ever targets a contributor's PR). +func writebackItemForObservation(obs stageObservation) writeback.Item { + return writeback.Item{Number: obs.Number, IsPR: true, Author: obs.Author, Labels: obs.Labels, CreatedAt: obs.OpenedAt} +} diff --git a/src/pkg/writeback/testdata/direct-writes-baseline.txt b/src/pkg/writeback/testdata/direct-writes-baseline.txt index d677e9b974..fc4cf03b1e 100644 --- a/src/pkg/writeback/testdata/direct-writes-baseline.txt +++ b/src/pkg/writeback/testdata/direct-writes-baseline.txt @@ -4,7 +4,6 @@ raw pkg/dashboard/delegated_decision_effect.go 1 raw pkg/github/advisory.go 6 raw pkg/github/advisory_forgestate.go 1 raw pkg/github/attribution.go 1 -raw pkg/github/automerge/automerge_adoption_close_first.go 7 raw pkg/github/automerge/automerge_adoption_orphan.go 3 raw pkg/github/automerge/automerge_bot_takeover.go 2 raw pkg/github/automerge/automerge_contributor_adopt.go 15