From 2b95b11a92786e425fd8b57eec9b3f924a8f10a9 Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Thu, 19 Nov 2026 11:37:33 -0500 Subject: [PATCH 1/2] fix(sentinel): judge the PR's current head, clear the hive's own stale alert A PR that already carried sentinel-alert was never evaluated again, so a finding on an early head kept the label, the dashboard sentinel gate and the status section on every later head. Every new head is now evaluated. On a clean head the hive removes the label only when it added it itself for an earlier head's alert, rewrites its comment and the quiet-mode status section to say the current head is clean, and audits sentinel-alert-cleared. A finding on the new head keeps the label and rewrites the alert for it. Fixes #19262 Signed-off-by: Andy Anderson --- .../fixed-19262-sentinel-current-head.md | 1 + src/cmd/hive/main_sweeps.go | 16 +- src/docs/notifications.md | 10 + .../sweeps-and-operations.md | 21 ++ src/docs/security-model.md | 9 +- .../stage_tracker_sentinel_head_scope_test.go | 73 +++++ src/pkg/github/sentinel_head_scope.go | 287 ++++++++++++++++++ src/pkg/github/sentinel_head_scope_test.go | 259 ++++++++++++++++ src/pkg/github/sentinel_sweep.go | 65 +++- src/pkg/github/sentinel_sweep_test.go | 7 + 10 files changed, 742 insertions(+), 6 deletions(-) create mode 100644 changelog.d/fixed-19262-sentinel-current-head.md create mode 100644 src/pkg/dashboard/stage_tracker_sentinel_head_scope_test.go create mode 100644 src/pkg/github/sentinel_head_scope.go create mode 100644 src/pkg/github/sentinel_head_scope_test.go diff --git a/changelog.d/fixed-19262-sentinel-current-head.md b/changelog.d/fixed-19262-sentinel-current-head.md new file mode 100644 index 0000000000..6ed9bfd86f --- /dev/null +++ b/changelog.d/fixed-19262-sentinel-current-head.md @@ -0,0 +1 @@ +- The sentinel now judges a PR's current head (#19262). A PR that already carried `sentinel-alert` was never evaluated again, so a finding on an early head (a `Makefile` edit, say) kept the label, the dashboard's "Needs human · sentinel" state and the status section's `Head matched` line on every later head, even a docs-only one. Every new head is now evaluated. When the current head matches no rule, the hive removes the label only if it added it itself for an earlier head's finding, rewrites its sentinel comment and the quiet-mode status section to say the current head is clean, and records `sentinel-alert-cleared` in the audit log; the earlier finding stays in `/api/sentinel` and its head's evidence bundle. A finding on the new head keeps the label and rewrites the alert for that head. A label a person added is never removed. diff --git a/src/cmd/hive/main_sweeps.go b/src/cmd/hive/main_sweeps.go index d1295e20d4..6e834ec3a2 100644 --- a/src/cmd/hive/main_sweeps.go +++ b/src/cmd/hive/main_sweeps.go @@ -1352,6 +1352,15 @@ func sentinelSweepOptions(cfg *config.Config, ghClient *github.Client, dashSrv * if dashSrv == nil { return } + if event.Cleared { + // The current head is clean and the hive removed its own + // label. The ring keeps the earlier head's finding for + // audit; only the clearance is logged (#19262). + detail := fmt.Sprintf("repo=%s, pr=%d, author=%s, head=%s, cleared_head=%s", + event.Repo, event.Number, event.Author, event.HeadSHA, event.ClearedHead) + dashSrv.AuditLogRecord("system", github.SentinelAlertClearedAuditAction, detail, "", event.Repo, event.Number) + return + } // Findings the write-back gate refused still reach the Security // tab and /api/sentinel: the scan happened, only the GitHub // write did not (#writeback containment). @@ -1407,8 +1416,8 @@ func runSentinelSweepIfDue(ctx context.Context, ghClient *github.Client, cfg *co if dashSrv != nil && cfg.Dashboard.Matrix.Active() { dashSrv.RecordMatrixIngest(time.Now(), matrixIngestInterval) } - if len(result.Flagged) > 0 || len(result.Notified) > 0 || len(result.Remediated) > 0 || result.Seen > 0 { - logger.Info("sentinel sweep complete", "seen", result.Seen, "flagged", len(result.Flagged), "notified", len(result.Notified), "suppressed", len(result.Suppressed), "remediated", len(result.Remediated), "skipped", result.Skipped, "errors", len(result.Errors), "cached_repos", result.CachedRepos, "listed_repos", result.ListedRepos) + if len(result.Flagged) > 0 || len(result.Notified) > 0 || len(result.Remediated) > 0 || len(result.Cleared) > 0 || result.Seen > 0 { + logger.Info("sentinel sweep complete", "seen", result.Seen, "flagged", len(result.Flagged), "notified", len(result.Notified), "suppressed", len(result.Suppressed), "remediated", len(result.Remediated), "cleared", len(result.Cleared), "skipped", result.Skipped, "errors", len(result.Errors), "cached_repos", result.CachedRepos, "listed_repos", result.ListedRepos) } hookDispatcher().Fire(context.Background(), hooks.Payload{ Transition: hooks.TransitionSweepCompleted, @@ -1436,6 +1445,9 @@ func logSentinelResult(result *github.SentinelSweepResult, logger *slog.Logger) for _, ev := range result.Remediated { logger.Info("sentinel unflagged trusted author PR", "repo", ev.Repo, "pr", ev.Number, "author", ev.Author, "trusted_reason", ev.TrustedReason, "head", ev.HeadSHA) } + for _, ev := range result.Cleared { + logger.Info("sentinel cleared alert on clean head", "repo", ev.Repo, "pr", ev.Number, "author", ev.Author, "head", ev.HeadSHA, "cleared_head", ev.ClearedHead) + } } // issueUnparkSweepInterval is the minimum spacing between un-park sweeps. A diff --git a/src/docs/notifications.md b/src/docs/notifications.md index 6b99c3bebc..9f4c4b0195 100644 --- a/src/docs/notifications.md +++ b/src/docs/notifications.md @@ -715,6 +715,16 @@ In `normal` mode the informational notice is still its own comment, as before. Either way the finding is recorded for audit, the dashboard Security tab and `/api/sentinel`. +Both kinds are judged per head (hivecommons/hive#19262, +`pkg/github/sentinel_head_scope.go`). Every new head is evaluated, including +on a PR that already carries the label. When the current head matches no +rule, a card section naming an earlier head is rewritten to say the current +head is clean (no card is ever created for that), and a `sentinel-alert` +label the hive added for an earlier head's finding is removed, with the +hive's sentinel comment rewritten as a clean record that keeps the earlier +alert in a collapsed block. A finding on the new head keeps the label and +rewrites the alert for that head. + ### Hive-maintained Actions workflows that defer to the card Some comments come from GitHub Actions workflows in this repository rather diff --git a/src/docs/operator-reference/sweeps-and-operations.md b/src/docs/operator-reference/sweeps-and-operations.md index 038a6b4f27..3863481e92 100644 --- a/src/docs/operator-reference/sweeps-and-operations.md +++ b/src/docs/operator-reference/sweeps-and-operations.md @@ -757,6 +757,27 @@ Every alert is also written to the dashboard audit log as `sentinel-alert`, and, when `evidence.enabled` is on, recorded under `sentinel` in the flagged head's [review evidence bundle](../review-evidence.md). +The sentinel judges the PR's **current head** (hivecommons/hive#19262, +`pkg/github/sentinel_head_scope.go`). Each new head is evaluated on its own +files, even on a PR that already carries the label: + +- **Finding on the new head:** the label stays and the hive's sentinel + comment is rewritten as the alert for that head. +- **Clean new head:** if the hive added the label for an earlier head's + finding (its own alert comment names an earlier head and the newest label + event is the hive's own, made no later than that comment), the label is + removed, the comment is rewritten to say the current head is clean with + the earlier alert kept in a collapsed block, a quiet-mode `sentinel` card + section is rewritten for the current head, and the audit log records + `sentinel-alert-cleared`. A label a person added, directly or through the + dashboard after the alert, is never removed, and neither is any label when + the hive cannot name its own accounts. +- **Unchanged head:** skipped, as before. + +The dashboard's sentinel state follows the live label plus the findings +recorded for the current head, so it clears with the label. Earlier heads' +findings stay in `/api/sentinel` for audit. + On the dashboard's Projects cards, every open PR that carries the configured sentinel label is drawn as a red pill (status chip and main pill), taking precedence over the held, needs-human and merge colours, and the pill legend diff --git a/src/docs/security-model.md b/src/docs/security-model.md index 4f73cc4a27..5e615d0f07 100644 --- a/src/docs/security-model.md +++ b/src/docs/security-model.md @@ -564,7 +564,14 @@ sensitive paths, owner self-nomination, permission escalation in workflows, secret exposure, CI gate weakening, test removal, security policy edits, and remote code execution patterns. A match applies `sentinel-alert`, posts one comment and writes an audit entry. The label blocks Hive approval and every -automerge lane until a maintainer removes it. +automerge lane until a maintainer removes it, or until a later head matches +no rule. Findings are head-scoped: every new head is evaluated again, and +when the current head is clean Hive removes the label only if Hive itself +added it for an earlier head's finding (its own alert comment names that +head, and the newest label event is Hive's own, made no later than that +comment). A label a person added stays. The earlier finding is kept in the +audit log (`sentinel-alert-cleared` records the removal), `/api/sentinel` +and that head's review evidence bundle. Whether that label and comment reach GitHub is decided by the **write-back containment gate** (`pkg/writeback`): on a PR Hive did not open, sentinel writes need ACMM L5 plus the review opt-in label (L6 without it), the repo diff --git a/src/pkg/dashboard/stage_tracker_sentinel_head_scope_test.go b/src/pkg/dashboard/stage_tracker_sentinel_head_scope_test.go new file mode 100644 index 0000000000..8a51b6229a --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_sentinel_head_scope_test.go @@ -0,0 +1,73 @@ +package dashboard + +import ( + "slices" + "testing" + + "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/sentinel" +) + +// TestStageTrackerSentinelJudgesCurrentHead (hivecommons/hive#19262): the +// tracker's sentinel state belongs to the PR's current head. A finding the +// sweep recorded for an earlier head stays in the /api/sentinel ring for +// audit, but once the sweep has removed its own label for a clean new head +// the row no longer reads "Needs human · sentinel" and names no findings; a +// finding on the new head, or a label a person put on, still flags it. +func TestStageTrackerSentinelJudgesCurrentHead(t *testing.T) { + const ( + repo = "acme/console" + number = 19192 + oldHead = "0bee4e4aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + newHead = "f718e15bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + ) + s := newTestServer() + s.RecordSentinelFinding(github.SentinelSweepEvent{Repo: repo, Number: number, HeadSHA: oldHead, Blocked: true, Findings: []sentinel.Finding{ + {Rule: sentinel.RuleSensitivePath, Summary: "changes 1 sensitive path(s)", Paths: []string{"Makefile"}}, + }}) + + // Old head, label on: flagged, with the old head's details. + alert, _, _, details := s.stageTrackerSentinel(nil, repo, number, oldHead, []string{config.DefaultSentinelLabel}) + if !alert || len(details) != 1 { + t.Fatalf("old head: alert=%v details=%+v", alert, details) + } + + // Clean new head after the sweep removed its label: not flagged, and the + // old head's finding is not shown as this head's. + alert, n, reason, details := s.stageTrackerSentinel(nil, repo, number, newHead, []string{"lgtm"}) + if alert || n != 0 || reason != "" || details != nil { + t.Fatalf("clean new head must not flag: alert=%v n=%d reason=%q details=%+v", alert, n, reason, details) + } + if slices.Contains(stageTrackerHumanGateReasons(StageTrackerItem{Kind: "pr", Head: newHead, SentinelAlert: alert}), gateReasonSentinel) { + t.Fatal("clean new head must not carry the sentinel human gate") + } + if !slices.Contains(stageTrackerHumanGateReasons(StageTrackerItem{Kind: "pr", Head: oldHead, SentinelAlert: true}), gateReasonSentinel) { + t.Fatal("positive control: a flagged head carries the sentinel human gate") + } + + // A label still on the new head (a person's, which the sweep leaves + // alone) keeps the gate. + if alert, _, _, _ := s.stageTrackerSentinel(nil, repo, number, newHead, []string{config.DefaultSentinelLabel}); !alert { + t.Fatal("a sentinel label on the current head must still flag") + } + + // A finding recorded for the new head is the new head's. + s.RecordSentinelFinding(github.SentinelSweepEvent{Repo: repo, Number: number, HeadSHA: newHead, Blocked: true, Findings: []sentinel.Finding{ + {Rule: sentinel.RuleSensitivePath, Summary: "changes 1 sensitive path(s)", Paths: []string{"Makefile"}}, + }}) + if _, _, _, details := s.stageTrackerSentinel(nil, repo, number, newHead, []string{config.DefaultSentinelLabel}); len(details) != 1 { + t.Fatalf("new head finding details=%+v", details) + } + + // History is kept: both heads stay in the ring. + heads := map[string]bool{} + for _, f := range s.sentinelFindings.list() { + if f.Number == number { + heads[f.HeadSHA] = true + } + } + if !heads[oldHead] || !heads[newHead] { + t.Fatalf("ring must keep every head's finding for audit: %v", heads) + } +} diff --git a/src/pkg/github/sentinel_head_scope.go b/src/pkg/github/sentinel_head_scope.go new file mode 100644 index 0000000000..a3aaac635e --- /dev/null +++ b/src/pkg/github/sentinel_head_scope.go @@ -0,0 +1,287 @@ +package github + +import ( + "context" + "fmt" + "strings" + "time" + + gh "github.com/google/go-github/v72/github" + "github.com/hivecommons/hive/pkg/sentinel" + "github.com/hivecommons/hive/pkg/writeback" +) + +// Head-scoped sentinel results (hivecommons/hive#19262). +// +// A sentinel finding belongs to the head it was raised on. Before this, a PR +// that already wore the alert label was never evaluated again, so a finding +// on an early head (a Makefile edit, say) kept the label, the "Needs human · +// sentinel" dashboard state and the status section's "Head matched" +// line on every later head, even a docs-only one. Now every new head is +// evaluated; when the current head matches no rule, the label is removed if +// and only if the hive itself put it there for an earlier head's finding, and +// the hive's sentinel comment and status section say the current head is +// clean. The earlier finding stays in the /api/sentinel ring, the review +// evidence bundle for that head and the audit log. +const ( + // sentinelCleanHeading opens the hive's sentinel comment once the current + // head is clean. It deliberately differs from sentinelAlertHeading so + // sentinelClearedByMaintainer never reads a clean record as a cleared + // alert. + sentinelCleanHeading = "## ✅ Sentinel: current head is clean" + // sentinelEarlierAlertSummary titles the collapsed copy of the earlier + // alert kept in the clean comment for audit. + sentinelEarlierAlertSummary = "Earlier sentinel alert, kept for audit" + // sentinelEarlierAlertTitle replaces the alert heading inside that copy, + // for the same reason sentinelCleanHeading differs from it. + sentinelEarlierAlertTitle = "**Sentinel alert for head `%s`**" + // SentinelAlertClearedAuditAction is the audit-log action for a label the + // sweep removed because the current head is clean. + SentinelAlertClearedAuditAction = "sentinel-alert-cleared" +) + +// sentinelMarkerHead returns the head SHA named by the first +// ` ` marker in body, or "". +func sentinelMarkerHead(body string) string { + _, rest, ok := strings.Cut(body, SentinelMarker+" ") + if !ok { + return "" + } + fields := strings.Fields(rest) + if len(fields) == 0 { + return "" + } + return fields[0] +} + +// SentinelCleanComment is the body the hive's sentinel comment is rewritten +// to when head matches no rule after an earlier head was alerted on. It +// carries the marker for head (so a restart finds it and the head stays +// judged) and a collapsed copy of the earlier alert, with its marker and +// heading neutralised, for audit. +func SentinelCleanComment(head, label, priorHead, priorBody string) string { + var b strings.Builder + b.WriteString(SentinelMarker + " " + head + "\n") + b.WriteString(sentinelCleanHeading + "\n\n") + fmt.Fprintf(&b, "Head `%s` matches no sentinel rule, so Hive removed the `%s` label it added for the finding on an earlier head (`%s`). Hive evaluates every new push again; the earlier finding stays in the dashboard Security tab and `/api/sentinel`.\n", shortSHA(head), label, shortSHA(priorHead)) + earlier := sentinelEarlierAlertBody(priorBody, priorHead) + if earlier != "" { + fmt.Fprintf(&b, "\n
%s\n\n%s\n\n
\n", sentinelEarlierAlertSummary, earlier) + } + return b.String() +} + +// sentinelEarlierAlertBody is priorBody without its marker lines and with +// the alert heading replaced, so the copy can never be read back as the +// hive's alert for any head. +func sentinelEarlierAlertBody(priorBody, priorHead string) string { + lines := strings.Split(priorBody, "\n") + out := make([]string, 0, len(lines)) + for _, line := range lines { + if strings.Contains(line, SentinelMarker) { + continue + } + if strings.Contains(line, sentinelAlertHeading) { + line = fmt.Sprintf(sentinelEarlierAlertTitle, shortSHA(priorHead)) + } + out = append(out, line) + } + return strings.TrimSpace(strings.Join(out, "\n")) +} + +// SentinelCleanStatusSection is the quiet-mode `sentinel` status section for +// a head that matches no rule after an earlier head's notice. It carries the +// notice marker for head so the section always names the head it describes. +func SentinelCleanStatusSection(head string) string { + return fmt.Sprintf("%s %s -->\n✅ **Sentinel:** head `%s` matches no sentinel rule. An earlier head's finding stays in the dashboard Security tab and `/api/sentinel`.", SentinelNoticeCardMarker, head, shortSHA(head)) +} + +// markSentinelNoticeSectionClean rewrites an existing quiet-mode sentinel +// section that describes an earlier head so it says head is clean. It never +// creates a status card or a section: a PR the sentinel never noticed stays +// untouched. Best effort, like clearSentinelNoticeSection. +func (c *Client) markSentinelNoticeSectionClean(ctx context.Context, repo string, number int, head string) { + if !c.notificationsQuiet() || strings.TrimSpace(head) == "" { + return + } + render := func(previous string) string { + if strings.TrimSpace(previous) == "" || strings.Contains(previous, SentinelNoticeCardMarker+" "+head+" ") { + return previous + } + return SentinelCleanStatusSection(head) + } + if _, err := c.UpsertPRStatusSectionFunc(ctx, repo, number, SentinelStatusKey, render); err != nil { + c.logger.Warn("sentinel: marking status-card section clean failed", "repo", repo, "number", number, "error", err) + } +} + +// sentinelLabelAddedByHive reports whether the newest label event for label +// on the PR is a `labeled` by one of the hive's own accounts at or before +// notAfter (the hive's alert comment's last write: the sweep adds the label +// and then writes the comment). A label a person added, directly or through +// the dashboard after the alert, fails one of those tests and is left alone. +// A hive that cannot name its accounts, or a zero notAfter, never matches: +// not knowing who added the label is never a reason to remove it. +func (c *Client) sentinelLabelAddedByHive(ctx context.Context, owner, repo string, number int, label string, notAfter time.Time) (bool, error) { + if !c.knowsOwnAccounts() || notAfter.IsZero() { + return false, nil + } + opts := &gh.ListOptions{PerPage: labelTimelinePageSize} + var ( + lastKind string + lastActor *gh.User + lastAt time.Time + ) + for { + page, resp, err := c.client.Issues.ListIssueTimeline(ctx, owner, repo, number, opts) + if err != nil { + return false, fmt.Errorf("reading timeline of %s/%s#%d for sentinel label provenance: %w", owner, repo, number, err) + } + for _, ev := range page { + if ev == nil { + continue + } + kind := strings.ToLower(ev.GetEvent()) + if kind != "labeled" && kind != "unlabeled" { + continue + } + if !strings.EqualFold(strings.TrimSpace(ev.GetLabel().GetName()), label) { + continue + } + at := ev.GetCreatedAt().Time + if at.IsZero() || at.Before(lastAt) { + continue + } + lastKind, lastActor, lastAt = kind, ev.GetActor(), at + } + if resp == nil || resp.NextPage == 0 { + break + } + opts.Page = resp.NextPage + } + if lastKind != "labeled" || lastActor == nil || !c.isHiveAccount(lastActor) { + return false, nil + } + return !lastAt.After(notAfter), nil +} + +// sentinelCommentWrittenAt is the comment's last write time: updated_at, +// falling back to created_at. +func sentinelCommentWrittenAt(comment *gh.IssueComment) time.Time { + if comment == nil { + return time.Time{} + } + if at := comment.GetUpdatedAt().Time; !at.IsZero() { + return at + } + return comment.GetCreatedAt().Time +} + +// clearStaleSentinelAlert handles a labelled PR whose current head matches +// no rule. It removes the label only when all of these hold: the hive can +// name its own accounts, the hive's own sentinel comment is a blocking alert +// for an earlier head, and the newest label event is the hive's own +// `labeled`, made no later than that comment. It then rewrites the comment +// (SentinelCleanComment) and the quiet-mode status section. cleared is false, +// with nothing written, in every other case, including a write-back gate +// refusal. +func (c *Client) clearStaleSentinelAlert(ctx context.Context, displayRepo, owner, repo string, pr *gh.PullRequest, label string) (SentinelSweepEvent, bool, error) { + number := pr.GetNumber() + head := pr.GetHead().GetSHA() + if head == "" || !c.knowsOwnAccounts() { + return SentinelSweepEvent{}, false, nil + } + prior, found, err := c.findOwnMarkerComment(ctx, owner, repo, number, SentinelMarker) + if err != nil { + return SentinelSweepEvent{}, false, err + } + if !found || prior == nil || !strings.Contains(prior.GetBody(), sentinelAlertHeading) { + return SentinelSweepEvent{}, false, nil + } + priorHead := sentinelMarkerHead(prior.GetBody()) + if priorHead == "" || strings.EqualFold(priorHead, head) { + return SentinelSweepEvent{}, false, nil + } + hiveAdded, err := c.sentinelLabelAddedByHive(ctx, owner, repo, number, label, sentinelCommentWrittenAt(prior)) + if err != nil { + return SentinelSweepEvent{}, false, err + } + if !hiveAdded { + return SentinelSweepEvent{}, false, nil + } + body := SentinelCleanComment(head, label, priorHead, prior.GetBody()) + if d := c.WritebackAllowed(displayRepo, c.sentinelWritebackItem(pr), writeback.KindSentinel, body); !d.Allowed { + return SentinelSweepEvent{}, false, nil + } + resp, err := c.client.Issues.RemoveLabelForIssue(ctx, owner, repo, number, label) // writeback:gated + c.noteWritebackOutcome(displayRepo, resp, err) + if err != nil { + return SentinelSweepEvent{}, false, fmt.Errorf("removing %s label from a clean head: %w", label, err) + } + if _, _, err := c.client.Issues.EditComment(ctx, owner, repo, prior.GetID(), &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { // writeback:gated + return SentinelSweepEvent{}, false, fmt.Errorf("updating sentinel comment for a clean head: %w", err) + } + c.noteCommentEdited() + c.markSentinelNoticeSectionClean(ctx, displayRepo, number, head) + return SentinelSweepEvent{ + Number: number, + Author: pr.GetUser().GetLogin(), + Title: pr.GetTitle(), + HeadSHA: head, + Cleared: true, + ClearedHead: priorHead, + }, true, nil +} + +// trySentinelLabelledHead evaluates a new head of a PR that already wears the +// alert label on the blocking path. A clean head goes to +// clearStaleSentinelAlert. A head with findings keeps the label (it is +// already on, so nothing is added) and the hive's sentinel comment is +// rewritten as the alert for this head, so the explanation always names the +// current head. A head the hive already wrote a sentinel comment for, or a +// labelled PR with no sentinel comment of the hive's (the label came from +// somewhere else), is left as it is. +func (c *Client) trySentinelLabelledHead(ctx context.Context, displayRepo, owner, repo string, pr *gh.PullRequest, label string, decision SentinelDecision, opts SentinelSweepOptions) (SentinelSweepEvent, bool, error) { + number := pr.GetNumber() + head := pr.GetHead().GetSHA() + author := pr.GetUser().GetLogin() + files, err := listPRFilesWithPatch(ctx, c.client, owner, repo, pr) + if err != nil { + return SentinelSweepEvent{}, false, err + } + if opts.PatchObserver != nil { + c.observeSentinelPatch(ctx, owner, repo, pr, files, opts.PatchObserver) + } + findings := sentinel.Evaluate(sentinel.PR{Author: author, Title: pr.GetTitle(), Files: files}, opts.Evaluator) + if len(findings) == 0 { + return c.clearStaleSentinelAlert(ctx, displayRepo, owner, repo, pr, label) + } + body := SentinelComment(decision, head, author, findings) + event := SentinelSweepEvent{Number: number, Author: author, Title: pr.GetTitle(), HeadSHA: head, Findings: findings, Blocked: decision.Block, TrustedReason: decision.TrustedReason} + if d := c.WritebackAllowed(displayRepo, c.sentinelWritebackItem(pr), writeback.KindSentinel, body); !d.Allowed { + event.Suppressed = true + event.SuppressedReason = d.Reason + return event, true, nil + } + target, posted, err := c.findOwnMarkerComment(ctx, owner, repo, number, SentinelMarker+" "+head) + if err != nil { + return SentinelSweepEvent{}, false, err + } + if posted || !c.knowsOwnAccounts() { + // The hive already wrote for this head, or cannot tell its own + // comment from a forged one: the label holds, nothing to rewrite. + return SentinelSweepEvent{}, false, nil + } + if target, posted, err = c.findOwnMarkerComment(ctx, owner, repo, number, SentinelMarker); err != nil { + return SentinelSweepEvent{}, false, err + } + if !posted || target == nil { + return SentinelSweepEvent{}, false, nil + } + if _, _, err := c.client.Issues.EditComment(ctx, owner, repo, target.GetID(), &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { // writeback:gated + return SentinelSweepEvent{}, false, fmt.Errorf("updating sentinel alert for a new head: %w", err) + } + c.noteCommentEdited() + c.clearSentinelNoticeSection(ctx, displayRepo, number) + return event, true, nil +} diff --git a/src/pkg/github/sentinel_head_scope_test.go b/src/pkg/github/sentinel_head_scope_test.go new file mode 100644 index 0000000000..0cfdd164fa --- /dev/null +++ b/src/pkg/github/sentinel_head_scope_test.go @@ -0,0 +1,259 @@ +package github + +// Tests for hivecommons/hive#19262: the sentinel judges the PR's current +// head. A finding on an earlier head no longer keeps the alert label, the +// hive's comment or the status section on a later clean head; a finding on +// the new head keeps the label; a label a person added is never removed. + +import ( + "context" + "strings" + "testing" + + gh "github.com/google/go-github/v72/github" + "github.com/hivecommons/hive/pkg/prstatus" + "github.com/hivecommons/hive/pkg/sentinel" +) + +const ( + headScopeBot = "hive[bot]" + headScopeOld = "0bee4e4aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + headScopeNew = "f718e15bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + headScopeNumber = 19192 + headScopeLabelAt = "2026-11-18T10:00:00Z" + headScopeAlertAt = "2026-11-18T10:00:05Z" + headScopeLaterAt = "2026-11-18T12:00:00Z" + headScopeDocsFile = "docs/guide.md" +) + +func headScopeOldAlert() string { + return SentinelComment(DecideSentinelAction("sentinel-alert", SentinelAuthorTrust{}, false), headScopeOld, "eve", + []sentinel.Finding{{Rule: sentinel.RuleSensitivePath, Summary: "changes 1 sensitive path(s)", Paths: []string{"Makefile"}}}) +} + +func headScopeFiles(path string) map[int][]map[string]any { + return map[int][]map[string]any{headScopeNumber: {{ + "filename": path, "status": "modified", "additions": 1, "deletions": 0, "patch": "@@ -1 +1 @@\n-a\n+b\n", + }}} +} + +// headScopeFixture is a PR still labelled for a finding on headScopeOld, now +// at headScopeNew with files, labelled at labelAt by labelActor. +func headScopeFixture(path, labelActor, labelActorType, labelAt string) *sentinelFixture { + return &sentinelFixture{ + prs: []map[string]any{sentinelPR(headScopeNumber, "eve", headScopeNew, "sentinel-alert")}, + files: headScopeFiles(path), + labelExists: true, + comments: map[int][]string{headScopeNumber: {headScopeOldAlert()}}, + commentUsers: map[int][]string{headScopeNumber: {headScopeBot}}, + commentUpdated: map[int][]string{headScopeNumber: {headScopeAlertAt}}, + timeline: map[int][]map[string]any{headScopeNumber: { + sentinelTimelineLabel("labeled", labelActor, labelActorType, labelAt), + }}, + } +} + +func TestSweepSentinelCleanNewHeadClearsHiveAddedLabel(t *testing.T) { + f := headScopeFixture(headScopeDocsFile, headScopeBot, "Bot", headScopeLabelAt) + srv := newSentinelServer(t, f) + defer srv.Close() + c := newTestClient(t, srv, "o", []string{"o/r"}) + c.SetAppBotLogin(headScopeBot) + + var audited []SentinelSweepEvent + res, err := c.SweepSentinel(context.Background(), defaultSentinelOpts(func(e SentinelSweepEvent) { audited = append(audited, e) })) + if err != nil { + t.Fatalf("sweep: %v", err) + } + if len(res.Cleared) != 1 || len(res.Flagged) != 0 || len(res.Errors) != 0 { + t.Fatalf("clean new head must clear the hive's label: res=%+v", res) + } + ev := res.Cleared[0] + if ev.HeadSHA != headScopeNew || ev.ClearedHead != headScopeOld || len(ev.Findings) != 0 || !ev.Cleared { + t.Fatalf("cleared event=%+v", ev) + } + if len(audited) != 1 || !audited[0].Cleared { + t.Fatalf("the clearance must reach the audit hook: %+v", audited) + } + if len(f.removed) != 1 || f.removed[0] != "19192|sentinel-alert" { + t.Fatalf("removed=%v", f.removed) + } + if len(f.labels[headScopeNumber]) != 0 { + t.Fatalf("no label may be added on a clean head: %v", f.labels[headScopeNumber]) + } + if len(f.comments[headScopeNumber]) != 1 { + t.Fatalf("the hive's comment is edited, never a new one: %v", f.comments[headScopeNumber]) + } + body := f.comments[headScopeNumber][0] + for _, want := range []string{SentinelMarker + " " + headScopeNew, sentinelCleanHeading, sentinelEarlierAlertSummary, "`Makefile`", shortSHA(headScopeOld)} { + if !strings.Contains(body, want) { + t.Errorf("clean comment missing %q:\n%s", want, body) + } + } + if strings.Contains(body, sentinelAlertHeading) || strings.Contains(body, SentinelMarker+" "+headScopeOld) { + t.Fatalf("the kept history must not read back as an alert:\n%s", body) + } + if sentinelClearedByMaintainer(&gh.IssueComment{Body: gh.Ptr(body)}, true) { + t.Fatal("a clean record must never count as a maintainer clearance") + } + + // Same head again: judged already, nothing more is written. + res, err = c.SweepSentinel(context.Background(), defaultSentinelOpts(nil)) + if err != nil || len(res.Cleared) != 0 || len(f.removed) != 1 { + t.Fatalf("unchanged head must stay quiet: res=%+v err=%v removed=%v", res, err, f.removed) + } +} + +func TestSweepSentinelFindingOnNewHeadKeepsLabel(t *testing.T) { + f := headScopeFixture("Makefile", headScopeBot, "Bot", headScopeLabelAt) + srv := newSentinelServer(t, f) + defer srv.Close() + c := newTestClient(t, srv, "o", []string{"o/r"}) + c.SetAppBotLogin(headScopeBot) + + res, err := c.SweepSentinel(context.Background(), defaultSentinelOpts(nil)) + if err != nil { + t.Fatalf("sweep: %v", err) + } + if len(res.Flagged) != 1 || len(res.Cleared) != 0 || res.Flagged[0].HeadSHA != headScopeNew { + t.Fatalf("finding on the new head must stay flagged: res=%+v", res) + } + if len(f.removed) != 0 { + t.Fatalf("label must stay on: removed=%v", f.removed) + } + if len(f.labels[headScopeNumber]) != 0 { + t.Fatalf("label is already on, nothing to add: %v", f.labels[headScopeNumber]) + } + if len(f.comments[headScopeNumber]) != 1 { + t.Fatalf("comments=%v", f.comments[headScopeNumber]) + } + body := f.comments[headScopeNumber][0] + if !strings.Contains(body, SentinelMarker+" "+headScopeNew) || !strings.Contains(body, sentinelAlertHeading) || strings.Contains(body, SentinelMarker+" "+headScopeOld) { + t.Fatalf("the alert must be rewritten for the current head:\n%s", body) + } + + // An unlabelled PR with a finding on its new head gets the label. + f2 := headScopeFixture("Makefile", headScopeBot, "Bot", headScopeLabelAt) + f2.prs = []map[string]any{sentinelPR(headScopeNumber, "eve", headScopeNew)} + f2.timeline = nil + srv2 := newSentinelServer(t, f2) + defer srv2.Close() + c2 := newTestClient(t, srv2, "o", []string{"o/r"}) + c2.SetAppBotLogin(headScopeBot) + res, err = c2.SweepSentinel(context.Background(), defaultSentinelOpts(nil)) + if err != nil || len(res.Flagged) != 1 || len(f2.labels[headScopeNumber]) != 1 { + t.Fatalf("finding on a new unlabelled head must add the label: res=%+v err=%v labels=%v", res, err, f2.labels[headScopeNumber]) + } +} + +func TestSweepSentinelCleanNewHeadLeavesLabelItCannotAttribute(t *testing.T) { + cases := []struct { + name string + fixture func() *sentinelFixture + knowsSelf bool + }{ + {"label added by a person", func() *sentinelFixture { + return headScopeFixture(headScopeDocsFile, "maintainer", "User", headScopeLabelAt) + }, true}, + {"label re-added through the hive after the alert", func() *sentinelFixture { + return headScopeFixture(headScopeDocsFile, headScopeBot, "Bot", headScopeLaterAt) + }, true}, + {"no hive alert comment", func() *sentinelFixture { + f := headScopeFixture(headScopeDocsFile, headScopeBot, "Bot", headScopeLabelAt) + f.comments = nil + f.commentUsers = nil + f.commentUpdated = nil + return f + }, true}, + {"alert comment has no timestamp", func() *sentinelFixture { + f := headScopeFixture(headScopeDocsFile, headScopeBot, "Bot", headScopeLabelAt) + f.commentUpdated = nil + return f + }, true}, + {"hive cannot name its accounts", func() *sentinelFixture { + return headScopeFixture(headScopeDocsFile, headScopeBot, "Bot", headScopeLabelAt) + }, false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + f := tc.fixture() + before := append([]string(nil), f.comments[headScopeNumber]...) + srv := newSentinelServer(t, f) + defer srv.Close() + c := newTestClient(t, srv, "o", []string{"o/r"}) + if tc.knowsSelf { + c.SetAppBotLogin(headScopeBot) + } + res, err := c.SweepSentinel(context.Background(), defaultSentinelOpts(nil)) + if err != nil || len(res.Cleared) != 0 || len(res.Flagged) != 0 { + t.Fatalf("res=%+v err=%v", res, err) + } + if len(f.removed) != 0 { + t.Fatalf("a label the hive cannot attribute to its own earlier alert must stay: removed=%v", f.removed) + } + if got := f.comments[headScopeNumber]; strings.Join(got, "\x00") != strings.Join(before, "\x00") { + t.Fatalf("comments must be untouched: %v", got) + } + }) + } +} + +// TestSentinelQuietTrustedNoticeSectionClearsOnCleanHead: the status card's +// sentinel section named an earlier head's finding ("Head matched"); +// a clean new head rewrites it for the current head, and a PR without a +// card never gets one. +func TestSentinelQuietTrustedNoticeSectionClearsOnCleanHead(t *testing.T) { + f := &sentinelFixture{ + prs: []map[string]any{sentinelPR(31, "hivecommons-hive[bot]", "head1aaaaaaa")}, + files: sentinelWorkflowFiles(31), + } + srv := newSentinelServer(t, f) + defer srv.Close() + c := quietSentinelClient(t, srv, true) + if _, err := c.SweepSentinel(context.Background(), trustedSentinelOpts()); err != nil { + t.Fatalf("sweep: %v", err) + } + if len(f.comments[31]) != 1 { + t.Fatalf("want the status card: %v", f.comments[31]) + } + + f.mu.Lock() + f.commentUsers = map[int][]string{31: {sentinelCardBot}} + f.prs[0]["head"] = map[string]string{"sha": "head2bbbbbbb"} + f.files[31] = []map[string]any{{"filename": "README.md", "status": "modified", "patch": "+docs\n"}} + f.mu.Unlock() + if _, err := c.SweepSentinel(context.Background(), trustedSentinelOpts()); err != nil { + t.Fatalf("sweep 2: %v", err) + } + if len(f.comments[31]) != 1 { + t.Fatalf("the card is edited in place: %v", f.comments[31]) + } + section, ok := prstatus.Get(f.comments[31][0], SentinelStatusKey) + if !ok || !strings.Contains(section, SentinelNoticeCardMarker+" head2bbbbbbb") || strings.Contains(section, "head1aaaaaaa") || strings.Contains(section, "matched") { + t.Fatalf("section must describe the clean current head:\n%s", section) + } + + // A trusted author's clean PR with no card stays without one. + g := &sentinelFixture{ + prs: []map[string]any{sentinelPR(32, "hivecommons-hive[bot]", "head3cccccccc")}, + files: map[int][]map[string]any{32: {{"filename": "README.md", "status": "modified", "patch": "+docs\n"}}}, + } + srv2 := newSentinelServer(t, g) + defer srv2.Close() + c2 := quietSentinelClient(t, srv2, true) + if _, err := c2.SweepSentinel(context.Background(), trustedSentinelOpts()); err != nil { + t.Fatalf("sweep clean: %v", err) + } + if len(g.comments[32]) != 0 { + t.Fatalf("a clean PR must not get a card: %v", g.comments[32]) + } +} + +func TestSentinelMarkerHead(t *testing.T) { + if got := sentinelMarkerHead(SentinelMarker + " abc123\n## x"); got != "abc123" { + t.Fatalf("got %q", got) + } + if got := sentinelMarkerHead("no marker"); got != "" { + t.Fatalf("got %q", got) + } +} diff --git a/src/pkg/github/sentinel_sweep.go b/src/pkg/github/sentinel_sweep.go index 14f04cec70..bb80971c25 100644 --- a/src/pkg/github/sentinel_sweep.go +++ b/src/pkg/github/sentinel_sweep.go @@ -238,6 +238,12 @@ type SentinelSweepEvent struct { Suppressed bool // SuppressedReason is the gate's reason when Suppressed. SuppressedReason string + // Cleared is set when HeadSHA matched no rule and the sweep removed the + // alert label the hive itself added for an earlier head's finding + // (hivecommons/hive#19262). Findings is empty; ClearedHead names the + // earlier head, whose finding stays recorded for audit. + Cleared bool + ClearedHead string } // Rules lists the triggered rule names. @@ -249,6 +255,9 @@ type SentinelSweepResult struct { Flagged []SentinelSweepEvent Notified []SentinelSweepEvent Remediated []SentinelSweepEvent + // Cleared lists PRs whose hive-added alert label was removed because + // the current head is clean (SentinelSweepEvent.Cleared). + Cleared []SentinelSweepEvent // Suppressed lists findings the write-back gate kept off GitHub // (dashboard/API only). Suppressed []SentinelSweepEvent @@ -265,7 +274,7 @@ type SentinelSweepResult struct { } func (r *SentinelSweepResult) actions() int { - return len(r.Flagged) + len(r.Notified) + len(r.Remediated) + return len(r.Flagged) + len(r.Notified) + len(r.Remediated) + len(r.Cleared) } // sentinelHeadsSeen remembers the head SHA each PR was last evaluated at so @@ -291,6 +300,19 @@ func (s *sentinelHeadsSeen) isSeen(key, head string) bool { return ok && prev == head && head != "" } +// forget drops key so its head is evaluated again on the next pass: a +// labelled PR whose evaluation failed must not stay judged on a head the +// sweep never finished reading. +func (s *sentinelHeadsSeen) forget(key string) { + s.mu.Lock() + defer s.mu.Unlock() + if _, ok := s.seen[key]; !ok { + return + } + delete(s.seen, key) + s.saveLocked() +} + func (s *sentinelHeadsSeen) unchanged(key, head string) bool { s.mu.Lock() defer s.mu.Unlock() @@ -630,6 +652,14 @@ func (c *Client) sentinelEvaluatePR(ctx context.Context, result *SentinelSweepRe return } event.Repo = repo + if event.Cleared { + result.Cleared = append(result.Cleared, event) + result.ReposHit[repo]++ + if opts.Audit != nil { + opts.Audit(event) + } + return + } c.recordReviewEvidenceSentinel(repo, pr, event.Findings, event.Blocked, time.Now()) if event.Suppressed { result.Suppressed = append(result.Suppressed, event) @@ -664,8 +694,18 @@ func (c *Client) trySentinelPR(ctx context.Context, displayRepo, owner, repo str return SentinelSweepEvent{}, false, nil } if hasAlertLabel && decision.Block { - // Already alerted on; a maintainer has not cleared it yet. - return SentinelSweepEvent{}, false, nil + // The label is on. It used to end the evaluation here for good, so + // a finding on an early head kept the label on every later head + // (hivecommons/hive#19262). Now only a head this sweep already + // evaluated is skipped; a new head is judged on its own files. + if c.sentinelHeads.unchanged(key, head) { + return SentinelSweepEvent{}, false, nil + } + event, acted, err := c.trySentinelLabelledHead(ctx, displayRepo, owner, repo, pr, label, decision, opts) + if err != nil { + c.sentinelHeads.forget(key) + } + return event, acted, err } files, err := listPRFilesWithPatch(ctx, c.client, owner, repo, pr) if err != nil { @@ -676,6 +716,25 @@ func (c *Client) trySentinelPR(ctx context.Context, displayRepo, owner, repo str } findings := sentinel.Evaluate(sentinel.PR{Author: author, Title: pr.GetTitle(), Files: files}, opts.Evaluator) if len(findings) == 0 { + if hasAlertLabel { + // A trusted author's PR still wearing a label the hive added + // for an earlier head (before the author was trusted, say). + // Judged once per head, like the blocking path. + if c.sentinelHeads.unchanged(key, head) { + return SentinelSweepEvent{}, false, nil + } + event, acted, err := c.clearStaleSentinelAlert(ctx, displayRepo, owner, repo, pr, label) + if err != nil { + c.sentinelHeads.forget(key) + } + return event, acted, err + } + if !decision.Block { + // Only a trusted author's finding is folded into the status + // card, so only their PRs can carry a section naming an older + // head. + c.markSentinelNoticeSectionClean(ctx, displayRepo, number, head) + } return SentinelSweepEvent{}, false, nil } event := SentinelSweepEvent{Number: number, Author: author, Title: pr.GetTitle(), HeadSHA: head, Findings: findings, Blocked: decision.Block, TrustedReason: decision.TrustedReason} diff --git a/src/pkg/github/sentinel_sweep_test.go b/src/pkg/github/sentinel_sweep_test.go index ce53e97d5f..799dbdc616 100644 --- a/src/pkg/github/sentinel_sweep_test.go +++ b/src/pkg/github/sentinel_sweep_test.go @@ -35,6 +35,9 @@ type sentinelFixture struct { // comments[num][i]; absent entries render a comment with no user, which // is how the fixture started and what the any-author fallback tests use. commentUsers map[int][]string + // commentUpdated[num][i] is the RFC3339 updated_at the fixture reports + // for comments[num][i]; absent entries render no timestamps. + commentUpdated map[int][]string // timeline[num] is the PR's issue timeline as GitHub would render it // (label events with actor and created_at, committed events with a // committer date, head_ref_force_pushed events); absent means empty. @@ -110,6 +113,10 @@ func newSentinelServer(t *testing.T, f *sentinelFixture) *httptest.Server { if users := f.commentUsers[num]; i < len(users) && users[i] != "" { entry["user"] = map[string]string{"login": users[i]} } + if times := f.commentUpdated[num]; i < len(times) && times[i] != "" { + entry["created_at"] = times[i] + entry["updated_at"] = times[i] + } out = append(out, entry) } _ = json.NewEncoder(w).Encode(out) From 9dc6d5fe671d3d921d8cb9d52962d0014de28f6b Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Thu, 19 Nov 2026 11:48:22 -0500 Subject: [PATCH 2/2] fix(sentinel): drop unused marker read, cover head-scoped branches Refs #19262 Signed-off-by: Andy Anderson --- src/pkg/github/sentinel_head_scope.go | 7 +- src/pkg/github/sentinel_head_scope_test.go | 85 ++++++++++++++++++++++ 2 files changed, 89 insertions(+), 3 deletions(-) diff --git a/src/pkg/github/sentinel_head_scope.go b/src/pkg/github/sentinel_head_scope.go index a3aaac635e..f5e8377448 100644 --- a/src/pkg/github/sentinel_head_scope.go +++ b/src/pkg/github/sentinel_head_scope.go @@ -263,7 +263,7 @@ func (c *Client) trySentinelLabelledHead(ctx context.Context, displayRepo, owner event.SuppressedReason = d.Reason return event, true, nil } - target, posted, err := c.findOwnMarkerComment(ctx, owner, repo, number, SentinelMarker+" "+head) + _, posted, err := c.findOwnMarkerComment(ctx, owner, repo, number, SentinelMarker+" "+head) if err != nil { return SentinelSweepEvent{}, false, err } @@ -272,10 +272,11 @@ func (c *Client) trySentinelLabelledHead(ctx context.Context, displayRepo, owner // comment from a forged one: the label holds, nothing to rewrite. return SentinelSweepEvent{}, false, nil } - if target, posted, err = c.findOwnMarkerComment(ctx, owner, repo, number, SentinelMarker); err != nil { + target, found, err := c.findOwnMarkerComment(ctx, owner, repo, number, SentinelMarker) + if err != nil { return SentinelSweepEvent{}, false, err } - if !posted || target == nil { + if !found || target == nil { return SentinelSweepEvent{}, false, nil } if _, _, err := c.client.Issues.EditComment(ctx, owner, repo, target.GetID(), &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { // writeback:gated diff --git a/src/pkg/github/sentinel_head_scope_test.go b/src/pkg/github/sentinel_head_scope_test.go index 0cfdd164fa..3e4ca75080 100644 --- a/src/pkg/github/sentinel_head_scope_test.go +++ b/src/pkg/github/sentinel_head_scope_test.go @@ -7,8 +7,10 @@ package github import ( "context" + "net/http" "strings" "testing" + "time" gh "github.com/google/go-github/v72/github" "github.com/hivecommons/hive/pkg/prstatus" @@ -257,3 +259,86 @@ func TestSentinelMarkerHead(t *testing.T) { t.Fatalf("got %q", got) } } + +// A trusted author's PR still wearing the label the hive added for an +// earlier head is cleared the same way on a clean head, once per head. +func TestSweepSentinelTrustedCleanHeadClearsHiveLabel(t *testing.T) { + f := headScopeFixture(headScopeDocsFile, headScopeBot, "Bot", headScopeLabelAt) + srv := newSentinelServer(t, f) + defer srv.Close() + c := newTestClient(t, srv, "o", []string{"o/r"}) + c.SetAppBotLogin(headScopeBot) + opts := defaultSentinelOpts(nil) + opts.TrustedAuthor = func(repo, author string) SentinelAuthorTrust { + return SentinelAuthorTrust{Trusted: true, Reason: "hive agent"} + } + res, err := c.SweepSentinel(context.Background(), opts) + if err != nil || len(res.Cleared) != 1 || len(f.removed) != 1 { + t.Fatalf("res=%+v err=%v removed=%v", res, err, f.removed) + } + res, err = c.SweepSentinel(context.Background(), opts) + if err != nil || len(res.Cleared) != 0 || len(f.removed) != 1 { + t.Fatalf("unchanged head must stay quiet: res=%+v err=%v removed=%v", res, err, f.removed) + } +} + +// The alert already names the current head (a restart before the heads map +// was persisted): nothing is removed or rewritten. +func TestSweepSentinelCleanHeadAlertForSameHeadUntouched(t *testing.T) { + f := headScopeFixture(headScopeDocsFile, headScopeBot, "Bot", headScopeLabelAt) + f.prs = []map[string]any{sentinelPR(headScopeNumber, "eve", headScopeOld, "sentinel-alert")} + srv := newSentinelServer(t, f) + defer srv.Close() + c := newTestClient(t, srv, "o", []string{"o/r"}) + c.SetAppBotLogin(headScopeBot) + res, err := c.SweepSentinel(context.Background(), defaultSentinelOpts(nil)) + if err != nil || len(res.Cleared) != 0 || len(f.removed) != 0 || f.comments[headScopeNumber][0] != headScopeOldAlert() { + t.Fatalf("res=%+v err=%v removed=%v", res, err, f.removed) + } +} + +// A failed files read on a labelled PR forgets the head, so the next pass +// reads it again instead of leaving the old head's label judged forever. +func TestSweepSentinelLabelledHeadErrorRetries(t *testing.T) { + f := headScopeFixture(headScopeDocsFile, headScopeBot, "Bot", headScopeLabelAt) + f.filesStatus = http.StatusInternalServerError + srv := newSentinelServer(t, f) + defer srv.Close() + c := newTestClient(t, srv, "o", []string{"o/r"}) + c.SetAppBotLogin(headScopeBot) + res, err := c.SweepSentinel(context.Background(), defaultSentinelOpts(nil)) + if err != nil || len(res.Errors) != 1 || len(f.removed) != 0 { + t.Fatalf("res=%+v err=%v", res, err) + } + f.mu.Lock() + f.filesStatus = 0 + f.mu.Unlock() + res, err = c.SweepSentinel(context.Background(), defaultSentinelOpts(nil)) + if err != nil || len(res.Cleared) != 1 || len(f.removed) != 1 { + t.Fatalf("retry must clear: res=%+v err=%v removed=%v", res, err, f.removed) + } +} + +func TestSentinelHeadScopeHelpers(t *testing.T) { + if !sentinelCommentWrittenAt(nil).IsZero() { + t.Fatal("nil comment has no write time") + } + created := gh.Timestamp{Time: time.Date(2026, 11, 18, 10, 0, 0, 0, time.UTC)} + if got := sentinelCommentWrittenAt(&gh.IssueComment{CreatedAt: &created}); !got.Equal(created.Time) { + t.Fatalf("created_at fallback = %v", got) + } + body := SentinelCleanComment(headScopeNew, "sentinel-alert", headScopeOld, "") + if strings.Contains(body, sentinelEarlierAlertSummary) || !strings.Contains(body, sentinelCleanHeading) { + t.Fatalf("empty history renders no block:\n%s", body) + } + if got := sentinelMarkerHead(SentinelMarker + " "); got != "" { + t.Fatalf("bare marker head = %q", got) + } + var s sentinelHeadsSeen + s.forget("missing") + s.unchanged("k", "h") + s.forget("k") + if s.isSeen("k", "h") { + t.Fatal("forget must drop the head") + } +}