diff --git a/changelog.d/fixed-19299-verified-close.md b/changelog.d/fixed-19299-verified-close.md new file mode 100644 index 0000000000..aaa1f8ea82 --- /dev/null +++ b/changelog.d/fixed-19299-verified-close.md @@ -0,0 +1 @@ +- A partially-addressed issue the scanner verified complete is now closed by the hive instead of sitting at `stage/010-actionable` until a person closes it (#17157 and #19177 both carried a scanner note saying "this can be closed"; #19299). The verify-once kick asks the scanner to end its note with `` (or `verdict=partial`), and the issue stage sweep reads that marker from the hive's own comments. When two reads 15 minutes apart agree, every cited PR is merged and no linked PR is still open, it closes the issue as completed with an evidence comment citing the merged PRs. When a guard is not met it parks the issue at 045 with the new `hive/verify-close` label, shown on the activity monitor with a one-click **Close as completed**. `verdict=partial` labels `hive/verified-open`. Held, `hive/tracking`, umbrella or tracker issues, parents with an open child, issues a person reopened and issues a person took out of the lane are never touched. Scanner claims are still released on an agent relaunch (a fresh CLI never resumes the old session); the marker now carries the verdict across it. diff --git a/src/docs/labels-and-control-signals/reference.md b/src/docs/labels-and-control-signals/reference.md index 562c156425..aaf3d01aac 100644 --- a/src/docs/labels-and-control-signals/reference.md +++ b/src/docs/labels-and-control-signals/reference.md @@ -623,7 +623,7 @@ A merged PR covered only part of the issue ([#11931](https://github.com/hivecomm **Checked by:** Close-on-merge sweep, PR-claim label sync and task-list sweep. **When:** Close-on-merge sweep for issues behind a confirmation gate. -**Release or override.** Hive removes it when a later merged PR fully covers the issue and `hive/likely-done` is applied; humans may remove it +**Release or override.** Hive removes it when a later merged PR fully covers the issue and `hive/likely-done` is applied; the hive closes the issue when the scanner's verification marker says complete and the guards hold, or parks it in `hive/verify-close`; humans may remove it **Configuration and implementation.** Fixed label (`src/pkg/github/close_on_merge.go`, `src/pkg/github/task_list_sweep.go`) @@ -641,6 +641,22 @@ A `hive/likely-done` / already-done claim from a merged PR was checked and the i **Configuration and implementation.** Fixed label (`src/pkg/github/prclaims.go` `VerifiedOpenLabel`, `src/cmd/hive/verifyonce.go`) +#### `hive/verify-close` + +**Applies to:** Issues. **Kind:** Hard suppress (the 045 park); dashboard one-click Close. + +The verify-close lane. The scanner's verify-once note ends with a machine-readable verdict, `` (nothing left; `prs` names the merged PRs that delivered it) or `` (work remains). For an open issue labelled `hive/partially-addressed`, the issue stage sweep reads the marker from the hive's own comments only (an agent note is relayed under the hive identity; a marker anyone else writes is ignored) and, once two reads `verifyCloseSettleInterval` (15 minutes, the tracker auto-close's settle interval) apart see the same evidence: closes the issue as *completed* with an evidence comment citing the merged PRs when every cited PR (the marker's plus the merged claim's) is merged and no PR linked from the timeline is still open; otherwise applies this label with one status note naming the unmet guard (a cited PR not merged, an open linked PR, notes that disagree, no cited PR, more than 20 PRs, or a human-filed bug whose reporter confirms the close). `verdict=partial` adds `hive/verified-open` instead. Never touched: a held or `hive/tracking` issue, an umbrella or tracker (the tracker auto-close owns those), a decomposed parent with an open child, an issue a person reopened, and an issue a person took out of the lane by removing this label. While the label is on, the issue derives `stage/045-needs-decision`, no agent is offered it, and the activity monitor row asks *The scanner verified this issue complete* and leads with **Close as completed** (one click, `decide:close-issue`). + +**Who applies it:** Hive. + +**Checked by:** Issue stage sweep (`closeVerifiedComplete`). **When:** Every stage sweep, at most one read of a candidate per settle interval. + +**Release or override.** A person closes the issue from the row, or removes the label when work remains (the hive does not re-apply it after that); the hive removes it when it closes the issue itself once the guards hold + +**Configuration and implementation.** Fixed label (`src/pkg/github/verified_close.go`, `src/pkg/config/issue_filter.go` `VerifyCloseLabel`, `src/pkg/scheduler/kickmessage.go` verify-once wording) + +**Claims across a relaunch.** A scanner claim on a partially-addressed issue is still released when its agent's CLI is relaunched (`releaseClaimsOnAgentRelaunch`): the relaunch notice fires only when a fresh CLI replaces the old one (a surviving pane never releases), and crux does not resume the previous session on a fresh launch, so "the same agent resumes" never reaches that path; keeping the claim would park the issue at 020 on a context that no longer exists (the #13083 incident the release was added for). The verdict no longer depends on the claim: it is on the issue as the marker, the verify-once gate still withholds the issue from a second verification (it reads the ledger's last attempt, which the release keeps), and this sweep acts on the marker whoever holds the issue next. + #### `hive/already-done` **Applies to:** Issues. **Kind:** Contributor hard skip; dashboard display; conditional close. diff --git a/src/docs/labels-and-control-signals/stage-labels.md b/src/docs/labels-and-control-signals/stage-labels.md index d38d17c2ea..953fa0a425 100644 --- a/src/docs/labels-and-control-signals/stage-labels.md +++ b/src/docs/labels-and-control-signals/stage-labels.md @@ -1467,7 +1467,7 @@ These existing labels qualify a stage and may coexist with any stage label; the reconciler never touches them: `hold` / `hold/*`, `needs-human`, `blocked`, `needs-rebase`, `hive:unauthorized` (the App lacks a permission for the next step; see the reference table), -`hive/likely-done`, `hive/partially-addressed`, `hive/verified-open`, +`hive/likely-done`, `hive/partially-addressed`, `hive/verified-open`, `hive/verify-close` (a 045 park, see below), `hive/claimed-by-` (the grey "who" modifier a stage cannot carry), `lgtm`, `role/*`, `author/*`, `dco` / `no-dco`, and the agent provenance labels. @@ -1484,6 +1484,17 @@ implement the remainder (`src/pkg/scheduler/kickmessage.go`, `src/cmd/hive/verifyonce.go`). They are not a second stage and are not retired. +A partially-addressed issue the scanner verified complete leaves that +loop: its verify-once note ends with +``, and the issue stage +sweep closes it as completed (evidence comment citing the merged PRs) or, +when a guard is not met, parks it at `stage/045-needs-decision` with +`hive/verify-close`, the verify-close lane the activity monitor shows with +a one-click **Close as completed** (`src/pkg/github/verified_close.go`). +The lane is a park label rather than a numbered stage: issue stages run +010 to 045 and PR stages 050 to 100, so a `stage/050-…` issue stage would +cross the kinds the stage table keeps disjoint. + #### `hive/claimed-by-`: one rule for the suffix `` names the **kind of party** accountable for the claim, derived from diff --git a/src/docs/notifications.md b/src/docs/notifications.md index 6b99c3bebc..2ff6c688bd 100644 --- a/src/docs/notifications.md +++ b/src/docs/notifications.md @@ -491,6 +491,8 @@ without a class. Review submissions and review requests are always counted as | `github.(*Client).PostInformationalIssueNote` | `status` | passthrough wrapper (issue status card in quiet mode or under `attention_pilot`, for notes nobody acts on); attributed to its caller | | `github.(*Client).closeDecomposedParent` | `status` | | | `github.(*Client).closeDoneTracker` | `status` | | +| `github.(*Client).closeVerified` | `status` | | +| `github.(*Client).parkVerifiedForClose` | `status` | | | `github.(*Client).closeIssueForMergedPRClaimWithIssue` | `status` | | | `github.(*Client).closeSupersededPRDecision` | `status` | | | `github.(*Client).fileReviewBacklog` | `status` | | diff --git a/src/pkg/config/issue_filter.go b/src/pkg/config/issue_filter.go index f6fb4f92b6..68a91c1141 100644 --- a/src/pkg/config/issue_filter.go +++ b/src/pkg/config/issue_filter.go @@ -64,6 +64,12 @@ const ( // suppress — no agent claims a parked issue — and it is not configurable: // the stage table owns the spelling (stagelabels contract tests pin it). PossiblyExistsStageLabel = "stage/017-possible-existing" + // VerifyCloseLabel is the verify-close lane: the scanner verified the + // issue complete (``) but a + // guard kept the hive from closing it itself, so a person confirms the + // close. It parks the issue in the decision bucket (045) like the + // stage label, and it is not configurable. + VerifyCloseLabel = "hive/verify-close" // LegacyNeedsDecisionLabel and LegacyNeedsDirectionLabel are the retired // park labels. Every hive still reads them as the decision bucket so an @@ -290,6 +296,9 @@ func (f IssueFilterConfig) HardSuppressIssueBucket(labels []string) string { if labelMatches(PossiblyExistsStageLabel, actual) { return PossiblyExistsStageLabel } + if labelMatches(VerifyCloseLabel, actual) { + return DefaultNeedsDecisionLabel + } } return "" } diff --git a/src/pkg/dashboard/stage_tracker_decision.go b/src/pkg/dashboard/stage_tracker_decision.go index cf773809d6..d4eaf26699 100644 --- a/src/pkg/dashboard/stage_tracker_decision.go +++ b/src/pkg/dashboard/stage_tracker_decision.go @@ -5,6 +5,7 @@ import ( "strings" "time" + ghpkg "github.com/hivecommons/hive/pkg/github" "github.com/hivecommons/hive/pkg/review" "github.com/hivecommons/hive/pkg/stagelabels" ) @@ -219,6 +220,10 @@ func stageTrackerDecisionNeededWith(it StageTrackerItem, verdict *review.Aggrega return decisionForPR(it, verdict, sentinelLabel, held) case it.Kind == "pr" && it.Stage == stagelabels.ReadyForHumanMerge.Number(): return decisionForHumanMerge(it, held) + case it.Kind == "issue" && stageTrackerHasLabel(it.Labels, ghpkg.VerifyCloseLabel): + // The scanner verified it complete; the hive only stopped short of + // closing it. The answer is Close, one click. + return decisionForVerifyClose(it, held) case it.Kind == "issue" && it.Mirrored: // The issue rides its covering PR; the PR's own row (nested under // the issue) carries the decision. @@ -264,3 +269,40 @@ func stageTrackerWithoutHold(it StageTrackerItem) StageTrackerItem { it.Modifiers = slices.DeleteFunc(slices.Clone(it.Modifiers), func(m string) bool { return m == modHold }) return it } + +// The verify-close lane's action id and asker (hivecommons/hive#19299). +const ( + decisionActionCloseIssue = "decide:close-issue" + decisionAskedByScanner = "the scanner's verification" +) + +// stageTrackerHasLabel reports whether labels carries want (case-insensitive). +func stageTrackerHasLabel(labels []string, want string) bool { + for _, l := range labels { + if strings.EqualFold(strings.TrimSpace(l), want) { + return true + } + } + return false +} + +// decisionForVerifyClose is the verify-close lane's popover: the scanner +// verified the issue complete, a guard kept the hive from closing it +// itself (its status card says which), and Close leads, one click. +func decisionForVerifyClose(it StageTrackerItem, held bool) *StageTrackerDecision { + d := &StageTrackerDecision{Since: it.StageSince, AskedBy: decisionAskedByScanner, BlockerReason: "label:" + ghpkg.VerifyCloseLabel} + d.Question = "The scanner verified this issue complete. Close it, or remove " + ghpkg.VerifyCloseLabel + " if work remains?" + d.Blocker = "The hive did not close it on its own; the reason is in the issue's status card. No agent picks it up while it waits here." + if held { + d.Blocker += " " + decisionHeldBlocker(it.Hold) + } + closeOpt := decisionOption(decisionActionCloseIssue, "Close as completed", true, "") + closeOpt.Lead = true + closeOpt.Consequence = "Closes this issue as completed, attributed to you" + d.Options = []StageTrackerDecisionOption{ + closeOpt, + decisionOption(decisionActionDirection, "Send back", true, ""), + decisionHoldOption(held), + } + return d +} diff --git a/src/pkg/dashboard/stage_tracker_verify_close_test.go b/src/pkg/dashboard/stage_tracker_verify_close_test.go new file mode 100644 index 0000000000..184ee5d059 --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_verify_close_test.go @@ -0,0 +1,30 @@ +package dashboard + +import ( + "testing" + "time" + + ghpkg "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/stagelabels" +) + +// The verify-close lane: the scanner verified the issue complete and the +// hive stopped short of closing it, so the row leads with a one-click Close. +func TestVerifyCloseIssueDecisionLeadsWithClose(t *testing.T) { + it := StageTrackerItem{Kind: "issue", Number: 17157, Stage: stagelabels.IssueNeedsDecision.Number(), + Labels: []string{ghpkg.PartiallyAddressedLabel, ghpkg.VerifyCloseLabel}} + d := stageTrackerDecisionNeededWith(it, nil, "", time.Date(2026, 11, 19, 12, 0, 0, 0, time.UTC), blockerOptionsContext{}) + if d == nil || d.AskedBy != decisionAskedByScanner || len(d.Options) == 0 { + t.Fatalf("decision = %+v, want the verify-close decision", d) + } + lead := d.Options[0] + if lead.Action != decisionActionCloseIssue || !lead.Lead || !lead.Enabled { + t.Fatalf("lead option = %+v, want an enabled one-click %s", lead, decisionActionCloseIssue) + } + + it.Labels = []string{ghpkg.PartiallyAddressedLabel} + d = stageTrackerDecisionNeededWith(it, nil, "", time.Date(2026, 11, 19, 12, 0, 0, 0, time.UTC), blockerOptionsContext{}) + if d != nil && d.AskedBy == decisionAskedByScanner { + t.Fatal("control: without the lane label the ordinary 045 decision applies") + } +} diff --git a/src/pkg/github/issue_stage_labels.go b/src/pkg/github/issue_stage_labels.go index 769be3f000..6648c1119f 100644 --- a/src/pkg/github/issue_stage_labels.go +++ b/src/pkg/github/issue_stage_labels.go @@ -148,6 +148,10 @@ type IssueStageResult struct { // issue and PR they reference is finished (trackers_too, // hivecommons/hive#19071). TrackersClosed int + // VerifiedClosed counts issues closed because the scanner's + // verification marker said complete and every guard held + // (closeVerifiedComplete). + VerifiedClosed int } // issueStageRESTCaller tags the writes for /api/gh-rate-limits. @@ -608,6 +612,12 @@ func SyncIssueStageLabelsWith(ctx context.Context, client *Client, result *Actio res.Comments++ continue } + if !awaitingChildren && client.closeVerifiedComplete(ctx, in, store, key, now, logger) { + res.VerifiedClosed++ + res.Writes++ + res.Comments++ + continue + } if closed, commented := handleMergedPRIssueStage(ctx, client, in, logger); closed { res.MergedPRIssuesClosed++ res.Writes++ diff --git a/src/pkg/github/issue_stage_labels_test.go b/src/pkg/github/issue_stage_labels_test.go index a25978a3dd..5b591cc9c1 100644 --- a/src/pkg/github/issue_stage_labels_test.go +++ b/src/pkg/github/issue_stage_labels_test.go @@ -68,6 +68,9 @@ type issueStageServer struct { // default); timelineGets counts the reads. timelines map[int][]map[string]any timelineGets int + // pullRequests marks numbers GET /issues/N reports as pull requests, + // with their merged_at ("" = not merged), for the verified-close sweep. + pullRequests map[int]string } func newIssueStageServer(t *testing.T) *issueStageServer { @@ -184,7 +187,15 @@ func newIssueStageServer(t *testing.T) *issueStageServer { if _, done := s.closed[n]; done { state = "closed" } - _ = json.NewEncoder(w).Encode(map[string]any{"number": n, "labels": labels, "state": state, "body": s.bodies[n], "user": map[string]any{"login": "hive[bot]", "type": "Bot"}}) + resp := map[string]any{"number": n, "labels": labels, "state": state, "body": s.bodies[n], "user": map[string]any{"login": "hive[bot]", "type": "Bot"}} + if mergedAt, ok := s.pullRequests[n]; ok { + link := map[string]any{"url": "https://api.example/pulls"} + if mergedAt != "" { + link["merged_at"] = mergedAt + } + resp["pull_request"] = link + } + _ = json.NewEncoder(w).Encode(resp) case r.Method == http.MethodGet && strings.HasSuffix(rest, "/timeline"): var n int _, _ = sscanIssue(rest, &n) diff --git a/src/pkg/github/labels.go b/src/pkg/github/labels.go index d488205145..477cd9c777 100644 --- a/src/pkg/github/labels.go +++ b/src/pkg/github/labels.go @@ -78,6 +78,7 @@ var hardSuppressIssueLabels = []string{ issueNeedsDecisionLabel, issueNeedsDirectionLabel, PossiblyExistsStageLabel, + VerifyCloseLabel, } // PossiblyExistsStageLabel is the prior-art gate's park: the issue stage @@ -160,6 +161,10 @@ var escalationIssueLabelDefinitions = map[string]issueLabelDefinition{ color: LikelyDoneLabelColor, description: LikelyDoneLabelDescription, }, + VerifyCloseLabel: { + color: VerifyCloseLabelColor, + description: VerifyCloseLabelDescription, + }, "meta": { color: "5319e7", description: "Tracker for multiple open items sharing one root cause", diff --git a/src/pkg/github/notification_write_sites.go b/src/pkg/github/notification_write_sites.go index 31789a8122..327d5590c6 100644 --- a/src/pkg/github/notification_write_sites.go +++ b/src/pkg/github/notification_write_sites.go @@ -57,6 +57,8 @@ var notificationWriteSites = map[string]NotificationWriteSite{ "github.(*Client).closeDecomposedParent": {Class: NotificationClassStatus}, "github.(*Client).closeIssueForMergedPRClaimWithIssue": {Class: NotificationClassStatus}, "github.(*Client).closeDoneTracker": {Class: NotificationClassStatus}, + "github.(*Client).closeVerified": {Class: NotificationClassStatus}, + "github.(*Client).parkVerifiedForClose": {Class: NotificationClassStatus}, "github.(*Client).closeSupersededPRDecision": {Class: NotificationClassStatus}, "github.(*Client).fileReviewBacklog": {Class: NotificationClassStatus}, "github.(*Client).foldSentinelNotice": {Class: NotificationClassStatus}, diff --git a/src/pkg/github/verified_close.go b/src/pkg/github/verified_close.go new file mode 100644 index 0000000000..fb590d0cee --- /dev/null +++ b/src/pkg/github/verified_close.go @@ -0,0 +1,515 @@ +package github + +import ( + "context" + "fmt" + "log/slog" + "regexp" + "sort" + "strconv" + "strings" + "time" + + "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/gfi" + "github.com/hivecommons/hive/pkg/stagelabels" +) + +// Verified close (hivecommons/hive#19299, the #17157 / #19177 pattern). +// +// A multi-phase PR says `Refs #N`; on merge the claim sync and +// close-on-merge label the issue hive/partially-addressed and the stage +// engine sends it back to 010. The scanner's verify-once kick then reads +// the issue and the merged work and writes its verdict. Until now that +// verdict was free text ("This can be closed"), nothing acted on it, and a +// finished issue sat at 010 until a person closed it. +// +// The scanner now ends its verification note with a machine-readable +// marker: +// +// +// +// +// verdict=complete means nothing is left on the issue; prs names the +// merged PRs that delivered it. This sweep reads the marker from the +// hive's own comments (an agent's note is relayed under the hive identity; +// a marker from anyone else is ignored) and: +// +// - closes the issue as completed, with an evidence comment citing the +// merged PRs, when every guard holds on two reads +// verifyCloseSettleInterval apart; +// - parks it for a person (VerifyCloseLabel, the 045 park the dashboard +// shows with a one-click Close) when the verdict is complete but a +// confidence guard does not hold; +// - labels it hive/verified-open on verdict=partial, so later kicks +// implement the remainder instead of re-verifying. +// +// Never touched: a held or hive/tracking issue, an umbrella or tracker +// (closeDoneTracker owns those), a decomposed parent with an open child, an +// issue a person reopened, and an issue a person took out of the +// verify-close lane by removing its label. The settle bookkeeping is the +// tracker auto-close's (trackerReadDue / trackerSettled, hivecommons/hive#19151). + +const ( + // VerifyCloseLabel is the verify-close lane: an issue the scanner + // verified complete that the hive will not close on its own. It is a + // hard-suppress park (stage/045-needs-decision): no agent is offered + // it, and the dashboard leads its row with Close. + VerifyCloseLabel = config.VerifyCloseLabel + // VerifyCloseLabelColor is the label colour (the likely-done green). + VerifyCloseLabelColor = "0e8a16" + // VerifyCloseLabelDescription is the description the label is created with. + VerifyCloseLabelDescription = "Scanner verified this complete; a person confirms the close" + + // verifyCloseSettleInterval is how far apart the two reads that must see + // the same evidence are, so a close never lands between two PRs or + // before a second note can disagree. It is the tracker auto-close's. + verifyCloseSettleInterval = trackerSettleInterval + // verifyCloseMaxPRs bounds the PR reads one issue can cost per read. An + // issue that cites or links more is parked for a person instead. + verifyCloseMaxPRs = 20 + // verifyCloseKeyPrefix namespaces this sweep's settle records in the + // tracker's read cache. + verifyCloseKeyPrefix = "verify-close:" + // verifyCloseEvidenceMarker identifies the close comment for one set of + // evidence, so a close that failed after its comment is not repeated. + verifyCloseEvidenceMarker = "" + // verifyCloseStatusKey is the status-card section of the lane note. + verifyCloseStatusKey = "verify-close" +) + +var ( + verificationMarkerRe = regexp.MustCompile(``) + verificationAttrRe = regexp.MustCompile(`([a-z]+)=([^\s]+)`) + verificationPRRe = regexp.MustCompile(`^(?:([A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+)#|#)?(\d+)$`) +) + +// VerificationMarker renders the marker an agent ends its verification note +// with. verdict is VerificationVerdictComplete or VerificationVerdictPartial. +func VerificationMarker(verdict string, prs ...int) string { + parts := make([]string, 0, len(prs)) + for _, n := range prs { + if n > 0 { + parts = append(parts, strconv.Itoa(n)) + } + } + s := "" +} + +// verification is one parsed marker. +type verification struct { + Verdict string + PRs []ChildRef +} + +// parseVerificationMarkers returns every well-formed marker in body, in +// order. A marker with an unknown verdict is ignored; a PR token that is +// not a number (or owner/repo#number) is dropped. +func parseVerificationMarkers(body string) []verification { + var out []verification + for _, m := range verificationMarkerRe.FindAllStringSubmatch(body, -1) { + v := verification{} + for _, a := range verificationAttrRe.FindAllStringSubmatch(m[1], -1) { + switch strings.ToLower(a[1]) { + case "verdict": + v.Verdict = strings.ToLower(a[2]) + case "prs": + for _, tok := range strings.Split(a[2], ",") { + pm := verificationPRRe.FindStringSubmatch(strings.TrimSpace(tok)) + if pm == nil { + continue + } + if n, err := strconv.Atoi(pm[2]); err == nil && n > 0 { + v.PRs = append(v.PRs, ChildRef{Repo: strings.ToLower(pm[1]), Number: n}) + } + } + } + } + if v.Verdict == VerificationVerdictComplete || v.Verdict == VerificationVerdictPartial { + out = append(out, v) + } + } + return out +} + +// verifyCloseAction is what the sweep does with one issue. +type verifyCloseAction int + +const ( + verifyCloseSkip verifyCloseAction = iota + verifyClosePartial + verifyClosePark + verifyCloseClose +) + +// verifyClosePR is one PR the evidence names. +type verifyClosePR struct { + Ref ChildRef + // Cited: the verification marker or the merged claim names it; it + // must be merged. A PR only linked from the timeline must not be open. + Cited bool + Merged bool + Open bool +} + +func (p verifyClosePR) state() string { + switch { + case p.Merged: + return "merged" + case p.Open: + return "open" + } + return "closed unmerged" +} + +// verifyCloseFacts is everything the decision reads, gathered first so the +// rules are one pure function. +type verifyCloseFacts struct { + // Hard exemptions: never closed, never parked. + Held bool + Tracking string + Umbrella bool + OpenChildren bool + ReopenedBy string + LaneRemovedBy string + NoVerdict bool + LatestVerdict string + VerdictsDisagree bool + // PRs are the cited and linked PRs, sorted. + PRs []verifyClosePR + // TooManyPRs: more than verifyCloseMaxPRs; nothing was read. + TooManyPRs bool + // ReporterGate is the reporter-confirmation close gate's reason ("" = + // not gated): a person confirms such a close. + ReporterGate string +} + +// decideVerifyClose applies the guards. The reason names the guard that +// parked or skipped the issue. +func decideVerifyClose(f verifyCloseFacts) (verifyCloseAction, string) { + switch { + case f.Held: + return verifyCloseSkip, "held" + case f.Tracking != "": + return verifyCloseSkip, "tracking issue (" + f.Tracking + ")" + case f.Umbrella: + return verifyCloseSkip, "umbrella or tracker; the tracker auto-close owns it" + case f.OpenChildren: + return verifyCloseSkip, "a sub-issue is still open" + case f.ReopenedBy != "": + return verifyCloseSkip, "reopened by " + f.ReopenedBy + case f.LaneRemovedBy != "": + return verifyCloseSkip, VerifyCloseLabel + " removed by " + f.LaneRemovedBy + case f.NoVerdict: + return verifyCloseSkip, "no verification marker" + } + if f.VerdictsDisagree { + return verifyClosePark, "the verification notes disagree (complete and partial)" + } + if f.LatestVerdict == VerificationVerdictPartial { + return verifyClosePartial, "verified partial: remainder still open" + } + if f.TooManyPRs { + return verifyClosePark, fmt.Sprintf("more than %d PRs to check", verifyCloseMaxPRs) + } + cited := 0 + for _, p := range f.PRs { + switch { + case p.Cited && !p.Merged: + return verifyClosePark, "PR " + p.Ref.String() + " is " + p.state() + case !p.Cited && p.Open: + return verifyClosePark, "linked PR " + p.Ref.String() + " is still open" + } + if p.Cited { + cited++ + } + } + if cited == 0 { + return verifyClosePark, "the verification cites no merged PR" + } + if f.ReporterGate != "" { + return verifyClosePark, "the reporter confirms this close" + } + return verifyCloseClose, "verified complete; every cited PR merged, no open linked PR" +} + +// verifyCloseCandidate is the cheap pre-filter: only an issue a merged PR +// partly addressed, or one already in the lane, is ever read. +func verifyCloseCandidate(in IssueStageInput) bool { + if in.Held || HasHoldLabel(in.Labels) || in.TrackerSignal || in.SpekUmbrella { + return false + } + if in.Children != nil && in.Children.Total > 0 && !in.Children.AllClosed() { + return false + } + return issueHasLabel(in.Labels, PartiallyAddressedLabel) || issueHasLabel(in.Labels, VerifyCloseLabel) +} + +// verifyCloseTimelineFacts reads the verdict, the reopen / lane-removal +// guards and the linked PRs from the issue timeline (oldest first). +func (c *Client) verifyCloseTimelineFacts(events []IssueEvent, repoFull string, f *verifyCloseFacts) (linked []ChildRef) { + var verdicts []string + seen := map[ChildRef]bool{} + for _, ev := range events { + switch { + case ev.Event == "commented" && ev.Body != "" && c.IsHiveAuthorLogin(ev.Actor): + for _, v := range parseVerificationMarkers(ev.Body) { + verdicts = append(verdicts, v.Verdict) + for _, ref := range v.PRs { + if strings.EqualFold(ref.Repo, repoFull) { + ref.Repo = "" + } + if !seen[ref] { + seen[ref] = true + f.PRs = append(f.PRs, verifyClosePR{Ref: ref, Cited: true}) + } + } + } + case ev.Event == "reopened" && !ev.ActorIsBot && ev.Actor != "": + f.ReopenedBy = ev.Actor + case ev.Event == "unlabeled" && strings.EqualFold(ev.Label, VerifyCloseLabel) && !ev.ActorIsBot && ev.Actor != "": + f.LaneRemovedBy = ev.Actor + case ev.Event == "cross-referenced" && ev.SourcePR > 0 && (ev.SourceRepo == "" || strings.EqualFold(ev.SourceRepo, repoFull)): + linked = append(linked, ChildRef{Number: ev.SourcePR}) + } + } + if len(verdicts) == 0 { + f.NoVerdict = true + return linked + } + f.LatestVerdict = verdicts[len(verdicts)-1] + for _, v := range verdicts { + if v != f.LatestVerdict { + f.VerdictsDisagree = true + } + } + return linked +} + +// verifyCloseEvidenceHash fingerprints the decision and the PR states so +// two reads can be compared. +func verifyCloseEvidenceHash(action verifyCloseAction, reason string, prs []verifyClosePR) string { + items := make([]trackerItem, 0, len(prs)+1) + items = append(items, trackerItem{Text: strconv.Itoa(int(action)) + " " + reason, State: "decision"}) + for _, p := range prs { + items = append(items, trackerItem{Ref: p.Ref, PR: true, State: p.state() + " cited=" + strconv.FormatBool(p.Cited)}) + } + return trackerEvidenceHash(items) +} + +// verifyCloseComment is the evidence comment left before the close. +func verifyCloseComment(prs []verifyClosePR, hash string) string { + var b strings.Builder + b.WriteString(parentAutoCloseMarker + "\n" + verifyCloseEvidenceMarker + hash + " -->\n") + b.WriteString("The scanner verified this issue complete with nothing left, and the merged work it cites is in:\n\n") + for _, p := range prs { + if p.Cited { + b.WriteString("- PR " + p.Ref.String() + ": merged\n") + } + } + b.WriteString("\nNo linked PR is still open, so the hive is closing it as completed. Reopen it if something is still missing; a reopen by a person is never overridden.") + return b.String() +} + +// verifyCloseParkNote is the status-card note on a parked issue. +func verifyCloseParkNote(reason string) string { + return "**Verify and close:** the scanner verified this issue complete, but the hive did not close it on its own: " + reason + + ". Close it from the dashboard row (one click), or remove `" + VerifyCloseLabel + "` if work remains." +} + +// closeVerifiedComplete runs the verified-close sweep for one issue. It +// reports whether the issue was closed. Two reads verifyCloseSettleInterval +// apart must see the same evidence before it writes anything. +func (c *Client) closeVerifiedComplete(ctx context.Context, in IssueStageInput, store *stagelabels.Store, key string, now time.Time, logger *slog.Logger) bool { + if !verifyCloseCandidate(in) { + return false + } + settleKey := verifyCloseKeyPrefix + key + if !trackerReadDue(settleKey, now) { + return false + } + owner, name := c.splitRepo(in.Repo) + repoFull := strings.ToLower(owner + "/" + name) + issue, _, err := c.client.Issues.Get(ctx, owner, name, in.Number) + if err != nil || !strings.EqualFold(issue.GetState(), "open") || issue.IsPullRequest() { + if err != nil && logger != nil { + logger.Warn("issue stage labels: verify-close issue unreadable, not closing", "repo", in.Repo, "issue", in.Number, "error", err) + } + trackerSettled(settleKey, now, "", false) + return false + } + labels := issueLabelNames(issue.Labels) + f := verifyCloseFacts{Held: HasHoldLabel(labels), ReporterGate: c.reporterConfirmationCloseGateReason(issue)} + if why, tracking := isTrackingIssue(issue); tracking { + f.Tracking = why + } + _, f.Umbrella = gfi.UmbrellaPolicy{}.UmbrellaReason(issue.GetTitle(), labels, issue.GetBody(), 0) + f.OpenChildren = in.Children != nil && in.Children.Total > 0 && !in.Children.AllClosed() + if f.Held || f.Tracking != "" || f.Umbrella || f.OpenChildren { + // Exempt whatever else it says: no further reads. + trackerSettled(settleKey, now, "", false) + return false + } + events, err := c.IssueTimelineSince(ctx, owner+"/"+name, in.Number, time.Time{}) + if err != nil { + if logger != nil { + logger.Warn("issue stage labels: verify-close timeline unreadable, not closing", "repo", in.Repo, "issue", in.Number, "error", err) + } + trackerSettled(settleKey, now, "", false) + return false + } + linked := c.verifyCloseTimelineFacts(events, repoFull, &f) + if in.Claim != nil && in.Claim.MergedPR && in.Claim.PRNumber > 0 { + ref := ChildRef{Repo: strings.ToLower(in.Claim.PRRepo), Number: in.Claim.PRNumber} + if strings.EqualFold(ref.Repo, repoFull) { + ref.Repo = "" + } + f.PRs = appendVerifyClosePR(f.PRs, verifyClosePR{Ref: ref, Cited: true}) + } + if !f.NoVerdict && f.LatestVerdict == VerificationVerdictComplete { + for _, ref := range linked { + f.PRs = appendVerifyClosePR(f.PRs, verifyClosePR{Ref: ref}) + } + if len(f.PRs) > verifyCloseMaxPRs { + f.TooManyPRs = true + } else if err := c.readVerifyClosePRs(ctx, owner, name, f.PRs); err != nil { + if logger != nil { + logger.Warn("issue stage labels: verify-close PR unreadable, not closing", "repo", in.Repo, "issue", in.Number, "error", err) + } + trackerSettled(settleKey, now, "", false) + return false + } + } + sort.SliceStable(f.PRs, func(i, j int) bool { + a, b := f.PRs[i].Ref, f.PRs[j].Ref + if a.Repo != b.Repo { + return a.Repo < b.Repo + } + return a.Number < b.Number + }) + action, reason := decideVerifyClose(f) + hash := verifyCloseEvidenceHash(action, reason, f.PRs) + if action == verifyCloseSkip || !trackerSettled(settleKey, now, hash, true) { + if action == verifyCloseSkip { + trackerSettled(settleKey, now, "", false) + } + return false + } + switch action { + case verifyClosePartial: + if !issueHasLabel(labels, VerifiedOpenLabel) { + if err := c.AddLabels(ctx, in.Repo, in.Number, []string{VerifiedOpenLabel}); err != nil && logger != nil { + logger.Warn("issue stage labels: labelling verified-open failed", "repo", in.Repo, "issue", in.Number, "error", err) + } + } + return false + case verifyClosePark: + c.parkVerifiedForClose(ctx, in, labels, reason, logger) + return false + } + return c.closeVerified(ctx, in, labels, f.PRs, hash, store, key, logger) +} + +func appendVerifyClosePR(prs []verifyClosePR, p verifyClosePR) []verifyClosePR { + for i := range prs { + if prs[i].Ref == p.Ref { + prs[i].Cited = prs[i].Cited || p.Cited + return prs + } + } + return append(prs, p) +} + +// readVerifyClosePRs fills Merged / Open for each PR from the issues API +// (pull_request.merged_at). An unreadable PR is an error: no write that +// cycle. +func (c *Client) readVerifyClosePRs(ctx context.Context, owner, name string, prs []verifyClosePR) error { + for i := range prs { + _, issue, err := c.readTrackerItem(ctx, owner, name, prs[i].Ref) + if err != nil { + return err + } + prs[i].Open = strings.EqualFold(issue.GetState(), "open") + prs[i].Merged = issue.IsPullRequest() && !issue.GetPullRequestLinks().GetMergedAt().IsZero() + } + return nil +} + +// parkVerifiedForClose puts the issue in the verify-close lane: the label +// (a 045 park, out of the actionable set) and one status note saying why +// the hive did not close it. +func (c *Client) parkVerifiedForClose(ctx context.Context, in IssueStageInput, labels []string, reason string, logger *slog.Logger) { + if issueHasLabel(labels, VerifyCloseLabel) { + // Already in the lane: the note was posted when it entered. + return + } + if err := c.AddLabels(ctx, in.Repo, in.Number, []string{VerifyCloseLabel}); err != nil { + if logger != nil { + logger.Warn("issue stage labels: adding verify-close label failed", "repo", in.Repo, "issue", in.Number, "error", err) + } + return + } + note := verifyCloseParkMarker + "\n" + verifyCloseParkNote(reason) + if _, err := c.PostInformationalIssueNote(ctx, in.Repo, in.Number, verifyCloseStatusKey, note, func(ctx context.Context) error { + return c.CreateIssueCommentBudgeted(ctx, in.Repo, in.Number, note) + }); err != nil && logger != nil { + logger.Warn("issue stage labels: verify-close note failed", "repo", in.Repo, "issue", in.Number, "error", err) + } + if logger != nil { + logger.Info("issue stage labels: verified complete, parked for a person to close", "repo", in.Repo, "issue", in.Number, "reason", reason) + } +} + +// closeVerified posts the evidence comment (once per evidence) and closes +// the issue as completed. A failed or refused comment means no close. +func (c *Client) closeVerified(ctx context.Context, in IssueStageInput, labels []string, prs []verifyClosePR, hash string, store *stagelabels.Store, key string, logger *slog.Logger) bool { + owner, name := c.splitRepo(in.Repo) + needle := verifyCloseEvidenceMarker + hash + " -->" + posted, err := c.IssueCommentsContain(ctx, in.Repo, in.Number, needle) + if err != nil { + if logger != nil { + logger.Warn("issue stage labels: verify-close comments unreadable, not closing", "repo", in.Repo, "issue", in.Number, "error", err) + } + return false + } + if !posted { + if err := c.CreateIssueCommentBudgeted(ctx, in.Repo, in.Number, verifyCloseComment(prs, hash)); err != nil { + if logger != nil { + logger.Warn("issue stage labels: verify-close evidence comment failed, not closing", "repo", in.Repo, "issue", in.Number, "error", err) + } + return false + } + } + if _, err := stagelabels.Enforce(ctx, c.StageLabeler(), stagelabels.IssueItem, owner, name, in.Number, labels, stagelabels.Desired{}); err != nil && logger != nil { + logger.Warn("issue stage labels: clearing stage labels before verified close failed", "repo", in.Repo, "issue", in.Number, "error", err) + } + if err := c.CloseIssue(ctx, in.Repo, in.Number, IssueCloseOptions{StateReason: IssueStateReasonCompleted}); err != nil { + if logger != nil { + logger.Warn("issue stage labels: verified close failed", "repo", in.Repo, "issue", in.Number, "error", err) + } + return false + } + if issueHasLabel(labels, VerifyCloseLabel) { + if err := c.RemoveLabel(ctx, in.Repo, in.Number, VerifyCloseLabel); err != nil && logger != nil { + logger.Warn("issue stage labels: removing verify-close label after close failed", "repo", in.Repo, "issue", in.Number, "error", err) + } + } + if store != nil { + store.Forget(key) + } + if logger != nil { + logger.Info("issue stage labels: issue closed, scanner verified it complete", "repo", in.Repo, "issue", in.Number, "evidence", hash, "prs", len(prs)) + } + return true +} diff --git a/src/pkg/github/verified_close_test.go b/src/pkg/github/verified_close_test.go new file mode 100644 index 0000000000..ede618e7cd --- /dev/null +++ b/src/pkg/github/verified_close_test.go @@ -0,0 +1,261 @@ +package github + +import ( + "slices" + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/stagelabels" +) + +func TestParseVerificationMarkers(t *testing.T) { + body := "Scanner verification: done.\n" + VerificationMarker(VerificationVerdictComplete, 19172, 19179) + + "\n\n" + got := parseVerificationMarkers(body) + if len(got) != 2 { + t.Fatalf("markers = %+v, want the complete and partial ones (unknown verdict ignored)", got) + } + if got[0].Verdict != VerificationVerdictComplete || len(got[0].PRs) != 2 || got[0].PRs[0] != (ChildRef{Number: 19172}) { + t.Errorf("complete marker = %+v", got[0]) + } + if got[1].Verdict != VerificationVerdictPartial || len(got[1].PRs) != 2 || got[1].PRs[1] != (ChildRef{Repo: "acme/other", Number: 6}) { + t.Errorf("partial marker = %+v (a non-number PR token is dropped)", got[1]) + } + if VerificationMarker(VerificationVerdictPartial) != "" { + t.Errorf("marker without PRs = %q", VerificationMarker(VerificationVerdictPartial)) + } +} + +func TestDecideVerifyCloseGuards(t *testing.T) { + merged := []verifyClosePR{{Ref: ChildRef{Number: 21}, Cited: true, Merged: true}} + ok := verifyCloseFacts{LatestVerdict: VerificationVerdictComplete, PRs: merged} + if a, why := decideVerifyClose(ok); a != verifyCloseClose { + t.Fatalf("complete, cited PR merged: action=%d (%s), want close", a, why) + } + cases := []struct { + name string + mut func(*verifyCloseFacts) + want verifyCloseAction + }{ + {"held", func(f *verifyCloseFacts) { f.Held = true }, verifyCloseSkip}, + {"tracking", func(f *verifyCloseFacts) { f.Tracking = "label" }, verifyCloseSkip}, + {"umbrella", func(f *verifyCloseFacts) { f.Umbrella = true }, verifyCloseSkip}, + {"open children", func(f *verifyCloseFacts) { f.OpenChildren = true }, verifyCloseSkip}, + {"reopened by a person", func(f *verifyCloseFacts) { f.ReopenedBy = "alice" }, verifyCloseSkip}, + {"lane label removed by a person", func(f *verifyCloseFacts) { f.LaneRemovedBy = "alice" }, verifyCloseSkip}, + {"no marker", func(f *verifyCloseFacts) { f.NoVerdict = true }, verifyCloseSkip}, + {"partial", func(f *verifyCloseFacts) { f.LatestVerdict = VerificationVerdictPartial }, verifyClosePartial}, + {"notes disagree", func(f *verifyCloseFacts) { f.VerdictsDisagree = true }, verifyClosePark}, + {"cited PR not merged", func(f *verifyCloseFacts) { + f.PRs = []verifyClosePR{{Ref: ChildRef{Number: 21}, Cited: true, Open: true}} + }, verifyClosePark}, + {"open linked PR", func(f *verifyCloseFacts) { + f.PRs = append(append([]verifyClosePR(nil), merged...), verifyClosePR{Ref: ChildRef{Number: 22}, Open: true}) + }, verifyClosePark}, + {"no cited PR", func(f *verifyCloseFacts) { f.PRs = nil }, verifyClosePark}, + {"too many PRs", func(f *verifyCloseFacts) { f.TooManyPRs = true }, verifyClosePark}, + {"reporter confirms", func(f *verifyCloseFacts) { f.ReporterGate = "human-filed bug" }, verifyClosePark}, + } + for _, tc := range cases { + f := ok + f.PRs = append([]verifyClosePR(nil), ok.PRs...) + tc.mut(&f) + if a, why := decideVerifyClose(f); a != tc.want { + t.Errorf("%s: action=%d (%s), want %d", tc.name, a, why, tc.want) + } + } + linkedClosed := ok + linkedClosed.PRs = append(append([]verifyClosePR(nil), merged...), verifyClosePR{Ref: ChildRef{Number: 23}}) + if a, _ := decideVerifyClose(linkedClosed); a != verifyCloseClose { + t.Error("a linked PR closed unmerged does not block the close") + } +} + +func TestVerifyCloseCandidate(t *testing.T) { + base := IssueStageInput{Repo: "acme/widgets", Number: 7, Labels: []string{PartiallyAddressedLabel}} + if !verifyCloseCandidate(base) { + t.Fatal("a partially-addressed issue is a candidate") + } + for name, in := range map[string]IssueStageInput{ + "plain issue": {Labels: []string{"bug"}}, + "held": {Labels: []string{PartiallyAddressedLabel}, Held: true}, + "hold label": {Labels: []string{PartiallyAddressedLabel, "hold"}}, + "tracker": {Labels: []string{PartiallyAddressedLabel}, TrackerSignal: true}, + "open children": {Labels: []string{PartiallyAddressedLabel}, Children: &IssueChildren{Total: 2, Completed: 1}}, + } { + if verifyCloseCandidate(in) { + t.Errorf("%s: must not be read", name) + } + } + if !verifyCloseCandidate(IssueStageInput{Labels: []string{VerifyCloseLabel}}) { + t.Error("an issue already in the lane is re-read so it can close once the guards hold") + } +} + +type verifyCloseCase struct { + labels []string + body string + timeline []map[string]any + // pullRequests maps PR number to merged_at ("" = open / unmerged). + pullRequests map[int]string + // closedPRs are PR numbers that are closed (merged or not). + closedPRs []int +} + +// runVerifyCloseSweeps sweeps issue #7 at stageNow() and again one settle +// interval later. It returns whether it closed after each sweep, the +// comments posted and the labels added. +func runVerifyCloseSweeps(t *testing.T, tc verifyCloseCase) (afterFirst, afterSecond bool, comments, added []string, timelineGets int) { + t.Helper() + resetTrackerReadsForTest(t) + fake := newIssueStageServer(t) + c := NewClientForTest(fake.srv.URL, "acme", []string{"widgets"}, testLogger()) + c.SetAppBotLogin("hive[bot]") + c.SetIssueStageLabels(func() IssueStagePolicy { return IssueStagePolicy{Enabled: true} }) + store := stagelabels.NewStore("", stageNow) + store.Observe(stagelabels.Key("acme/widgets", 7), stagelabels.Actionable, "actionable") + fake.mu.Lock() + fake.bodies[7] = tc.body + fake.pullRequests = tc.pullRequests + for _, n := range tc.closedPRs { + fake.closed[n] = "completed" + } + fake.timelines = map[int][]map[string]any{7: tc.timeline} + fake.mu.Unlock() + + build := func() *ActionableResult { + result := &ActionableResult{} + result.Issues = IssueResultFromItems([]Issue{{Repo: "acme/widgets", Number: 7, Title: "Slice 5: knowledge advise route", Body: tc.body, + Labels: append([]string{stagelabels.Actionable.Label()}, tc.labels...)}}) + return result + } + syncSeeded(t, fake, c, build(), store, stageNow()) + fake.mu.Lock() + _, afterFirst = fake.closed[7] + fake.mu.Unlock() + syncSeeded(t, fake, c, build(), store, stageNow().Add(verifyCloseSettleInterval+time.Minute)) + fake.mu.Lock() + defer fake.mu.Unlock() + _, afterSecond = fake.closed[7] + return afterFirst, afterSecond, append([]string(nil), fake.commentBodies[7]...), append([]string(nil), fake.added[7]...), fake.timelineGets +} + +func scannerNote(marker string) map[string]any { + return timelineEvent("commented", "hive[bot]", "Bot", "Scanner verification: #21 implements it.\n"+marker, "2026-11-19T04:54:00Z") +} + +func TestVerifiedClose_CompleteClosesAfterSettleWithEvidence(t *testing.T) { + first, second, comments, _, _ := runVerifyCloseSweeps(t, verifyCloseCase{ + labels: []string{PartiallyAddressedLabel}, + timeline: []map[string]any{scannerNote(VerificationMarker(VerificationVerdictComplete, 21))}, + pullRequests: map[int]string{21: "2026-11-19T06:00:00Z"}, + closedPRs: []int{21}, + }) + if first { + t.Fatal("the first read must only record the evidence, not close") + } + if !second { + t.Fatal("the same complete verdict on a second read must close the issue") + } + var evidence string + for _, c := range comments { + if strings.Contains(c, verifyCloseEvidenceMarker) { + evidence = c + } + } + if evidence == "" || !strings.Contains(evidence, "PR #21: merged") || !strings.Contains(evidence, parentAutoCloseMarker) { + t.Fatalf("evidence comment = %q", comments) + } +} + +func TestVerifiedClose_GuardUnmetParksForAPerson(t *testing.T) { + for name, tc := range map[string]verifyCloseCase{ + "cited PR still open": { + timeline: []map[string]any{scannerNote(VerificationMarker(VerificationVerdictComplete, 21))}, + pullRequests: map[int]string{21: ""}, + }, + "open linked PR": { + timeline: []map[string]any{ + scannerNote(VerificationMarker(VerificationVerdictComplete, 21)), + {"event": "cross-referenced", "created_at": "2026-11-19T05:00:00Z", "source": map[string]any{"type": "issue", "issue": map[string]any{ + "number": 22, "pull_request": map[string]any{"url": "https://api.example/pulls"}, + "repository": map[string]any{"full_name": "acme/widgets"}, + }}}, + }, + pullRequests: map[int]string{21: "2026-11-19T06:00:00Z", 22: ""}, + closedPRs: []int{21}, + }, + "notes disagree": { + timeline: []map[string]any{ + scannerNote(VerificationMarker(VerificationVerdictPartial, 21)), + scannerNote(VerificationMarker(VerificationVerdictComplete, 21)), + }, + pullRequests: map[int]string{21: "2026-11-19T06:00:00Z"}, + closedPRs: []int{21}, + }, + } { + tc.labels = []string{PartiallyAddressedLabel} + _, second, _, added, _ := runVerifyCloseSweeps(t, tc) + if second { + t.Errorf("%s: an unmet guard must not close", name) + } + if !slices.Contains(added, VerifyCloseLabel) { + t.Errorf("%s: labels added = %v, want %s (the verify-close lane)", name, added, VerifyCloseLabel) + } + } +} + +func TestVerifiedClose_PartialLabelsVerifiedOpen(t *testing.T) { + _, second, _, added, _ := runVerifyCloseSweeps(t, verifyCloseCase{ + labels: []string{PartiallyAddressedLabel}, + timeline: []map[string]any{scannerNote(VerificationMarker(VerificationVerdictPartial, 21))}, + }) + if second || !slices.Contains(added, VerifiedOpenLabel) || slices.Contains(added, VerifyCloseLabel) { + t.Fatalf("partial verdict: closed=%v added=%v, want hive/verified-open only", second, added) + } +} + +func TestVerifiedClose_NeverTouched(t *testing.T) { + complete := []map[string]any{scannerNote(VerificationMarker(VerificationVerdictComplete, 21))} + prs := map[int]string{21: "2026-11-19T06:00:00Z"} + for name, tc := range map[string]verifyCloseCase{ + "hold": {labels: []string{PartiallyAddressedLabel, "hold"}, timeline: complete}, + "tracking": {labels: []string{PartiallyAddressedLabel, "hive/tracking"}, timeline: complete}, + "umbrella": {labels: []string{PartiallyAddressedLabel, "epic"}, timeline: complete}, + "reopened by a person": {labels: []string{PartiallyAddressedLabel}, timeline: append(append([]map[string]any(nil), complete...), + timelineEvent("reopened", "alice", "User", "", "2026-11-19T07:00:00Z"))}, + "lane label removed by a person": {labels: []string{PartiallyAddressedLabel}, timeline: append(append([]map[string]any(nil), complete...), + map[string]any{"event": "unlabeled", "created_at": "2026-11-19T07:00:00Z", "label": map[string]any{"name": VerifyCloseLabel}, "actor": map[string]any{"login": "alice", "type": "User"}})}, + "marker from someone else": {labels: []string{PartiallyAddressedLabel}, timeline: []map[string]any{ + timelineEvent("commented", "mallory", "User", VerificationMarker(VerificationVerdictComplete, 21), "2026-11-19T04:54:00Z")}}, + "no marker, free text only": {labels: []string{PartiallyAddressedLabel}, timeline: []map[string]any{ + timelineEvent("commented", "hive[bot]", "Bot", "Scanner verification: this can be closed.", "2026-11-19T04:54:00Z")}}, + } { + tc.pullRequests = prs + tc.closedPRs = []int{21} + _, second, _, added, _ := runVerifyCloseSweeps(t, tc) + if second || slices.Contains(added, VerifyCloseLabel) { + t.Errorf("%s: closed=%v added=%v, want nothing", name, second, added) + } + } +} + +func TestVerifiedClose_PlainIssueCostsNoReads(t *testing.T) { + _, second, _, _, gets := runVerifyCloseSweeps(t, verifyCloseCase{ + labels: []string{"bug"}, + timeline: []map[string]any{scannerNote(VerificationMarker(VerificationVerdictComplete, 21))}, + }) + if second || gets != 0 { + t.Fatalf("an issue no merged PR partly addressed is never read: closed=%v timeline reads=%d", second, gets) + } +} + +func TestVerifyCloseLabelParksInDecisionBucket(t *testing.T) { + if got := hardSuppressIssueLabel([]string{VerifyCloseLabel}); got != VerifyCloseLabel { + t.Fatalf("hardSuppressIssueLabel = %q, want %s: the lane keeps agents off the issue", got, VerifyCloseLabel) + } + if got := parkedOnPersonLabel(IssueStageInput{Labels: []string{VerifyCloseLabel}}); got != VerifyCloseLabel { + t.Fatalf("parkedOnPersonLabel = %q, want the lane label (045)", got) + } +} diff --git a/src/pkg/scheduler/kickmessage.go b/src/pkg/scheduler/kickmessage.go index e21b8087da..9b0eb6bcc6 100644 --- a/src/pkg/scheduler/kickmessage.go +++ b/src/pkg/scheduler/kickmessage.go @@ -200,7 +200,8 @@ func (s *Scheduler) formatIssueListWithPolicy(issues []github.Issue) (string, bo if hasIssueLabel(issue.Labels, github.VerifiedOpenLabel) { b.WriteString(fmt.Sprintf("; already verified (%s): remaining work is confirmed — do NOT re-verify, implement the rest", github.VerifiedOpenLabel)) } else { - b.WriteString(fmt.Sprintf("; verify once: close the issue if resolved, otherwise label it `%s` and implement the remainder (hive then stops asking); context: %s", github.VerifiedOpenLabel, reason)) + b.WriteString(fmt.Sprintf("; verify once: close the issue if resolved, otherwise label it `%s` and implement the remainder (hive then stops asking); end the verification note with `%s` when nothing is left (hive closes it, or parks it for a person to close) or `%s` when work remains; context: %s", + github.VerifiedOpenLabel, github.VerificationMarker(github.VerificationVerdictComplete, issue.ClaimContext.PRNumber), github.VerificationMarker(github.VerificationVerdictPartial, issue.ClaimContext.PRNumber), reason)) } b.WriteString("\n") } diff --git a/src/pkg/writeback/testdata/direct-writes-baseline.txt b/src/pkg/writeback/testdata/direct-writes-baseline.txt index 0f57645eac..36c862a456 100644 --- a/src/pkg/writeback/testdata/direct-writes-baseline.txt +++ b/src/pkg/writeback/testdata/direct-writes-baseline.txt @@ -122,6 +122,7 @@ wrap pkg/github/review_request_watcher.go 2 wrap pkg/github/stage_labeler.go 2 wrap pkg/github/tracker_autoclose.go 1 wrap pkg/github/tracking_issue.go 1 +wrap pkg/github/verified_close.go 4 wrap pkg/prfollowup/prfollowup.go 2 wrap pkg/questionclose/questionclose.go 2 wrap pkg/scheduler/clarity_gate.go 2