From ec69daf37eb3fa8dcf462656ee8e2b6c72d73199 Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Tue, 3 Nov 2026 11:09:07 -0500 Subject: [PATCH 1/5] =?UTF-8?q?=F0=9F=90=9B=20Edit=20claim=20ledger,=20nee?= =?UTF-8?q?ds-decision=20and=20sentinel=20comments=20in=20place;=20suppres?= =?UTF-8?q?s=20reviewer-lane=20no-findings=20reviews?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Issue-side comment churn (hivecommons/hive#16433): hive:claim/hive:release transitions now maintain one per-issue claim-ledger comment edited in place (github.notifications.claim_ledger, default on) that every existing marker reader still parses; the needs-decision/ready entry comment is rewritten with an Updated line on re-entry; a new push rewrites the hive's existing sentinel comment instead of stamping the PR again; and in quiet mode a reviewer-lane review that narrates "no findings" with an approving, finding-free verdict is recorded and folded into the hive:status comment instead of being submitted. Signed-off-by: Andrew Anderson --- .../changed-issue-side-comment-churn.md | 1 + src/cmd/hive/claimswire.go | 69 +++++- .../sweeps-and-operations.md | 72 +++++- src/pkg/claims/ledger_comment.go | 231 ++++++++++++++++++ src/pkg/claims/ledger_comment_test.go | 185 ++++++++++++++ src/pkg/config/github_notifications.go | 13 + .../dashboard/settings_parity_allowlist.txt | 1 + .../github/automerge/automerge_stage_human.go | 43 ++++ .../automerge/automerge_stage_human_test.go | 58 +++++ src/pkg/github/claimed_by_label.go | 32 ++- src/pkg/github/issue_marker_comment.go | 77 ++++++ src/pkg/github/pr_status_comment_test.go | 71 ++++++ src/pkg/github/review_request_watcher.go | 47 +++- src/pkg/github/sentinel_sweep.go | 54 ++-- src/pkg/github/sentinel_sweep_test.go | 19 +- src/pkg/issueclaim/issueclaim.go | 5 + src/pkg/review/no_findings.go | 37 +++ src/pkg/review/no_findings_test.go | 28 +++ src/pkg/stagelabels/human.go | 20 ++ 19 files changed, 1008 insertions(+), 55 deletions(-) create mode 100644 changelog.d/changed-issue-side-comment-churn.md create mode 100644 src/pkg/claims/ledger_comment.go create mode 100644 src/pkg/claims/ledger_comment_test.go create mode 100644 src/pkg/github/issue_marker_comment.go diff --git a/changelog.d/changed-issue-side-comment-churn.md b/changelog.d/changed-issue-side-comment-churn.md new file mode 100644 index 0000000000..cf98be5a10 --- /dev/null +++ b/changelog.d/changed-issue-side-comment-churn.md @@ -0,0 +1 @@ +- Issue-side comment churn is cut by editing in place instead of re-posting ([#16433](https://github.com/hivecommons/hive/issues/16433)): `hive:claim` / `hive:release` transitions now maintain one per-issue claim-ledger comment (``, current state plus the last 8 transitions; `github.notifications.claim_ledger`, default on, `false` restores one comment per transition) that every existing claim reader still parses; a PR re-entering a needs-decision stage has its entry comment rewritten with an `Updated ` line; a new push rewrites the hive's existing `hive-sentinel` comment for the new head; and in quiet mode a reviewer-lane review that narrates "no findings" with an approving, finding-free verdict is recorded and folded into the `hive:status` comment instead of being submitted as a review. diff --git a/src/cmd/hive/claimswire.go b/src/cmd/hive/claimswire.go index 3371a51580..eb5470f22f 100644 --- a/src/cmd/hive/claimswire.go +++ b/src/cmd/hive/claimswire.go @@ -240,6 +240,9 @@ func githubClaimHooks(ctx context.Context, cfg *config.Config, client func() *gi } comment := cfg.Governor.Claims.CommentEnabled() label := cfg.Governor.Claims.LabelEnabled() + // The ledger folds every transition into one edited comment per issue + // (hivecommons/hive#16433); off, each transition is its own comment. + ledgerMode := cfg.GitHub.Notifications.ClaimLedgerEnabled() queue := &claimEffectQueue{} attempt := func(fn func(ctx context.Context, gh *github.Client) error, gh *github.Client) error { cctx, cancel := context.WithTimeout(ctx, claimsGitHubTimeout) @@ -265,13 +268,44 @@ func githubClaimHooks(ctx context.Context, cfg *config.Config, client func() *gi logger.Warn("issue-claims: GitHub side effect failed", "what", what, "issue", c.Key(), "attempts", 1, "error", err) } } + // ledger edits the issue's claim ledger comment for event, posting the + // one notifying comment a human owed one gets. The edit is retried: a + // PATCH that lands twice is the same body, unlike a POST. + ledger := func(what string, event claims.LedgerEvent, notice func(previous string) string) { + run(what, event.Claim, func(ctx context.Context, gh *github.Client) error { + res, err := gh.EditIssueMarkerComment(ctx, event.Claim.Repo, event.Claim.Issue, claims.LedgerMarker, func(previous string) string { + return claims.LedgerComment(previous, event) + }) + if err != nil { + return err + } + if notice == nil || !res.Found { + // A freshly created ledger already notified: it carries the + // same @-mention the standalone comment did. + return nil + } + if body := notice(res.Previous); body != "" { + return gh.CreateIssueCommentBudgeted(ctx, event.Claim.Repo, event.Claim.Issue, body) + } + return nil + }) + } return claims.Hooks{ OnClaimed: func(c claims.Claim, outcome claims.Outcome) { queue.run(c.Key(), func() { if comment && outcome == claims.OutcomeClaimed { - runOnce("claim comment", c, func(ctx context.Context, gh *github.Client) error { - return gh.CreateIssueCommentBudgeted(ctx, c.Repo, c.Issue, claims.ClaimComment(c)) - }) + if ledgerMode { + ledger("claim ledger", claims.LedgerEvent{Claim: c, At: c.ClaimedAt}, func(previous string) string { + if claims.LedgerNotifiesHuman(previous, c) { + return claims.LedgerNoticeComment(c) + } + return "" + }) + } else { + runOnce("claim comment", c, func(ctx context.Context, gh *github.Client) error { + return gh.CreateIssueCommentBudgeted(ctx, c.Repo, c.Issue, claims.ClaimComment(c)) + }) + } } if label { // The stage is a fact for the engine (ADR-0025): a live @@ -296,9 +330,17 @@ func githubClaimHooks(ctx context.Context, cfg *config.Config, client func() *gi OnTakenOver: func(now, previous claims.Claim) { queue.run(now.Key(), func() { if comment { - runOnce("takeover comment", now, func(ctx context.Context, gh *github.Client) error { - return gh.CreateIssueComment(ctx, now.Repo, now.Issue, claims.TakeoverComment(now, previous)) - }) + if ledgerMode { + ledger("takeover ledger", claims.LedgerEvent{Claim: now, Previous: previous, At: now.ClaimedAt}, func(string) string { + // The displaced person must hear it; an edit + // tells them nothing. + return claims.LedgerDisplacedNotice(now, previous) + }) + } else { + runOnce("takeover comment", now, func(ctx context.Context, gh *github.Client) error { + return gh.CreateIssueComment(ctx, now.Repo, now.Issue, claims.TakeoverComment(now, previous)) + }) + } } if label { run("claimed stage", now, func(ctx context.Context, gh *github.Client) error { @@ -345,8 +387,9 @@ func githubClaimHooks(ctx context.Context, cfg *config.Config, client func() *gi }) } // Every early release needs a marker: the šŸ”’ comment is - // never edited, and issueclaim.Latest otherwise reads the - // hold as live until until=. This includes relay disconnect, + // never edited (the ledger rewrites it to carry the release + // marker instead), and issueclaim.Latest otherwise reads + // the hold as live until until=. This includes relay disconnect, // revoke and lease-expiry releases: omitting them starved // hive agents while relays flapped (hivecommons/hive#13579). // TTL expiry needs no marker: until= has already lapsed. @@ -356,9 +399,13 @@ func githubClaimHooks(ctx context.Context, cfg *config.Config, client func() *gi // SetIssueClaimLedgerHive still prevents this hive from // believing its own stale hold. if comment && reason != claims.ReasonExpired { - runOnce("release comment", c, func(ctx context.Context, gh *github.Client) error { - return gh.CreateIssueCommentBudgeted(ctx, c.Repo, c.Issue, claims.ReleaseComment(c, reason)) - }) + if ledgerMode { + ledger("release ledger", claims.LedgerEvent{Claim: c, Released: true, Reason: reason, At: time.Now()}, nil) + } else { + runOnce("release comment", c, func(ctx context.Context, gh *github.Client) error { + return gh.CreateIssueCommentBudgeted(ctx, c.Repo, c.Issue, claims.ReleaseComment(c, reason)) + }) + } } }) }, diff --git a/src/docs/operator-reference/sweeps-and-operations.md b/src/docs/operator-reference/sweeps-and-operations.md index 6294f93ad7..e194a4d4b3 100644 --- a/src/docs/operator-reference/sweeps-and-operations.md +++ b/src/docs/operator-reference/sweeps-and-operations.md @@ -539,12 +539,19 @@ not what it records: The comment is created the first time a note is due and PATCHed for every later note; only the creation sends email. - **No "no findings" reviews.** A reviewer whose whole body is the clean - acknowledgement has its verdict recorded through the relay and the - evidence bundle, and no GitHub review is submitted (the reviewer prompts - also stop asking for the line, whatever `review.acknowledge_no_findings` - says). Only perspectives with findings post, and a head carries at most - one hive review: a later perspective's findings for the same head are - folded into the status comment instead of becoming a second review. + acknowledgement — or whose body says it has no findings while its verdict + report approves with an empty findings list, as the plain `reviewer` + lanes narrate ("Read the tree at … Looks correct to me. No findings.") — + has its verdict recorded through the relay and the evidence bundle, and + no GitHub review is submitted (the reviewer prompts also stop asking for + the line, whatever `review.acknowledge_no_findings` says). The verdict + and the reviewer's notes land in the status comment as a + `review-findings:` section instead. A body that asks for a + decision, carries a hive marker, or rides a non-approving verdict is a + real review and still posts. Only perspectives with findings post, and a + head carries at most one hive review: a later perspective's findings for + the same head are folded into the status comment instead of becoming a + second review. - **@-mentions once per cause.** The 071 note mentions the author the first time a cause class appears (conflict, red CI, changes requested) and is silent for further heads with the same cause; a new cause mentions again. @@ -586,6 +593,59 @@ already present), so the effect of the mode can be charted from the logs. `normal` restores the previous behaviour: every note is its own comment, every perspective's verdict its own review, every new head its own mention. +Three issue-side comments are edited in place in either mode, because a +re-post never carried information the previous comment lacked: + +- **Needs-decision entry** (`` and the + other stage entry markers): a PR that re-enters the stage after a decision + cycle has its existing entry comment rewritten, with an `Updated ` + line, instead of receiving a new one. Only the hive's own comment is + reused; a stranger's comment carrying the marker is ignored. +- **Sentinel alert** (` `): a new push rewrites + the hive's existing sentinel comment for the new head rather than + stamping the PR again. The label is what blocks; one explanation per PR + is enough. A hive that cannot verify its own account (no App login and + no resolvable identity) still posts a fresh comment rather than edit a + comment the PR author may have forged. +- **Claim ledger** (`github.notifications.claim_ledger`, default `true`): + see below. + +### Claim ledger (`github.notifications.claim_ledger`) + +**Why:** every `hive:claim` and `hive:release` the fleet posted was a new +comment, and a relaunch or lease revocation appends a release+claim pair +each time. Over 48 hours that was 334 comments — a quarter of everything +the hive wrote — on issues whose holder, as far as a reader cared, had not +changed. + +```yaml +github: + notifications: + claim_ledger: true # default; false restores one comment per claim/release +``` + +With the ledger on, an issue carries **one** claim comment marked +`` that is PATCHed on every transition. It +shows the current state — the same `hive:claim` / `hive:release` / +`hive:preempt` machine marker and text the separate comments carried — and +a collapsed `Claim history` list of the last 8 transitions (timestamp, +agent, kind, release reason). The first claim on an issue creates the +comment; later claims, takeovers and releases edit it, and only the +creation sends email. + +The ledger is written so that every reader of the old comments keeps +working without change: it carries exactly one machine marker, for the +current state, so `issueclaim.Latest` (claim recovery after a restart, the +`claimed-by` label sweep, the contributor lane's "is it free" check and the +dashboard's claims view) reads the ledger the way it read the newest +separate comment. A legacy claim comment on the same issue is superseded +by the ledger's later `at=` the same way a later comment superseded it. + +A human is still told, in a fresh comment, the two things only a new +comment can tell them: that an agent took over an issue they held, and +that they displaced an agent (so they know to drop the `claimed-by` label +when done). Everything else goes into the ledger. + `github.notifications.shadow: true` (default off) adds would-notify instrumentation without changing any write: every new comment, review, review request and @-mention is classified by producer and class, repeats of diff --git a/src/pkg/claims/ledger_comment.go b/src/pkg/claims/ledger_comment.go new file mode 100644 index 0000000000..2c2a24d105 --- /dev/null +++ b/src/pkg/claims/ledger_comment.go @@ -0,0 +1,231 @@ +package claims + +import ( + "fmt" + "regexp" + "strings" + "time" +) + +// The claim ledger is the one comment per issue that records who holds it. +// Before it existed every claim, takeover and release was its own comment, +// and a relaunch/revoke cycle appended a fresh release+claim pair each time +// (334 comments in 48h, a quarter of the hive's output). The ledger is +// edited in place instead: editing notifies nobody, while the facts stay on +// the issue. +// +// Compatibility with marker readers (pkg/issueclaim.Latest, the dashboard's +// contribute claims view, the contributor lane) rests on two rules: +// +// - the ledger body carries EXACTLY ONE machine-readable marker for the +// current state — a `hive:claim` marker while held, a `hive:release` +// marker once released — so a reader that scans comment bodies sees the +// same thing it saw when each transition was its own comment; +// - the history lines never contain a marker prefix, and LedgerMarker +// itself does not start with `" + // LedgerHistoryLimit is how many transitions the ledger keeps. + LedgerHistoryLimit = 8 + + ledgerHistoryOpen = "
Claim history" + ledgerHistoryClose = "
" + ledgerLinePrefix = "- " +) + +// LedgerEvent is one transition the ledger records. +type LedgerEvent struct { + // Claim is the claim the event concerns: the new holder for a claim or + // takeover, the released holder for a release. + Claim Claim + // Previous is the displaced holder on a takeover; zero otherwise. + Previous Claim + // Released is set for a release; Reason is its reason. + Released bool + Reason string + // At is when the transition happened. + At time.Time +} + +// LedgerComment renders the ledger body after event, given the body of the +// existing ledger comment (empty when the issue has none yet). The current +// state is rendered exactly as the standalone claim / takeover / release +// comment used to be, so the marker a reader finds is unchanged; the history +// below it keeps the last LedgerHistoryLimit transitions, oldest first. +func LedgerComment(previous string, event LedgerEvent) string { + if event.At.IsZero() { + event.At = time.Now() + } + history := ParseLedgerHistory(previous) + history = append(history, ledgerHistoryLine(event)) + if len(history) > LedgerHistoryLimit { + history = history[len(history)-LedgerHistoryLimit:] + } + var b strings.Builder + b.WriteString(LedgerMarker) + b.WriteString("\n") + switch { + case event.Released: + b.WriteString(releaseCommentAt(event.Claim, event.Reason, event.At)) + case event.Previous.Holder != "": + b.WriteString(TakeoverComment(event.Claim, event.Previous)) + default: + b.WriteString(ClaimComment(event.Claim)) + } + b.WriteString("\n\n") + b.WriteString(ledgerHistoryOpen) + b.WriteString("\n\n") + for _, line := range history { + b.WriteString(ledgerLinePrefix) + b.WriteString(line) + b.WriteString("\n") + } + b.WriteString("\n") + b.WriteString(ledgerHistoryClose) + return b.String() +} + +// ParseLedgerHistory returns the history lines of a ledger body, oldest +// first, without their bullet. A body that is not a ledger yields none. +func ParseLedgerHistory(body string) []string { + if !strings.Contains(body, LedgerMarker) { + return nil + } + start := strings.Index(body, ledgerHistoryOpen) + if start < 0 { + return nil + } + rest := body[start+len(ledgerHistoryOpen):] + if end := strings.Index(rest, ledgerHistoryClose); end >= 0 { + rest = rest[:end] + } + var lines []string + for _, line := range strings.Split(rest, "\n") { + line = strings.TrimSpace(line) + if !strings.HasPrefix(line, ledgerLinePrefix) { + continue + } + if line = strings.TrimSpace(strings.TrimPrefix(line, ledgerLinePrefix)); line != "" { + lines = append(lines, line) + } + } + return lines +} + +// LedgerMentions reports whether the ledger body already names holder: +// a human holder the ledger has never named is owed one notifying comment, +// since an edit emails nobody. +func LedgerMentions(body, holder string) bool { + holder = strings.TrimPrefix(strings.TrimSpace(holder), "@") + if body == "" || holder == "" { + return false + } + lower := strings.ToLower(body) + holder = strings.ToLower(holder) + return strings.Contains(lower, "@"+holder) || strings.Contains(lower, "`"+holder+"`") +} + +// LedgerNotifiesHuman reports whether a claim by c should also post a +// notifying comment: the holder is a person (the claim comment @-mentions +// them) and the ledger has not named them before. +func LedgerNotifiesHuman(previous string, c Claim) bool { + switch c.Kind { + case KindHuman, KindExternal, KindContributor: + default: + return false + } + return !LedgerMentions(previous, c.Holder) +} + +// LedgerNoticeComment is the one notifying comment a newly named human +// holder gets. It carries no claim marker: the ledger is the record, this +// is only the email. +func LedgerNoticeComment(c Claim) string { + return fmt.Sprintf("%s you now hold this issue (%s%s); the claim ledger comment above tracks it. Reply `/unclaim` to release.", mention(c), c.Kind, hiveSuffix(c)) +} + +// LedgerDisplacedNotice is the notifying comment a displaced human holder +// gets on a takeover (an edit would tell them nothing); "" when the +// displaced holder is not a person. +func LedgerDisplacedNotice(now, previous Claim) string { + switch previous.Kind { + case KindHuman, KindExternal, KindContributor: + default: + return "" + } + return fmt.Sprintf("%s: your claim on this issue was taken over by %s (%s). Stop work on this item and pick up something else; the claim ledger comment above has the details.", mention(previous), mention(now), now.Kind) +} + +// ledgerHistoryLine renders one transition. It is prose only: the marker +// prefixes stay out of the history so a reader finds exactly one. +func ledgerHistoryLine(e LedgerEvent) string { + at := e.At.UTC().Format("2006-01-02 15:04 UTC") + who := ledgerName(e.Claim) + var line string + switch { + case e.Released: + reason := strings.TrimSpace(e.Reason) + if reason == "" { + reason = "released" + } + line = fmt.Sprintf("%s — released by %s (%s; %s)", at, who, e.Claim.Kind, reason) + case e.Previous.Holder != "": + line = fmt.Sprintf("%s — taken over by %s (%s) from %s (%s)", at, who, e.Claim.Kind, ledgerName(e.Previous), e.Previous.Kind) + default: + line = fmt.Sprintf("%s — claimed by %s (%s%s)", at, who, e.Claim.Kind, hiveSuffix(e.Claim)) + } + return strings.Join(strings.Fields(strings.ReplaceAll(line, "", At: t0.Add(time.Minute)}) + if n := strings.Count(body, issueclaim.MarkerPrefix); n != 0 { + t.Fatalf("history must not carry a claim marker prefix: %q", body) + } + now := ledgerTestClaim("alice", KindHuman, t0.Add(2*time.Minute)) + body = LedgerComment(body, LedgerEvent{Claim: now, Previous: prev, At: now.ClaimedAt}) + if !strings.Contains(body, "`) that every claim, takeover and + // release edits in place, instead of posting a fresh `hive:claim` / + // `hive:release` comment per transition (hivecommons/hive#16433). A + // human holder the ledger has not named before still gets one notifying + // comment. Default on; `claim_ledger: false` restores a comment per + // transition. + ClaimLedger *bool `yaml:"claim_ledger,omitempty" json:"claim_ledger,omitempty"` +} + +// ClaimLedgerEnabled resolves ClaimLedger with its default (on). +func (c GitHubNotificationsConfig) ClaimLedgerEnabled() bool { + return c.ClaimLedger == nil || *c.ClaimLedger } // Quiet reports whether the hive should fold its PR notes into one edited diff --git a/src/pkg/dashboard/settings_parity_allowlist.txt b/src/pkg/dashboard/settings_parity_allowlist.txt index c88a5414ed..499677130e 100644 --- a/src/pkg/dashboard/settings_parity_allowlist.txt +++ b/src/pkg/dashboard/settings_parity_allowlist.txt @@ -202,6 +202,7 @@ github.attention.flap_window # single-admitter ownership and flap window are YAM github.attention.recipient_budget # per-recipient attention budget, off by default; yaml-only, see docs/notifications.md (#16271) github.attention.reminder_interval # attention-pilot reminder interval; yaml-only, see src/docs/attention-episodes.md (#16361) github.notifications.attention_pilot # opt-in attention-pilot issue status card; yaml-only, see docs/notifications.md (#16358) +github.notifications.claim_ledger # one per-issue claim-ledger comment edited in place; yaml-only, see operator-reference (#16433) github.notifications.mode # quiet|normal PR notification mode; yaml-only, see operator-reference.md github.shared_uid_read_token # shared-UID App read-token opt-in; yaml-only, restart required (#14778) good_first_issue.exclude_labels[] # advanced scorer tuning; yaml-only (#12185) diff --git a/src/pkg/github/automerge/automerge_stage_human.go b/src/pkg/github/automerge/automerge_stage_human.go index 40e779c1af..118e61e8bd 100644 --- a/src/pkg/github/automerge/automerge_stage_human.go +++ b/src/pkg/github/automerge/automerge_stage_human.go @@ -681,6 +681,22 @@ func (c *Engine) postHumanEntry(ctx context.Context, store *stagelabels.Store, k return 0, nil } } + // One entry comment per PR and stage, edited in place + // (hivecommons/hive#16433): a later head or cause rewrites the hive's + // existing 085 / 090 comment with an "updated" line instead of posting + // another copy, which emailed everyone again to say the same thing. + if existing := c.findOwnEntryComment(ctx, obs, stagelabels.EntryCommentMarker(route.Stage)); existing != nil { + updated := stagelabels.EntryCommentUpdated(body, c.now()) + // Rewrites the comment the gate admitted when it was posted; an edit notifies nobody. + if _, _, err := c.gh.Issues.EditComment(ctx, obs.Owner, obs.Repo, existing.GetID(), &gh.IssueComment{Body: gh.Ptr(updated)}); err != nil { // writeback:gated + c.warn("stage labels: entry comment edit failed", "repo", obs.Display, "pr", obs.Number, "stage", route.Stage.String(), "error", err) + return 0, err + } + store.MarkEntryCommentedCause(key, obs.HeadSHA, cause) + store.MarkEntryCommentedDecisionKey(key, decisionKey) + c.info("stage labels: entry comment updated in place", "repo", obs.Display, "pr", obs.Number, "stage", route.Stage.String(), "reasons", route.Reasons) + return 0, nil + } if _, _, err := c.gh.Issues.CreateComment(ctx, obs.Owner, obs.Repo, obs.Number, &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { c.warn("stage labels: entry comment failed", "repo", obs.Display, "pr", obs.Number, "stage", route.Stage.String(), "error", err) return 0, err @@ -691,6 +707,33 @@ func (c *Engine) postHumanEntry(ctx context.Context, store *stagelabels.Store, k return 1, nil } +// findOwnEntryComment returns the hive's existing entry comment carrying +// marker on the PR, or nil. Only a comment the hive's App login wrote +// counts: anyone can type the marker, and the hive must never edit a +// stranger's comment. A list failure reads as "none", so the entry is +// posted rather than lost. +func (c *Engine) findOwnEntryComment(ctx context.Context, obs stageObservation, marker string) *gh.IssueComment { + if marker == "" || c == nil || c.transport == nil { + return nil + } + app := normalizeBotLogin(c.transport.AppBotLogin()) + if app == "" { + return nil + } + comments, err := c.listIssueComments(ctx, obs.Owner, obs.Repo, obs.Number) + if err != nil { + c.warn("stage labels: could not list comments for the entry upsert", "repo", obs.Display, "pr", obs.Number, "error", err) + return nil + } + for _, cm := range comments { + if cm == nil || !strings.Contains(cm.GetBody(), marker) || normalizeBotLogin(cm.GetUser().GetLogin()) != app { + continue + } + return cm + } + return nil +} + // workflowApprovalSnippet appends the self-contained ok-to-test workflow, // rendered for this hive's own App login, to the 085 entry when held runs // stayed `action_required` past the grace period (the repository most likely diff --git a/src/pkg/github/automerge/automerge_stage_human_test.go b/src/pkg/github/automerge/automerge_stage_human_test.go index 83ff0e039d..98985ee975 100644 --- a/src/pkg/github/automerge/automerge_stage_human_test.go +++ b/src/pkg/github/automerge/automerge_stage_human_test.go @@ -849,3 +849,61 @@ func TestApplyStageLabelsHumanPRNeverAskedSupersededCloser(t *testing.T) { t.Fatalf("calls=%v result=%+v added=%v", spy.calls, res, api.added) } } + +// TestEntryCommentUpsertsExistingComment: when the hive's 085 entry comment +// is still on the PR, a re-entry on a new head rewrites it in place with an +// "Updated" line instead of posting a second copy (hivecommons/hive#16433). +// A comment carrying the marker but written by someone else is left alone. +func TestEntryCommentUpsertsExistingComment(t *testing.T) { + api := &stageAPI{labels: map[string]string{}, statefulComments: true} + for _, d := range stagelabels.AllLabelDefs() { + api.labels[d.Name] = d.Color + } + srv := newStageAPI(t, api) + defer srv.Close() + clock := &contributorLaneClock{at: time.Date(2026, 10, 20, 12, 0, 0, 0, time.UTC)} + verdict := &ContributorLaneVerdict{Configured: true, Verdict: "requires_human"} + e, store := humanStageEngine(t, srv.URL, clock, verdict, 0) + ctx := context.Background() + sweep := func(head string, labels ...string) { + t.Helper() + api.reset() + pr := stagePR(14, labels...) + pr.Head.SHA = gh.Ptr(head) + pr.Body = gh.Ptr("Fixes the widget.\n\n— hive: backend=pi model=gpt-6\n") + e.recordStage(stageLaneContributor, "acme/widget", "acme", "widget", pr, contributorLaneReasonNoVerdict, false, nil) + e.noteStageVerdict("acme", "widget", 14, *verdict) + e.noteStageRole("acme", "widget", 14, stagelabels.RoleContributor) + if _, err := e.ApplyStageLabels(ctx); err != nil { + t.Fatal(err) + } + } + key := stageKey("acme", "widget", 14) + + // A stranger's comment carrying the marker must never be edited. + api.issueComments = map[int][]map[string]any{14: {{"id": int64(5), "body": stagelabels.DecisionCommentMarker + "\nforged", "user": map[string]any{"login": "mallory"}}}} + + sweep("sha", "role/contributor", "author/human", "stage/050-review-pending") + if len(api.comments) != 1 || !strings.HasPrefix(api.comments[0], stagelabels.DecisionCommentMarker) { + t.Fatalf("first entry comments = %q", api.comments) + } + if len(api.commentEdits) != 0 { + t.Fatalf("a stranger's marker comment was edited: %q", api.commentEdits) + } + + store.Observe(key, stagelabels.ReviewPending, "review-requested") + clock.advance(time.Hour) + sweep("sha2", "role/contributor", "author/human", "stage/050-review-pending") + if got := stageOf(t, store, 14); got != stagelabels.NeedsDecision { + t.Fatalf("stage=%v want 085", got) + } + if len(api.comments) != 0 { + t.Fatalf("new head must edit the existing entry comment, not post another: %q", api.comments) + } + if len(api.commentEdits) != 1 || !strings.HasPrefix(api.commentEdits[0], stagelabels.DecisionCommentMarker) || !strings.Contains(api.commentEdits[0], "Updated 2026-10-20 13:00 UTC.") { + t.Fatalf("entry comment edits = %q", api.commentEdits) + } + if rec, _ := store.Get(key); !rec.EntryCommented || rec.EntryCommentedHead != "sha2" { + t.Fatalf("record after the in-place update: %+v", rec) + } +} diff --git a/src/pkg/github/claimed_by_label.go b/src/pkg/github/claimed_by_label.go index 1d3b080403..8595c2746b 100644 --- a/src/pkg/github/claimed_by_label.go +++ b/src/pkg/github/claimed_by_label.go @@ -92,23 +92,45 @@ func (c *Client) humanClaimReleased(ctx context.Context, owner, repo string, num return false, err } var bodies []string + // The claim ledger (claims.LedgerMarker) is one comment rewritten per + // transition: once released it carries only the release marker, the + // human claim it ended no longer appears anywhere. A ledger whose + // current state is a human release is a released human claim. + ledgerReleasedHuman := false for _, comment := range comments { if !c.isTrustedAppBotCommentAuthor(comment) { continue } body := comment.GetBody() - if _, ok := issueclaim.ParseReleaseMarker(body); ok { + if rel, ok := issueclaim.ParseReleaseMarker(body); ok { bodies = append(bodies, body) + if strings.Contains(body, claims.LedgerMarker) { + ledgerReleasedHuman = humanClaimKind(rel.Kind) + } + continue + } + marker, ok := issueclaim.ParseMarker(body) + if !ok { continue } - if marker, ok := issueclaim.ParseMarker(body); ok && - (strings.EqualFold(marker.Kind, string(claims.KindHuman)) || - strings.EqualFold(marker.Kind, string(claims.KindContributor)) || strings.EqualFold(marker.Kind, string(claims.KindExternal))) { + if humanClaimKind(marker.Kind) { bodies = append(bodies, body) + } else if strings.Contains(body, claims.LedgerMarker) { + ledgerReleasedHuman = claims.LedgerHumanReleased(body) } } latest, found := issueclaim.Latest(bodies, 0) - return found && latest.Released, nil + if !found { + return ledgerReleasedHuman, nil + } + return latest.Released, nil +} + +// humanClaimKind reports whether kind names a human principal: a person, a +// relay contributor or an external bot acting for one. +func humanClaimKind(kind string) bool { + return strings.EqualFold(kind, string(claims.KindHuman)) || + strings.EqualFold(kind, string(claims.KindContributor)) || strings.EqualFold(kind, string(claims.KindExternal)) } // RemoveClaimedByLabel removes the claimed-by label(s) derived from claim: diff --git a/src/pkg/github/issue_marker_comment.go b/src/pkg/github/issue_marker_comment.go new file mode 100644 index 0000000000..cc7f926e0c --- /dev/null +++ b/src/pkg/github/issue_marker_comment.go @@ -0,0 +1,77 @@ +package github + +import ( + "context" + "fmt" + "strings" + + gh "github.com/google/go-github/v72/github" +) + +// IssueMarkerCommentResult reports what EditIssueMarkerComment did. +type IssueMarkerCommentResult struct { + // Found is set when a comment carrying the marker already existed; + // Previous is its body before the edit. + Found bool + Previous string + // Created is set when the body was posted as a new comment. + Created bool + // Edited is set when the existing comment was rewritten. + Edited bool +} + +// EditIssueMarkerComment finds the hive's own comment on repo#number that +// carries marker, asks render for the body that should replace it (render +// receives the previous body, or "" when none exists) and edits it in +// place; when no such comment exists the rendered body is posted as a new +// comment through the per-issue comment budget. An empty rendered body is +// a no-op, as is an unchanged one. +// +// Editing notifies nobody, which is the point: the claim ledger +// (hivecommons/hive#16433) replaces one comment per claim transition with +// one comment per issue. Only a comment one of the hive's own accounts +// wrote is edited; when the hive cannot name its accounts, any author is +// accepted, the same fallback the sentinel's marker reads use. +func (c *Client) EditIssueMarkerComment(ctx context.Context, repo string, number int, marker string, render func(previous string) string) (IssueMarkerCommentResult, error) { + if c == nil { + return IssueMarkerCommentResult{}, ErrNoGitHubClient + } + if render == nil { + return IssueMarkerCommentResult{}, fmt.Errorf("editing marker comment on %s#%d: no renderer", repo, number) + } + owner, repoName := c.splitRepo(repo) + comments, err := c.listIssueComments(ctx, owner, repoName, number) + if err != nil { + return IssueMarkerCommentResult{}, err + } + var existing *gh.IssueComment + for _, cm := range comments { + if cm == nil || !strings.Contains(cm.GetBody(), marker) || !c.markerAuthorTrusted(cm.GetUser()) { + continue + } + existing = cm + break + } + if existing == nil { + body := render("") + if strings.TrimSpace(body) == "" { + return IssueMarkerCommentResult{}, nil + } + if err := c.CreateIssueCommentBudgeted(ctx, owner+"/"+repoName, number, body); err != nil { + return IssueMarkerCommentResult{}, err + } + return IssueMarkerCommentResult{Created: true}, nil + } + res := IssueMarkerCommentResult{Found: true, Previous: existing.GetBody()} + body := render(res.Previous) + if strings.TrimSpace(body) == "" || body == res.Previous { + return res, nil + } + // Rewrites a comment the hive already owns; an edit notifies nobody. + if _, _, err := c.client.Issues.EditComment(ctx, owner, repoName, existing.GetID(), &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { // writeback:gated + return res, fmt.Errorf("editing marker comment on %s/%s#%d: %w", owner, repoName, number, err) + } + c.noteCommentEdited() + res.Edited = true + return res, nil +} diff --git a/src/pkg/github/pr_status_comment_test.go b/src/pkg/github/pr_status_comment_test.go index b235a3c421..300a72480d 100644 --- a/src/pkg/github/pr_status_comment_test.go +++ b/src/pkg/github/pr_status_comment_test.go @@ -28,6 +28,7 @@ type statusCommentServer struct { creates int edits int deletes []string + reviews int } var issuePathRe = regexp.MustCompile(`^/repos/[^/]+/[^/]+/issues/(\d+)$`) @@ -44,6 +45,9 @@ func (s *statusCommentServer) start(t *testing.T) *httptest.Server { _ = json.NewEncoder(w).Encode(map[string]any{"number": n, "state": "open", "user": map[string]any{"login": "alice", "type": "User"}, "labels": []any{}}) case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/comments"): _ = json.NewEncoder(w).Encode(s.comments) + case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/reviews"): + s.reviews++ + _ = json.NewEncoder(w).Encode(map[string]any{"id": 1, "state": "APPROVED"}) case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/comments"): var body map[string]string _ = json.NewDecoder(r.Body).Decode(&body) @@ -264,6 +268,73 @@ func TestReviewRequestWatcher_QuietModeSuppressesNoFindingsReview(t *testing.T) } } +// Quiet mode: a narrated clean review from a plain reviewer lane ("Read the +// tree … Looks correct to me. No findings.") whose verdict approves with no +// findings is suppressed like the one-line acknowledgement, and its body is +// folded into the PR's status comment — created once, then edited in place +// when the second lane reports — instead of being submitted as a review. +func TestReviewRequestWatcher_QuietModeSuppressesNarratedCleanReview(t *testing.T) { + s := &statusCommentServer{} + srv := s.start(t) + c := reviewTestClient(t, srv.URL) + c.SetAppBotLogin("hive-app[bot]") + c.SetNotificationsQuiet(func() bool { return true }) + dir := withReviewDir(t) + oldLinks := ReviewLinksPath + ReviewLinksPath = filepath.Join(t.TempDir(), "review-links.json") + t.Cleanup(func() { ReviewLinksPath = oldLinks }) + withVerdictDispatchState(t, review.DispatchState{Pending: []review.PendingReview{ + {Repo: "o/r", Number: 5, HeadSHA: "abc", Perspective: review.PerspectiveCorrectness, Agent: "reviewer"}, + {Repo: "o/r", Number: 5, HeadSHA: "abc", Perspective: review.PerspectiveSecurity, Agent: "reviewer-2"}, + }}) + + submit := func(agent, perspective, event, verdict, body string) ReviewResponse { + t.Helper() + path, err := WriteReviewRequest(dir, ReviewRequest{Repo: "o/r", Number: 5, Event: event, Agent: agent, Body: body, Report: validVerdictJSON(t, "o/r", 5, perspective, verdict)}) + if err != nil { + t.Fatal(err) + } + c.ProcessReviewRequestsOnce(context.Background()) + raw, err := os.ReadFile(strings.TrimSuffix(path, ".json") + ".result.json") + if err != nil { + t.Fatal(err) + } + var resp ReviewResponse + _ = json.Unmarshal(raw, &resp) + return resp + } + + narrated := "Read the tree at `c7c8dfb`: the retry loop bounds its attempts. Looks correct to me.\n\nNo findings." + resp := submit("reviewer", "correctness", "approve", "approve", narrated) + if !resp.OK || resp.State != ReviewEventRecordVerdict || resp.Note != reviewNoFindingsSuppressedNote { + t.Fatalf("narrated clean review must be recorded, not posted: %+v", resp) + } + if s.reviews != 0 || s.creates != 1 || s.edits != 0 { + t.Fatalf("reviews=%d creates=%d edits=%d, want the verdict folded into one new status comment", s.reviews, s.creates, s.edits) + } + body, _ := s.comments[0]["body"].(string) + if !strings.Contains(body, "**Reviewed** by `reviewer` — no findings.") || !strings.Contains(body, "Looks correct to me.") { + t.Fatalf("status comment must carry the verdict and the reviewer's notes: %q", body) + } + + if resp := submit("reviewer-2", "security", "approve", "approve", "Checked the token handling; no findings from security."); !resp.OK || resp.State != ReviewEventRecordVerdict { + t.Fatalf("second lane must be recorded too: %+v", resp) + } + if s.reviews != 0 || s.creates != 1 || s.edits != 1 { + t.Fatalf("reviews=%d creates=%d edits=%d, want the second lane to edit the status comment", s.reviews, s.creates, s.edits) + } + body, _ = s.comments[0]["body"].(string) + if !strings.Contains(body, "by `reviewer` —") || !strings.Contains(body, "by `reviewer-2` —") { + t.Fatalf("both lanes must share the status comment: %q", body) + } + + // A body that says "no findings" while the verdict disagrees is a + // real review and still goes out. + if resp := submit("reviewer", "correctness", "request_changes", "changes_requested", "No findings on the happy path, but `main.go:12` drops the error."); !resp.OK || s.reviews != 1 { + t.Fatalf("a non-approving verdict must still post: %+v reviews=%d", resp, s.reviews) + } +} + func TestMaxReviewsPerHeadQuietMode(t *testing.T) { c := testClient(t, "http://127.0.0.1:0") c.SetReviewCadenceLimits(func() bool { return false }, func() int { return 0 }) diff --git a/src/pkg/github/review_request_watcher.go b/src/pkg/github/review_request_watcher.go index ea582bb3de..e85ce6526c 100644 --- a/src/pkg/github/review_request_watcher.go +++ b/src/pkg/github/review_request_watcher.go @@ -299,18 +299,25 @@ func (c *Client) handleOneReviewRequest(ctx context.Context, path string, src re threadID := strings.TrimSpace(req.ThreadID) // A "comment" that names a thread is an in-thread reply, not a PR review. threadReply := okEvent && apiEvent == "COMMENT" && threadID != "" - // Quiet notification mode: a review whose whole body is the clean - // acknowledgement ("**Reviewed** — no findings from …") is recorded as - // a verdict and never submitted. Submitting it emails the author and - // every watcher to say nothing happened; the verdict still reaches the - // evidence bundle and the Activity Monitor. The request keeps its + // Quiet notification mode: a clean review — the one-line acknowledgement + // ("**Reviewed** — no findings from …"), or a narrated body that says it + // has no findings while its verdict report approves with none + // (review.CleanReview; the plain reviewer lanes write the latter, + // hivecommons/hive#16433) — is recorded as a verdict and never + // submitted. Submitting it emails the author and every watcher to say + // nothing happened; the verdict still reaches the evidence bundle and + // the Activity Monitor, and the body is folded into the PR's status + // comment below so the reasoning is not lost. The request keeps its // report, so the shape checks below treat it exactly as record_verdict. noFindingsSuppressed := false if okEvent && !recordOnly && !resolveThread && threadID == "" && !req.Revise && - c.notificationsQuiet() && strings.TrimSpace(req.Report) != "" && review.NoFindingsAcknowledgement(req.Body) { - recordOnly = true - noFindingsSuppressed = true - req.Event = ReviewEventRecordVerdict + c.notificationsQuiet() && strings.TrimSpace(req.Report) != "" { + reports, _ := review.ValidateReportsFor([]byte(strings.TrimSpace(req.Report)), c.perspectives) + if review.CleanReview(req.Body, reports) { + recordOnly = true + noFindingsSuppressed = true + req.Event = ReviewEventRecordVerdict + } } // Validate shape BEFORE authorizing or touching the API — a hopeless request // must never retry. @@ -506,6 +513,14 @@ func (c *Client) handleOneReviewRequest(ctx context.Context, path string, src re // Authorized and well-formed, but nothing to post: record and finish // without touching the GitHub API. if recordOnly { + if noFindingsSuppressed { + // The clean verdict lands in the status comment, edited in + // place, instead of a review submission of its own. + if _, ferr := c.UpsertPRStatusSection(ctx, req.Repo, req.Number, prstatus.KeyReviewFindingsPrefix+verdictSlug(req.Agent), reviewNoFindingsSection(req)); ferr != nil { + c.logger.Warn("review-request watcher: could not fold the clean verdict into the status comment", + slog.String("repo", req.Repo), slog.Int("number", req.Number), slog.String("error", ferr.Error())) + } + } c.recordReviewEvidence(ctx, req, c.recordReviewVerdict(ctx, req, ""), nil, nowFn()) if err := c.fileOutOfScopeReviewBacklog(ctx, req, nowFn().UTC()); err != nil { c.logger.Warn("review-request watcher: could not file out-of-scope backlog", @@ -971,6 +986,20 @@ func (c *Client) maxReviewsPerHead() int { // acknowledgement the quiet mode recorded instead of submitting. const reviewNoFindingsSuppressedNote = "comment suppressed: no-findings acknowledgement recorded as a verdict (github.notifications.mode: quiet)" +// reviewNoFindingsSection renders a suppressed clean review for the status +// comment: the verdict on its own line, the reviewer's reasoning folded. +func reviewNoFindingsSection(req ReviewRequest) string { + var b strings.Builder + fmt.Fprintf(&b, "**Reviewed** by `%s` — no findings.", strings.TrimSpace(req.Agent)) + body := strings.TrimSpace(req.Body) + if body != "" && !review.NoFindingsAcknowledgement(body) { + b.WriteString("\n\n
Reviewer notes\n\n") + b.WriteString(body) + b.WriteString("\n\n
") + } + return b.String() +} + // reviewFindingsSection renders a perspective's findings for the status // comment: who found them, then the body as written. func reviewFindingsSection(req ReviewRequest) string { diff --git a/src/pkg/github/sentinel_sweep.go b/src/pkg/github/sentinel_sweep.go index ad557e6c47..d83985ffe7 100644 --- a/src/pkg/github/sentinel_sweep.go +++ b/src/pkg/github/sentinel_sweep.go @@ -692,6 +692,39 @@ func (c *Client) trySentinelPR(ctx context.Context, displayRepo, owner, repo str if err != nil { return SentinelSweepEvent{}, false, err } + // The hive's sentinel comment for an EARLIER head, if this head has + // none yet. A new push rewrites it for the new head rather than + // stamping the PR a second time (hivecommons/hive#16433): the label is + // what blocks, the comment is the explanation, and one explanation per + // PR is enough. Only a comment the hive can verify as its own is + // reused — a hive that cannot name its accounts never rewrites a + // comment the PR author may have forged. findOwnMarkerComment keeps + // its exact-head read for the clearance logic below. + var prior *gh.IssueComment + if !posted && c.knowsOwnAccounts() { + if prior, _, err = c.findOwnMarkerComment(ctx, owner, repo, number, SentinelMarker); err != nil { + return SentinelSweepEvent{}, false, err + } + } + writeSentinelComment := func(body, what string) error { + target := comment + if !posted { + target = prior + } + if target != nil { + if _, _, err := c.client.Issues.EditComment(ctx, owner, repo, target.GetID(), &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { // writeback:gated + return fmt.Errorf("updating sentinel %s: %w", what, err) + } + c.noteCommentEdited() + return nil + } + _, resp, err := c.client.Issues.CreateComment(ctx, owner, repo, number, &gh.IssueComment{Body: gh.Ptr(body)}) // writeback:gated + c.noteWritebackOutcome(displayRepo, resp, err) + if err != nil { + return fmt.Errorf("posting sentinel %s: %w", what, err) + } + return nil + } if decision.Block && !hasAlertLabel && sentinelClearedByMaintainer(comment, posted) { // The alert for this exact head is on the PR but the label is not: // only a maintainer removes it, and the comment promised "Hive will @@ -741,16 +774,14 @@ func (c *Client) trySentinelPR(ctx context.Context, displayRepo, owner, repo str if err != nil { return SentinelSweepEvent{}, false, fmt.Errorf("removing %s label from trusted author PR: %w", label, err) } - if _, _, err := c.client.Issues.EditComment(ctx, owner, repo, comment.GetID(), &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { // writeback:gated - return SentinelSweepEvent{}, false, fmt.Errorf("updating sentinel notice: %w", err) + if err := writeSentinelComment(body, "notice"); err != nil { + return SentinelSweepEvent{}, false, err } return event, true, nil } if !posted { - _, resp, err := c.client.Issues.CreateComment(ctx, owner, repo, number, &gh.IssueComment{Body: gh.Ptr(body)}) // writeback:gated - c.noteWritebackOutcome(displayRepo, resp, err) - if err != nil { - return SentinelSweepEvent{}, false, fmt.Errorf("posting sentinel notice: %w", err) + if err := writeSentinelComment(body, "notice"); err != nil { + return SentinelSweepEvent{}, false, err } } return event, true, nil @@ -763,15 +794,8 @@ func (c *Client) trySentinelPR(ctx context.Context, displayRepo, owner, repo str if err != nil { return SentinelSweepEvent{}, false, fmt.Errorf("adding %s label: %w", label, err) } - body := SentinelComment(decision, head, author, findings) - if posted { - if _, _, err := c.client.Issues.EditComment(ctx, owner, repo, comment.GetID(), &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { // writeback:gated - return SentinelSweepEvent{}, false, fmt.Errorf("updating sentinel alert: %w", err) - } - } else { - if _, _, err := c.client.Issues.CreateComment(ctx, owner, repo, number, &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { // writeback:gated - return SentinelSweepEvent{}, false, fmt.Errorf("posting sentinel comment: %w", err) - } + if err := writeSentinelComment(SentinelComment(decision, head, author, findings), "alert"); err != nil { + return SentinelSweepEvent{}, false, err } return event, true, nil } diff --git a/src/pkg/github/sentinel_sweep_test.go b/src/pkg/github/sentinel_sweep_test.go index 28ba0cf986..ce53e97d5f 100644 --- a/src/pkg/github/sentinel_sweep_test.go +++ b/src/pkg/github/sentinel_sweep_test.go @@ -1,6 +1,7 @@ package github -// Tests for the sentinel sweep: label + one comment per head on a finding, +// Tests for the sentinel sweep: label + one comment per PR on a finding +// (rewritten for each new head when the hive can verify its own comment), // nothing on a clean PR, no re-application once a maintainer clears the // label for an unchanged head (including across a restart, where the // clearance is read back from the alert comment), fail-closed on an @@ -551,8 +552,8 @@ func TestSweepSentinelClearanceOnNewerHeadIsHonoured(t *testing.T) { c := newTestClient(t, srv, "o", []string{"o/r"}) c.SetAppBotLogin("hive[bot]") res, err := c.SweepSentinel(context.Background(), defaultSentinelOpts(nil)) - if err != nil || len(res.Flagged) != 1 || len(f.labels[9]) != 1 || len(f.comments[9]) != 2 || !strings.Contains(f.comments[9][1], SentinelMarker+" hC") { - t.Fatalf("push after clearance must re-alert: res=%+v err=%v labels=%v comments=%d", res, err, f.labels[9], len(f.comments[9])) + if err != nil || len(res.Flagged) != 1 || len(f.labels[9]) != 1 || len(f.comments[9]) != 1 || !strings.Contains(f.comments[9][0], SentinelMarker+" hC") { + t.Fatalf("push after clearance must re-alert by rewriting the hive's comment: res=%+v err=%v labels=%v comments=%v", res, err, f.labels[9], f.comments[9]) } }) } @@ -617,8 +618,8 @@ func TestSweepSentinelDashboardApprovalReleasesHead(t *testing.T) { c := newTestClient(t, srv, "o", []string{"o/r"}) c.SetAppBotLogin("hive[bot]") res, err := c.SweepSentinel(context.Background(), defaultSentinelOpts(nil)) - if err != nil || len(res.Flagged) != 1 || len(f.labels[9]) != 1 || len(f.comments[9]) != 4 || !strings.Contains(f.comments[9][3], SentinelMarker+" hC") { - t.Fatalf("push after the approval must re-alert: res=%+v err=%v labels=%v comments=%d", res, err, f.labels[9], len(f.comments[9])) + if err != nil || len(res.Flagged) != 1 || len(f.labels[9]) != 1 || len(f.comments[9]) != 3 || !strings.Contains(f.comments[9][0], SentinelMarker+" hC") { + t.Fatalf("push after the approval must re-alert by rewriting the hive's comment: res=%+v err=%v labels=%v comments=%v", res, err, f.labels[9], f.comments[9]) } } @@ -654,8 +655,8 @@ func TestSweepSentinelDashboardApprovalNotHonoured(t *testing.T) { c := newTestClient(t, srv, "o", []string{"o/r"}) c.SetAppBotLogin("hive[bot]") res, err := c.SweepSentinel(context.Background(), defaultSentinelOpts(nil)) - if err != nil || len(res.Flagged) != 1 || len(f.labels[9]) != 1 || len(f.comments[9]) != 3 || !strings.Contains(f.comments[9][2], SentinelMarker+" hB") { - t.Fatalf("new head must re-alert: res=%+v err=%v labels=%v comments=%v", res, err, f.labels[9], f.comments[9]) + if err != nil || len(res.Flagged) != 1 || len(f.labels[9]) != 1 || len(f.comments[9]) != 2 || !strings.Contains(f.comments[9][0], SentinelMarker+" hB") || f.comments[9][1] != tc.body { + t.Fatalf("new head must re-alert by rewriting the hive's comment, leaving the other alone: res=%+v err=%v labels=%v comments=%v", res, err, f.labels[9], f.comments[9]) } }) } @@ -800,8 +801,8 @@ func TestSweepSentinelClearanceOnNewerHeadRejected(t *testing.T) { if got := f.labels[9]; len(got) != 1 || got[0] != "sentinel-alert" { t.Fatalf("label must be applied: %v", got) } - if len(f.comments[9]) != 2 || f.comments[9][0] != alertA || !strings.Contains(f.comments[9][1], SentinelMarker+" hB") { - t.Fatalf("a fresh alert for hB must be posted and the hA alert left alone: %v", f.comments[9]) + if len(f.comments[9]) != 1 || !strings.Contains(f.comments[9][0], SentinelMarker+" hB") || strings.Contains(f.comments[9][0], SentinelMarker+" hA") { + t.Fatalf("the hA alert must be rewritten for hB, not duplicated: %v", f.comments[9]) } }) } diff --git a/src/pkg/issueclaim/issueclaim.go b/src/pkg/issueclaim/issueclaim.go index 0b481814ec..8f563ae148 100644 --- a/src/pkg/issueclaim/issueclaim.go +++ b/src/pkg/issueclaim/issueclaim.go @@ -128,6 +128,9 @@ func (c Claim) Live(now time.Time) bool { type Release struct { Identity string At time.Time + // Kind is the released holder's kind when the marker carries kind= + // (human, agent, contributor, external); "" on older markers. + Kind string } // ParseReleaseMarker reads a `` @@ -151,6 +154,8 @@ func ParseReleaseMarker(body string) (Release, bool) { switch key { case "who": rel.Identity = val + case "kind": + rel.Kind = val case "at": at, err := time.Parse(time.RFC3339, val) if err != nil { diff --git a/src/pkg/review/no_findings.go b/src/pkg/review/no_findings.go index 5476a98162..5f952f1442 100644 --- a/src/pkg/review/no_findings.go +++ b/src/pkg/review/no_findings.go @@ -21,3 +21,40 @@ func NoFindingsAcknowledgement(body string) bool { body = strings.TrimSpace(body) return body != "" && noFindingsRe.MatchString(body) } + +// noFindingsPhraseRe matches the free-text way a reviewer says it found +// nothing ("No findings.", "no findings from this perspective", "I have no +// findings") anywhere in a body. +var noFindingsPhraseRe = regexp.MustCompile(`(?i)\bno\s+(?:further\s+|other\s+|additional\s+)?findings\b`) + +// CleanReview reports whether a review body submitted with reports is a +// clean review in substance, not only in form: either the one-line +// acknowledgement, or a body that says it has no findings while every +// report it rides with approves (or is not applicable) with an empty +// findings list and asks for no decision. The plain reviewer lanes narrate +// their reading ("Read the tree at abc1234 … Looks correct to me. No +// findings.") and so escaped NoFindingsAcknowledgement, costing a review +// email per clean lane per head (hivecommons/hive#16433). A body carrying a +// hidden hive marker (a decision question, a redundant-of pointer) is never +// clean: something downstream reads it. +func CleanReview(body string, reports []PerspectiveReport) bool { + body = strings.TrimSpace(body) + if body == "" { + return false + } + if noFindingsRe.MatchString(body) { + return true + } + if len(reports) == 0 || strings.Contains(body, "\nNo findings otherwise.", approve, false}, + {"narrated body without reports", narrated, nil, false}, + {"empty", "", approve, false}, + } + for _, tc := range cases { + if got := CleanReview(tc.body, tc.reports); got != tc.want { + t.Errorf("%s: CleanReview = %v, want %v", tc.name, got, tc.want) + } + } +} diff --git a/src/pkg/stagelabels/human.go b/src/pkg/stagelabels/human.go index 67d071c50d..a47685e496 100644 --- a/src/pkg/stagelabels/human.go +++ b/src/pkg/stagelabels/human.go @@ -650,6 +650,26 @@ const ( DecisionCommentMarker = "" ) +// EntryCommentMarker is the marker the entry comment for stage carries, or +// "" for a stage with no entry comment. +func EntryCommentMarker(stage Stage) string { + switch stage { + case ReadyForHumanMerge: + return ReadyCommentMarker + case NeedsDecision: + return DecisionCommentMarker + } + return "" +} + +// EntryCommentUpdated is body — a fresh ReadyComment or DecisionComment — +// as it is written over the PR's existing entry comment: the same text with +// one line saying when it was last rewritten, so a reader who saw the +// earlier wording knows it changed (hivecommons/hive#16433). +func EntryCommentUpdated(body string, at time.Time) string { + return strings.TrimRight(body, "\n") + "\n\nUpdated " + at.UTC().Format("2006-01-02 15:04 UTC") + "." +} + // ReadyComment renders the 090 entry comment: // // Ready for a human merge: verdict approved @abc1234, 55/55 checks green, From 98af21b8e0734c0de487c4f81b32c51a1acae289 Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Tue, 3 Nov 2026 11:16:32 -0500 Subject: [PATCH 2/5] =?UTF-8?q?=F0=9F=90=9B=20Fix=20test=20literal=20and?= =?UTF-8?q?=20adoption=20read=20counts=20for=20the=20entry-comment=20upser?= =?UTF-8?q?t?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Andrew Anderson --- .../automerge/automerge_adoption_orphan_test.go | 11 ++++++++--- src/pkg/review/no_findings_test.go | 8 ++++++-- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/src/pkg/github/automerge/automerge_adoption_orphan_test.go b/src/pkg/github/automerge/automerge_adoption_orphan_test.go index e0372e74bd..db283293db 100644 --- a/src/pkg/github/automerge/automerge_adoption_orphan_test.go +++ b/src/pkg/github/automerge/automerge_adoption_orphan_test.go @@ -239,7 +239,9 @@ func TestAdoptionMarkerWithClosedCopyReadopts(t *testing.T) { h.adopt.superseders[89] = map[string]any{"number": 89, "state": "closed", "merged": false} h.adopt.mu.Unlock() res := observe() - if h.adopt.commentReads != 1 { + // One read for the marker scan, one for the 085 entry-comment upsert + // (hivecommons/hive#16433) that precedes posting the entry. + if h.adopt.commentReads != 2 { t.Fatalf("comment reads = %d", h.adopt.commentReads) } if len(h.adopt.pulls) != 1 || len(h.adopt.prEdits) != 0 { @@ -261,7 +263,7 @@ func TestAdoptionMarkerWithClosedCopyReadopts(t *testing.T) { if added := h.addedLabels(); len(added) != 1 || added[0] != "stage/074-adopted-by-hive" { t.Fatalf("074 after marker recovery: added=%v removed=%v", h.api.added, h.api.removed) } - if h.adopt.commentReads != 1 { + if h.adopt.commentReads != 2 { t.Fatalf("comments re-read: %d", h.adopt.commentReads) } } @@ -320,7 +322,10 @@ func TestAdoptionMarkerSettledOrAbsentIsNotRecovered(t *testing.T) { h.adopt.mu.Unlock() observe() observe() - if len(h.adopt.pulls) != 0 || h.adopt.commentReads != 1 { + // The marker scan reads once per head; the 085 entry-comment upsert + // reads once more before the entry is posted, and not again for the + // same head and cause (hivecommons/hive#16433). + if len(h.adopt.pulls) != 0 || h.adopt.commentReads != 2 { t.Fatalf("settled marker recovered: pulls=%d reads=%d", len(h.adopt.pulls), h.adopt.commentReads) } rec, _ := h.e.stageStoreOrShared().Get(stageKey("acme", "widget", 7)) diff --git a/src/pkg/review/no_findings_test.go b/src/pkg/review/no_findings_test.go index ba36748f5c..6eb949e39c 100644 --- a/src/pkg/review/no_findings_test.go +++ b/src/pkg/review/no_findings_test.go @@ -1,6 +1,10 @@ package review -import "testing" +import ( + "testing" + + "github.com/hivecommons/hive/pkg/outputschema" +) func TestNoFindingsAcknowledgement(t *testing.T) { yes := []string{ @@ -42,7 +46,7 @@ func TestCleanReview(t *testing.T) { {"no further findings", "Re-read after the fixup; no further findings from me.", approve, true}, {"not-applicable perspective", "Nothing to review for style here — no findings.", []PerspectiveReport{{Perspective: PerspectiveStyle, Verdict: VerdictApprove, NotApplicable: true}}, true}, {"narration without the phrase", "Read the tree at `c7c8dfb`. Looks correct to me.", approve, false}, - {"says no findings but report has one", narrated, []PerspectiveReport{{Perspective: PerspectiveCorrectness, Verdict: VerdictApprove, Findings: []PerspectiveFinding{{Perspective: PerspectiveCorrectness}}}}, false}, + {"says no findings but report has one", narrated, []PerspectiveReport{{AgentReport: outputschema.AgentReport{Findings: []outputschema.Finding{{Title: "nil deref"}}}, Perspective: PerspectiveCorrectness, Verdict: VerdictApprove}}, false}, {"says no findings but requests changes", narrated, []PerspectiveReport{{Perspective: PerspectiveCorrectness, Verdict: VerdictChangesRequested}}, false}, {"decision requested", "No findings, but a maintainer should decide the API shape.", []PerspectiveReport{{Perspective: PerspectiveCorrectness, Verdict: VerdictApprove, DecisionRequested: true}}, false}, {"hidden marker", "\nNo findings otherwise.", approve, false}, From 1161442c3a45926b907f3c78e48eec6ba98dd85e Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Tue, 3 Nov 2026 11:25:43 -0500 Subject: [PATCH 3/5] =?UTF-8?q?=F0=9F=90=9B=20Teach=20the=20claim=20hook?= =?UTF-8?q?=20tests=20the=20ledger's=20comment=20lookup;=20cover=20ledger?= =?UTF-8?q?=20vs=20legacy=20mode?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Andrew Anderson --- src/cmd/hive/claimswire_budget_test.go | 7 +- src/cmd/hive/claimswire_relaunch_test.go | 104 +++++++++++++++++++++++ 2 files changed, 110 insertions(+), 1 deletion(-) diff --git a/src/cmd/hive/claimswire_budget_test.go b/src/cmd/hive/claimswire_budget_test.go index 5ea53c8100..9330810ad8 100644 --- a/src/cmd/hive/claimswire_budget_test.go +++ b/src/cmd/hive/claimswire_budget_test.go @@ -27,6 +27,11 @@ func TestClaimHooks_LeaseRevokedSharesClaimCommentBudget(t *testing.T) { t.Run(name, func(t *testing.T) { posted := make(chan string, 1) srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodGet && r.URL.Path == "/repos/acme/widgets/issues/7/comments" { + // The claim ledger looks for its comment before writing. + _, _ = w.Write([]byte(`[]`)) + return + } if r.Method != http.MethodPost || r.URL.Path != "/repos/acme/widgets/issues/7/comments" { t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path) http.NotFound(w, r) @@ -77,7 +82,7 @@ func TestClaimHooks_LeaseRevokedSharesClaimCommentBudget(t *testing.T) { t.Fatalf("missing lease release marker: %s", body) } case message := <-failed: - if !exhausted || !strings.Contains(message, github.ErrIssueCommentBudget.Error()) || !strings.Contains(message, "release comment") { + if !exhausted || !strings.Contains(message, github.ErrIssueCommentBudget.Error()) || !strings.Contains(message, "release ledger") { t.Fatalf("unexpected hook failure: %s", message) } case <-time.After(5 * time.Second): diff --git a/src/cmd/hive/claimswire_relaunch_test.go b/src/cmd/hive/claimswire_relaunch_test.go index 253ac6e3fb..033c92ac7e 100644 --- a/src/cmd/hive/claimswire_relaunch_test.go +++ b/src/cmd/hive/claimswire_relaunch_test.go @@ -2,6 +2,7 @@ package main import ( "context" + "encoding/json" "io" "log/slog" "net/http" @@ -89,6 +90,11 @@ func TestClaimHooks_RelaunchReleasePostsReleaseMarker(t *testing.T) { _, _ = w.Write([]byte(`{"number":7,"labels":[{"name":"stage/020-claimed"},{"name":"hive/claimed-by-scanner"}]}`)) }) mux.HandleFunc("/repos/acme/widgets/issues/7/comments", func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodGet { + // The claim ledger looks for its comment before writing. + _, _ = w.Write([]byte(`[]`)) + return + } body, _ := io.ReadAll(r.Body) mu.Lock() comments = append(comments, string(body)) @@ -125,3 +131,101 @@ func TestClaimHooks_RelaunchReleasePostsReleaseMarker(t *testing.T) { t.Fatalf("release comment:\n%s", got[0]) } } + +// With the claim ledger on (the default), an issue's claim, release and +// re-claim are one comment: the first claim creates it, every later +// transition PATCHes it, and the body always carries exactly one machine +// marker — the current state — above the history (hivecommons/hive#16433). +// With the ledger off, each transition is its own comment as before. +func TestClaimHooks_ClaimLedgerEditsOneCommentPerIssue(t *testing.T) { + for _, ledgerOn := range []bool{true, false} { + name := "ledger" + if !ledgerOn { + name = "legacy" + } + t.Run(name, func(t *testing.T) { + var mu sync.Mutex + var posted, edited []string + var existing []byte + mux := http.NewServeMux() + mux.HandleFunc("/repos/acme/widgets/issues/7/comments", func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + defer mu.Unlock() + if r.Method == http.MethodGet { + if existing == nil { + _, _ = w.Write([]byte(`[]`)) + return + } + _, _ = w.Write([]byte(`[{"id":41,"body":` + string(existing) + `,"user":{"login":"hive[bot]"}}]`)) + return + } + var body struct { + Body string `json:"body"` + } + _ = json.NewDecoder(r.Body).Decode(&body) + posted = append(posted, body.Body) + existing, _ = json.Marshal(body.Body) + w.WriteHeader(http.StatusCreated) + _, _ = w.Write([]byte(`{"id":41}`)) + }) + mux.HandleFunc("/repos/acme/widgets/issues/comments/41", func(w http.ResponseWriter, r *http.Request) { + var body struct { + Body string `json:"body"` + } + _ = json.NewDecoder(r.Body).Decode(&body) + mu.Lock() + edited = append(edited, body.Body) + existing, _ = json.Marshal(body.Body) + mu.Unlock() + _, _ = w.Write([]byte(`{"id":41}`)) + }) + mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte(`[]`)) }) + srv := httptest.NewServer(mux) + defer srv.Close() + gh := github.NewClientForTest(srv.URL, "acme", []string{"widgets"}, slog.New(slog.NewTextHandler(io.Discard, nil))) + gh.SetAppBotLogin("hive[bot]") + cfg := &config.Config{} + cfg.Governor.Claims.Label = boolPtr(false) + cfg.Governor.Claims.Comment = boolPtr(true) + cfg.GitHub.Notifications.ClaimLedger = boolPtr(ledgerOn) + hooks := githubClaimHooks(context.Background(), cfg, func() *github.Client { return gh }, nil) + at := time.Date(2026, 11, 3, 9, 0, 0, 0, time.UTC) + claim := claims.Claim{Repo: "acme/widgets", Issue: 7, Holder: "scanner", HolderID: "scanner", Kind: claims.KindAgent, ClaimedAt: at, ExpiresAt: at.Add(time.Hour)} + + hooks.OnClaimed(claim, claims.OutcomeClaimed) + hooks.OnReleased(claim, claims.ReasonHolderRelaunched) + claim.ClaimedAt = at.Add(2 * time.Minute) + hooks.OnClaimed(claim, claims.OutcomeClaimed) + wantPosted, wantEdited := 1, 2 + if !ledgerOn { + wantPosted, wantEdited = 3, 0 + } + testutil.Eventually(t, 5*time.Second, func() bool { + mu.Lock() + defer mu.Unlock() + return len(posted) == wantPosted && len(edited) == wantEdited + }, "claim transitions never settled") + mu.Lock() + defer mu.Unlock() + if len(posted) != wantPosted || len(edited) != wantEdited { + t.Fatalf("posted=%d edited=%d, want %d/%d", len(posted), len(edited), wantPosted, wantEdited) + } + if !ledgerOn { + return + } + if !strings.HasPrefix(posted[0], claims.LedgerMarker) || !strings.Contains(posted[0], "" + + res, err := c.EditIssueMarkerComment(ctx, "o/r", 7, marker, func(prev string) string { + if prev != "" { + t.Fatalf("first render got previous %q", prev) + } + return marker + "\nv1" + }) + if err != nil || !res.Created || res.Found || res.Edited { + t.Fatalf("first write = %+v, %v", res, err) + } + res, err = c.EditIssueMarkerComment(ctx, "o/r", 7, marker, func(prev string) string { + if !strings.HasSuffix(prev, "v1") { + t.Fatalf("second render got previous %q", prev) + } + return marker + "\nv2" + }) + if err != nil || !res.Found || !res.Edited || res.Created { + t.Fatalf("second write = %+v, %v", res, err) + } + res, err = c.EditIssueMarkerComment(ctx, "o/r", 7, marker, func(prev string) string { return prev }) + if err != nil || !res.Found || res.Edited { + t.Fatalf("unchanged body must not edit: %+v, %v", res, err) + } + res, err = c.EditIssueMarkerComment(ctx, "o/r", 7, marker, func(string) string { return " " }) + if err != nil || !res.Found || res.Edited { + t.Fatalf("empty body must not edit: %+v, %v", res, err) + } + if s.creates != 1 || s.edits != 1 || len(s.comments) != 1 { + t.Fatalf("creates=%d edits=%d comments=%d, want 1/1/1", s.creates, s.edits, len(s.comments)) + } + if got := s.comments[0]["body"]; got != marker+"\nv2" { + t.Fatalf("comment body = %q", got) + } +} + +// A marker comment by someone other than the hive is never edited: the +// hive posts its own instead. An empty first render posts nothing. +func TestEditIssueMarkerCommentIgnoresForeignAuthorAndEmptyBody(t *testing.T) { + s := &statusCommentServer{} + s.comments = append(s.comments, map[string]any{"id": 9, "body": "\nforged", "user": map[string]any{"login": "mallory", "type": "User"}}) + srv := s.start(t) + c := testClient(t, srv.URL) + c.SetAppBotLogin("hive-app[bot]") + ctx := context.Background() + const marker = "" + + res, err := c.EditIssueMarkerComment(ctx, "o/r", 7, marker, func(string) string { return "" }) + if err != nil || res.Found || res.Created { + t.Fatalf("empty first render = %+v, %v", res, err) + } + res, err = c.EditIssueMarkerComment(ctx, "o/r", 7, marker, func(prev string) string { + if prev != "" { + t.Fatalf("forged comment must not be offered as previous: %q", prev) + } + return marker + "\nours" + }) + if err != nil || !res.Created { + t.Fatalf("write past forged comment = %+v, %v", res, err) + } + if s.creates != 1 || s.edits != 0 { + t.Fatalf("creates=%d edits=%d, want 1/0", s.creates, s.edits) + } + + if _, err := (*Client)(nil).EditIssueMarkerComment(ctx, "o/r", 7, marker, func(string) string { return "x" }); err == nil { + t.Fatal("nil client must error") + } + if _, err := c.EditIssueMarkerComment(ctx, "o/r", 7, marker, nil); err == nil { + t.Fatal("nil renderer must error") + } +}