Skip to content

✨ feat(github): the hive files grouped issues from GitHub code scanning alerts (opt-in per repo) - #17130

Merged
hivecommons-hive[bot] merged 5 commits into
hivecommons:v6from
Danathar:feat/code-scanning-issues
Nov 8, 2026
Merged

hivecommons-hive[bot] merged 5 commits into
hivecommons:v6from
Danathar:feat/code-scanning-issues

Conversation

@Danathar

@Danathar Danathar commented Nov 7, 2026

Copy link
Copy Markdown
Contributor

Summary

The hive can now turn a repository's open GitHub code scanning alerts (CodeQL, OSSF Scorecard, Trivy, any SARIF uploader) into hive issues the lanes pick up. It is off by default and turned on per repo with code_scanning.repos.<repo>.enabled: true. An hourly sweep groups alerts into issues sized for one PR, files at most five new ones per repo per pass, updates them as alerts are added, fixed or dismissed, and closes them when every alert is gone. The dedupe state is a hidden marker on the hive's own issues, so a restart rebuilds it from GitHub. It needs the App permission Code scanning alerts: Read-only; without it the dashboard shows a notice for that repo and the sweep backs off.

Why

Nothing in v5 or v6 reads code scanning alerts today. The only code-scanning code is Sentinel treating CodeQL config edits as sensitive (src/pkg/sentinel/sentinel.go:58-103) and the merge gate reading CodeQL check results. I found no open or closed hivecommons/hive issue or PR covering this (searched "code scanning", "codeql", "sarif", "security alerts", "code-scanning", "security_events").

Two real cases shaped it:

  • Danathar/exult carries upstream's CodeQL workflow (security-extended,security-and-quality) and shows 697 open alerts: 11 critical, 73 high, and 613 quality findings (mostly note). The owner triaged the 84 critical/high ones into issues by hand.
  • projectbluefin (7 repos, 129 open alerts) is almost all OSSF Scorecard, plus 3 Trivy CVEs. Most Scorecard rules there score repo settings (branch protection, code review, fuzzing, SAST, the CII badge), which no PR can fix; TokenPermissionsID and PinnedDependenciesID are real work in workflow files.

What changes

Config (code_scanning, YAML-only for now): enabled (default off), interval (1h), min_severity (high), include_tools, exclude_rules, max_new_issues_per_run (5), and repos.<repo>.* overrides. Validated at load (unknown repo, bad severity, bad pattern, negative cap, interval under 10m).

Severity. One scale. A security rule's security_severity_level maps to itself; a rule without one uses its SARIF level one step down (error → medium, warning → low, note → note). So min_severity: high selects exactly what the Security tab calls High or Critical: on exult, 84 alerts over 13 rules.

Scorecard posture checks are excluded by default rather than rolled into an owner "posture" issue. They are repository settings or project decisions, the owner already sees them on the Security tab, and an issue an agent cannot act on would only park. They still count on the dashboard (excluded), and exclude_rules: ["!SASTID"] re-includes one. The default list: BinaryArtifactsID, BranchProtectionID, CIIBestPracticesID, CITestsID, CodeReviewID, ContributorsID, DependencyUpdateToolID, FuzzingID, LicenseID, MaintainedID, PackagingID, SASTID, SecurityPolicyID, SignedReleasesID, VulnerabilitiesID (it repeats the dependency alerts), WebhooksID.

Grouping (pkg/codescanning/group.go, Cluster):

  • Code alerts group by (tool, rule). A rule in at most 5 files is one issue. Past that, files are packed directory by directory, in path order, into issues of at most 5 files; a directory is split only when it alone has more than 5. Exult's 84 alerts become 18 issues.
  • Dependency alerts (a Package: in the message, as Trivy writes) group by (tool, package): one issue per package with every CVE, pointing at the go.mod/lockfile or Containerfile/Dockerfile that brings it in.
  • Scorecard TokenPermissionsID (one alert per job) therefore becomes one issue per up-to-5 workflow files.
  • New issues are filed highest severity first; the cap holds the rest for later passes.

Issue body, in house style: summary with a plain "may be false positives" warning, evidence (analysed commit, alert table with links and path:line, a numbered code excerpt, rule docs), wanted behaviour, acceptance criteria, test plan, what to do with a false positive (say so on the issue; never weaken code or suppress), and out of scope. Two extras:

  • Workflow files. When every file is under .github/workflows/, the body says the fix needs the Workflows permission. If a lane serving the repo can push workflow files (config.WorkflowsCapableLane), the issue also gets hive/workflows-lane, so the scheduler routes it there; otherwise the body tells a lane to park it with the workflows blocker instead of trying and failing.
  • Forks. The sweep reads the same file at the upstream parent's HEAD; if the flagged lines are gone it reads the last upstream commit to touch the file and says "port upstream <sha>", else it says upstream has no fix to port. At most two reads per new issue.

Dedupe and lifecycle. Each issue starts with <!-- hive:code-scanning tool=… rule=… paths=… alerts=… --> and carries origin/governor + hive/code-scanning. Each pass lists the hive's own hive/code-scanning issues (App-authored only, so a squatted marker does nothing):

  • an alert number on any of them, open or closed, is never filed again, and the sweep never reopens an issue;
  • a new alert in a file an open issue already covers for the same rule (or the same package) is added to that issue;
  • rows turn fixed / dismissed; when all are gone the sweep comments and closes (completed, or not planned if all were dismissed);
  • if the open-alert listing hits its 1,000-alert bound, nothing is closed or marked fixed that pass.

Permission. A 403, or a 404 for no access, becomes a missing_permission notice; 404 no analysis found (or "Advanced Security must be enabled") becomes not_enabled. The repo is logged once and skipped for 6h. The notice shows as a pinned Code Scanning Alerts Not Readable dashboard banner with a Security-tab link, and in /api/status.

GitHub API budget. The sweep is a sweepOptional job, so it gets the staggered first pass (#16958) and is skipped whenever the budget mode is not normal; it also re-checks the mode before each repo. Calls are tagged hive:code_scanning. Listings are stable URLs with no since= (no cacheableSince needed), so unchanged pages are free 304s; alert pages are bounded at 10, issue pages at 5, and the dismissed list (2 pages) is read only when a tracked alert left the open list. Hook point: src/cmd/hive/sweep_workers.go:194@3fedee34c, in sweepJobs() beside its siblings.

Write-back gate. Every write (create, body edit, closing comment, close) asks WritebackAllowed as issue_file on the hive's own issue and carries // writeback:gated. The closing comment is inventoried in notificationWriteSites (status class).

Dashboard / API. /api/status gets code_scanning {enabled, repos[], notices[]}: per repo, open alerts by severity, qualifying / below threshold / excluded, tracked by an open hive issue, tracked by a closed one, untracked (waiting for the cap), open issues, this pass's filed / updated / closed, and the Security-tab link.

Files

  • src/pkg/codescanning/ (new): alert model, severity scale, policy, Cluster, marker, issue rendering, and Run against a Forge interface. No GitHub dependency.
  • src/pkg/github/code_scanning.go (new): the gated Forge over the App client, RunCodeScanningSweep, per-repo status, back-off and notices.
  • src/pkg/config/code_scanning.go (new) + config.go, validate.go: the code_scanning block.
  • src/cmd/hive/code_scanning.go (new), sweep_workers.go: the code_scanning sweep job.
  • src/pkg/dashboard/server.go, static-src/{html/root-notices.html,js/banners.js,js/refresh.js} (+ regenerated index.html): status field and notice banner.
  • Docs: new src/docs/code-scanning.md; github-app-setup.md (the permission), operator reference (feature row, write-surface sweeps table, API budget note), API reference (/api/status), labels reference (hive/code-scanning, origin/governor filers), glossary (the marker), notifications.md, documentation-map.md, hive.yaml.example; settings-parity allowlist (YAML-only keys); changelog.d/added-code-scanning-issues.md.

Tests

Fixtures are real alert payloads, slimmed and with owners replaced by example/…: 93 Danathar/exult CodeQL alerts (the 84 critical/high plus 9 quality findings), and the projectbluefin actions + common mix (Scorecard posture checks, TokenPermissions, PinnedDependencies, Trivy).

  • pkg/codescanning: severity mapping; exult min_severity: high selects 84 alerts over 13 rules and every group stays within 5 files; directory packing; cap per pass and dedupe across runs and a restart (18 issues total, no alert on two issues, no writes on re-scan); 0 qualifying alerts files nothing; fixed → closed completed, dismissed → closed not planned, reappearing alerts never refiled; an added alert updates the issue, a partial fix marks the row; a truncated listing never closes; missing permission and not-enabled notices; Scorecard posture checks file nothing while TokenPermissions groups by workflow file with the routing label (or park advice with no capable lane) and Trivy groups by package; exclude/re-include patterns; marker round trip; fork upstream note.
  • pkg/github: end-to-end sweep over an httptest GitHub (labels, filer tag, marker, status counts, dedupe until all 84 alerts are tracked, write-back gate off stops writes); a 403 notice is recorded once and the repo is not re-read inside the back-off; 404 no analysis found → not-enabled; no calls when the sweep is off or the budget is in conserve; the alert listing honours its page bound.
  • pkg/config: off by default, per-repo overrides, validation.
  • pkg/dashboard: /api/status code_scanning (counts, tracked, link, notice), absent when off; banner wiring.
  • cmd/hive: code_scanning is an optional job with a staggered first pass, a configurable hourly interval, and is shed in conserve.

Fail-before: the cmd/hive and pkg/dashboard tests failed before the job and status field were wired (no code_scanning sweep job, code_scanning missing); the pkg/codescanning tests failed (11 of 13) against stubbed Run/Cluster/Judge/Level; the pkg/github and pkg/config tests do not build on the v6 tip.

Ran in full: pkg/codescanning, pkg/writeback (TestDirectWriteRatchet), pkg/config, pkg/github (incl. TestNotificationWriteSitesInventory), pkg/dashboard (incl. settings parity), pkg/dashboard/webstatic, cmd/hive; go vet on each; check-docs-links.py, check-docs-citations.py, check-api-reference-citations.sh. TestGateFailsClosedWithoutIP6Tables in pkg/config fails on this machine on the v6 tip too (host lacks the expected ip6tables setup); it is unrelated.

Not in this PR

  • A Settings-dialog control for the keys (they are YAML-only, allowlisted in the parity file).
  • A per-repo counts table in the dashboard UI. The counts are in /api/status; the UI shows only the notice banner today.
  • A one-issue "repo security posture" decision for the excluded Scorecard checks.

🤖 Generated with Claude Code

https://claude.ai/code/session_01BQYnPGFJx81c8JXR3o1sg1

An opt-in sweep (code_scanning, off by default, per repo) reads a
repository's open code scanning alerts (CodeQL, OSSF Scorecard, Trivy,
any SARIF uploader) and files them as issues sized for one PR: code
alerts grouped by rule and at most five files (packed by directory),
dependency alerts grouped by package. At most five new issues per repo
per hourly pass, highest severity first.

Each issue carries a hidden <!-- hive:code-scanning ... --> marker
listing its alert numbers; the sweep lists its own hive/code-scanning
issues to rebuild dedupe state from GitHub, adds new alerts in covered
files, marks fixed/dismissed rows, closes an issue when every alert is
gone, and never reopens or refiles. OSSF Scorecard repo-posture checks
are excluded by default. Workflow-file issues get hive/workflows-lane
when a lane can push workflows; fork issues say whether upstream
changed the flagged code.

Missing "Code scanning alerts: Read" surfaces as a dashboard banner and
/api/status notice with a six-hour back-off. The job is a sweepOptional
worker (staggered first pass, skipped outside normal API budget), and
every write goes through WritebackAllowed as issue_file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BQYnPGFJx81c8JXR3o1sg1
Signed-off-by: Danathar <Danathar@users.noreply.github.com>
@kubestellar-prow kubestellar-prow Bot added the dco-signoff: yes Indicates the PR's author has signed the DCO. label Nov 7, 2026
@kubestellar-prow

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by:
Once this PR has been reviewed and has the lgtm label, please assign nicholasjackson for approval. For more information see the Code Review Process.

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@kubestellar-prow kubestellar-prow Bot added the size/XXL Denotes a PR that changes 1000+ lines, ignoring generated files. label Nov 7, 2026
@Danathar
Danathar marked this pull request as draft November 7, 2026 23:33
@kubestellar-prow kubestellar-prow Bot added the do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. label Nov 7, 2026
@github-actions

github-actions Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Open PR overlap check

Base branch: v6

Conflicts are checked with every PR merged onto the current tip of v6, so a PR that only needs a rebase is not reported as conflicting with its siblings.

PR Title Relation Files
#17025 🌱 Forward-merge v5 into v6 (1 commits) same files src/docs/documentation-map.md
src/docs/operator-reference/README.md

@hivecommons-hive

Copy link
Copy Markdown
Contributor

@Danathar this PR is back in your court (stage/072-returned-to-contributor). The hive will not merge it until the head changes.

Failing checks:

  • check-failure

Reply here or push a new head to this branch (same sign-off); CI and the review swarm re-run automatically and the PR returns to the normal path.

Queued in your relay fix queue (4 waiting): fixes are handed out before new work as soon as you have capacity.

Danathar and others added 2 commits November 8, 2026 09:01
TestCommentMarkerRatchet failed: codeScanningForge.CloseIssue posted a
comment without a hive marker (47 unmarked emitters against a baseline of
46). The closing note now starts with codescanning.CloseMarker, and
CloseIssue checks for its own marked note before posting. A retry after a
refused close then closes without posting the note again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BQYnPGFJx81c8JXR3o1sg1
Signed-off-by: Danathar <Danathar@users.noreply.github.com>
Signed-off-by: Danathar <Danathar@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

A critical fail-open author check trusts unverified marked issues when identity lookup fails, allowing other users’ issues to suppress filings or be edited or closed.

5 open issues
What changed in this PR

Adds an opt-in code-scanning sweep that turns GitHub security alerts into grouped issues for Hive’s existing lanes, with lifecycle tracking, API-budget controls, and operator notices.

Changes:

  • Adds severity filtering, alert grouping, persistent deduplication, and issue updates and closure.
  • Integrates per-repository configuration, gated GitHub writes, and staggered optional scheduling.
  • Exposes status and permission notices, with fixtures, tests, and operator documentation.
File Description
src/​pkg/​github/​notification_write_sites.go Registers closing comments in the notification inventory.
src/​pkg/​github/​code_scanning.go Implements GitHub access, gated writes, status, and backoff.
src/​pkg/​github/​code_scanning_test.go Tests filing, deduplication, permissions, and request bounds.
src/​pkg/​github/​client.go Adds client-held sweep state.
src/​pkg/​dashboard/​static/​index.html Includes the generated notice banner and rendering logic.
src/​pkg/​dashboard/​static-src/​js/​refresh.js Calls the code-scanning banner renderer.
src/​pkg/​dashboard/​static-src/​js/​banners.js Renders repository notices and Security-tab links.
src/​pkg/​dashboard/​static-src/​html/​root-notices.html Adds the pinned notice container.
src/​pkg/​dashboard/​settings_parity_allowlist.txt Records YAML-only configuration keys.
src/​pkg/​dashboard/​server.go Exposes code-scanning status through /api/status.
src/​pkg/​dashboard/​code_scanning_status_test.go Tests status output and banner wiring.
src/​pkg/​config/​validate.go Invokes code-scanning configuration validation.
src/​pkg/​config/​testdata/​agent_runtime_golden.json Updates the configuration serialization fixture.
src/​pkg/​config/​config.go Adds the top-level configuration block.
src/​pkg/​config/​code_scanning.go Defines defaults, repository overrides, and validation.
src/​pkg/​config/​code_scanning_test.go Tests defaults, overrides, and invalid settings.
src/​pkg/​codescanning/​testdata/​scorecard-trivy-common.json Supplies mixed Scorecard and dependency alert fixtures.
src/​pkg/​codescanning/​testdata/​scorecard-actions.json Supplies workflow and repository-posture alert fixtures.
src/​pkg/​codescanning/​sweep.go Coordinates filing, lifecycle updates, excerpts, and upstream checks.
src/​pkg/​codescanning/​sweep_test.go Tests filtering, grouping, deduplication, and lifecycle behavior.
src/​pkg/​codescanning/​render.go Generates issue bodies, alert tables, and closing comments.
src/​pkg/​codescanning/​group.go Groups alerts and encodes persistent tracking markers.
src/​pkg/​codescanning/​alert.go Defines alert models, severity mapping, and filtering policy.
src/​hive.yaml.example Shows per-repository opt-in configuration.
src/​docs/​operator-reference/​sweeps-and-operations.md Documents write surfaces and budget behavior.
src/​docs/​operator-reference/​README.md Lists the feature and configuration options.
src/​docs/​notifications.md Documents the closing-comment notification class.
src/​docs/​labels-and-control-signals/​reference.md Documents issue provenance and the tracking label.
src/​docs/​github-app-setup.md Documents the optional code-scanning permission.
src/​docs/​documentation-map.md Links the feature guide.
src/​docs/​dashboard-glossary.md Defines code-scanning issues and their markers.
src/​docs/​code-scanning.md Explains configuration, grouping, lifecycle, and operations.
src/​docs/​api-reference/​health-status-events.md Documents the new status response block.
src/​cmd/​hive/​sweep_workers.go Registers the optional scheduled sweep.
src/​cmd/​hive/​sweep_workers_test.go Tests scheduling, cadence, and budget classification.
src/​cmd/​hive/​code_scanning.go Connects the sweep worker to the GitHub client.
changelog.d/​added-code-scanning-issues.md Announces the opt-in feature.

Review effort: Balanced


func (f codeScanningForge) ListIssues(ctx context.Context, repo string) ([]codescanning.TrackedIssue, error) {
owner, name := f.c.splitRepo(repo)
own := f.c.knowsOwnAccounts()
Comment on lines +89 to +101
for _, files := range packFiles(distinctPaths(as)) {
in := map[string]bool{}
for _, f := range files {
in[f] = true
}
var sub []Alert
for _, a := range as {
if in[a.Path()] {
sub = append(sub, a)
}
}
out = append(out, newGroup(k.tool, "", sub))
}
for _, is := range openIssues {
for _, n := range is.Marker.Alerts {
if _, ok := openByNum[n]; !ok && dismissed == nil {
ds, _, derr := f.ListAlerts(ctx, o.Repo, "dismissed", dismissedMaxPages)
Comment on lines +148 to +153
sort.Strings(keys)
for _, k := range keys {
if !known[codeScanningRepoKey(c.Project.Org, k)] {
return fmt.Errorf("code_scanning.repos: %q is not listed in project.repos", k)
}
r := cs.Repos[k]
Comment on lines +4074 to +4076
if cs := s.deps.GHClient.CodeScanningStatus(); cs.Enabled || len(cs.Repos) > 0 {
payload.CodeScanning = &cs
}
…r the v6 merge

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BQYnPGFJx81c8JXR3o1sg1
Signed-off-by: Danathar <Danathar@users.noreply.github.com>

@hivecommons-hive hivecommons-hive Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Intent alignment (read at 3fedee34c): the diff does what the summary says — opt-in code_scanning config with per-repo overrides (src/pkg/config/code_scanning.go:84-107), marker-based dedupe over App-authored issues only (src/pkg/github/code_scanning.go ListIssues), 403/404 → notice with 6h back-off, every write behind WritebackAllowed, cap + severity-first filing (src/pkg/codescanning/sweep.go Run), and the sweep job/dashboard wiring. No unrelated scope.

One small factual slip in a line this PR edits:

  • src/docs/scale-envelope.md: the citation is bumped from client.go:5470-5480 to 5475-5485, but at head RankActionableIssues spans src/pkg/github/client.go:5461-5471 (the PR adds one line to client.go at :181); 5475-5485 points at makeLabelSet/actionableIssueRankTier.
     (`RankActionableIssues`, `src/pkg/github/client.go:5461-5471`, descending `AgeMinutes` within each tier).

— hive: agent=adjudicator-3 backend=copilot model=claude-fable-5.1 copilot=1.0.88

@hivecommons-hive

hivecommons-hive Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Hive status — updated in place; edits do not notify. Full history is in the Activity Monitor.

Review findings from adjudicator-5 (folded here because this head already carries its hive review):

Docs-currency pass on 3fedee3. The new code-scanning.md, config table, hive.yaml.example, API reference, labels reference row for hive/code-scanning, App-permission row and changelog all match the code I read (DefaultMaxNewIssues/zero-means-5, ParseLevel names, the default Scorecard list in pkg/codescanning/alert.go, security_events, 6h back-off). One stale spot:

hive/workflows-lane reference entry does not list the code scanning sweep as an applier (src/docs/labels-and-control-signals/reference.md:396-408, table row ~:411). pkg/github/code_scanning.go now passes WorkflowsLaneLabel: WorkflowsLaneLabel and pkg/codescanning/sweep.go appends it to new workflow-only issues when cfg.WorkflowsCapableLane(repo) is non-empty — and code-scanning.md cross-links to that anchor — but the section still says Who applies it: "Hive (issue-request relay, blocker re-check)" and describes only the park/relay path. An operator reading the label reference will not learn that a fresh issue can be born with this label.

**Who applies it:** Hive (issue-request relay, blocker re-check, code scanning sweep — on a new issue whose flagged files are all under `.github/workflows/`, when a lane serving the repository can push workflow files; see [Code scanning issues](../code-scanning.md)).

and in the summary table row's "Who applies" cell: Hive (issue-request relay, code scanning sweep).

Review findings from adjudicator-4 (folded here because this head already carries its hive review):

Style/maintainability review (read at head 3fedee3, files under src/pkg/codescanning, src/pkg/github/code_scanning.go, src/pkg/config/code_scanning.go, src/cmd/hive). Nothing blocking; a few things that will cost the next reader.

  1. Title round-trips through the body to be scrubbed once — src/pkg/github/code_scanning.go:298-302. prepare(repo, title+"\n"+body) then strings.Cut(body, "\n") relies on neither AgentIssueTitle, logscrub.ScrubString nor NeutralizeMentions ever producing or consuming a newline at the seam. Two calls is clearer and removes the invariant:

    	title, err := f.prepare(repo, title)
    	if err != nil {
    		return 0, err
    	}
    	body, err = f.prepare(repo, body)
    	if err != nil {
    		return 0, err
    	}
    
  2. Two ad-hoc parsers for the alert-table row — src/pkg/codescanning/render.go:277-281 edits the Status column with index arithmetic on ") | " / " |", while src/pkg/codescanning/sweep.go:367-373 reads the same column with SplitN(row, " | ", 3)[1]. Both encode the row layout written at render.go:270. One rowStatus/setRowStatus pair next to alertRowRE would keep the format in one place (and make alertRowRE the single source for the [a-z]+ status token).

  3. Policy.Judge evaluated twice per alert — src/pkg/codescanning/sweep.go:209 and :225. Judge rebuilds excludeList() on every call (alert.go:271-290), so this also doubles the allocation per alert. Hoist it:

    		v := o.Policy.Judge(a)
    		switch v {
    

    and if v != Qualifies { at :225.

  4. Smaller idiom points: map[bool]string{true: "", false: "s"}[n == 1] appears four times (render.go:47,95,101,293) where the repo convention is a local plural() helper (pkg/review/confidence.go, pkg/escalation/escalation.go, …); CodeScanningConfig.AnyEnabled (config/code_scanning.go:109) has no production caller — only its own test — and its (repos, org) argument order is the reverse of For(org, repo); drop it or wire it.

Run (sweep.go:144-355) is ~210 lines with three distinct phases (dedupe state, close/refresh, file new); splitting the last two into helpers would help, but that is a judgement call and does not block.

Review findings from adjudicator-2 (folded here because this head already carries its hive review):

Security perspective, read at head 3fedee3. No blocker; the write path is sound (canary scan + logscrub + mention neutralising in prepare, writeback gate before every write, URL-escaped marker, fence-safe excerpt, HTML-escaped dashboard banner). Two low-severity advisories:

1. Identity-unknown fallback adopts anyone's labelled issue as the hive's own — src/pkg/github/code_scanning.go:247,261. When knowsOwnAccounts() is false the author filter is skipped, so any issue a triage-level collaborator labels hive/code-scanning and seeds with a marker is treated as tracked state: its alert numbers are never filed (suppresses security filings), and the sweep edits/closes that third-party issue while telling the writeback gate HiveAuthored: true (code_scanning.go:290). The PR body says "App-authored only, so a squatted marker does nothing"; that holds only when identity is known. This mirrors attention_queue.go:377-389, but the clarity/prior-art resumes fail closed instead, and a filer that owns issue lifecycle fits the fail-closed side better:

	if !f.c.knowsOwnAccounts() {
		return nil, fmt.Errorf("listing %s issues in %s: hive cannot name its own accounts; refusing to adopt tracking state", CodeScanningLabel, repo)
	}

(replace own := f.c.knowsOwnAccounts() at line 247 and drop the own && at line 261).

2. Rule description is not escaped before the table delimiter — src/pkg/codescanning/render.go:101,186-191. cell() (line 314) escapes | and <!-- for message text, but ruleTitle writes Rule.Description raw into the Summary, which sits before <!-- hive:code-scanning-alerts -->. A SARIF uploader whose rule description contains that delimiter moves strings.Index(body, alertsStart) in rewriteBody (line 336) to the summary, so the next pass overwrites the summary/excerpt. Low likelihood (needs a tool with security-events: write), one-line fix:

	if d := cell(g.Alerts[0].Rule.Description); d != "" {

Review findings from reviewer (folded here because this head already carries its hive review):

Read the whole core path (pkg/codescanning/{sweep,group,render}.go, pkg/github/code_scanning.go, the sweep_workers.go hook) against v6 and the symbols it calls (activeRepos, knowsOwnAccounts, WorkflowsCapableLane, findOwnMarkerComment, WritebackAllowed). The design holds together: every write goes through codeScanningForge.gate → WritebackAllowed; ListIssues fails closed past its page bound so a partial dedupe view never files; Run closes nothing when the open listing is truncated; the marker round-trips with query-escaping. One concrete defect, one doc nit.

Finding (medium): the closing note cross-references unrelated issues/PRs.

src/pkg/codescanning/render.go:359 and :361 build CloseComment as "#" + strconv.Itoa(n) where n is a code scanning alert number. In a GitHub issue comment a bare #12 is auto-linked to issue/PR 12 of the same repository and posts a "mentioned this" timeline event on it. Alert numbers are small integers (exult's start at 1), so on every close the hive will stamp spurious cross-references onto whichever unrelated issues and PRs happen to carry those numbers — and the comment text points readers at the wrong thing. The alert table already avoids this at render.go:273 / :284 by writing [#%d](alertURL); the closing note should do the same (or say "alert 12"). sweep_test.go:339 asserts strings.Contains(closeComment, "fixed: #") and will need the same adjustment.

Doc nit (info): the PR body and src/docs/code-scanning.md say dedupe counts "App-authored only, so a squatted marker does nothing". code_scanning.go ListIssues applies that filter only when knowsOwnAccounts() is true; with no bot login / ai_author / App login configured and /user unreachable it falls back to any author with the label + marker. That matches the rest of the client's behaviour and is fine, but the doc should say the guarantee is conditional.

Verified no-ops I'd otherwise have flagged: the dismissed listing is bounded at 2 pages, so an alert dismissed beyond the 200th is reported as fixed and the issue closes completed instead of not_planned — bounded on purpose per the body, just noting the edge. An alert tracked on a closed issue is never refiled and never joins an open one; also as documented.

I have not approved or requested changes as a review event; this is a comment for the maintainer.

Review findings from adjudicator (folded here because this head already carries its hive review):

Correctness review (head 3fedee3). Read pkg/codescanning/{sweep,render,group,alert}.go, pkg/github/code_scanning.go, pkg/config/code_scanning.go, the sweep wiring, and advisory.NeutralizeMentions / logscrub. The dedupe/lifecycle logic holds up (marker values are query-escaped, so prepare() cannot corrupt it). Two advisory notes, neither blocking:

1. Re-scan is not idempotent when an alert message contains a mention-shaped name (hourly no-op edit).
Run decides whether to write by comparing the regenerated body with the stored one (src/pkg/codescanning/sweep.go:276-278), but the stored body was rewritten by codeScanningForge.prepare (src/pkg/github/code_scanning.go:259-261, 292-295): advisory.NeutralizeMentions turns babel/core into `babel`/core outside fences (src/pkg/advisory/sanitize.go:34-53). The alert table row is rebuilt from the raw Rule.ID + Message.Text each pass (src/pkg/codescanning/render.go:261), so for any Trivy npm package (Package: scope/pkg) or CodeQL message quoting a decorator, the regenerated body never equals the stored one → EditIssueBody (and Updated++) on every pass forever. The in-memory test forge does not apply prepare, so the "no writes on re-scan" test cannot see it. Suggested fix — let the forge normalise before the comparison via an optional interface:

--- a/src/pkg/codescanning/sweep.go
+++ b/src/pkg/codescanning/sweep.go
@@ func Run(ctx context.Context, f Forge, o Options) (Status, error) {
 		body := rewriteBody(is.Body, m, alertsSection(o.Repo, rows, gone, previousRows(is.Body)))
+		if n, ok := f.(interface{ Normalize(repo, text string) string }); ok {
+			body = n.Normalize(o.Repo, body)
+		}
 		if strings.TrimSpace(body) == strings.TrimSpace(is.Body) {
 			continue
 		}
--- a/src/pkg/github/code_scanning.go
+++ b/src/pkg/github/code_scanning.go
@@ func (f codeScanningForge) prepare(repo, text string) (string, error) {
 	return logscrub.ScrubString(advisory.NeutralizeMentions(text)), nil
 }
+
+// Normalize is prepare without the canary check, so Run compares the body it
+// would actually post against the stored one.
+func (f codeScanningForge) Normalize(repo, text string) string {
+	return logscrub.ScrubString(advisory.NeutralizeMentions(text))
+}

A test with a fixture message containing Package: scope/pkg run through the httptest forge twice would pin it.

2. Dismissed listing bound misreports closure reason. dismissedMaxPages = 2 (sweep.go:84) caps the dismissed read at 200 alerts; anything dismissed beyond that falls through to StatusFixed (sweep.go:234-238), so an issue whose alerts were all dismissed closes as completed with a "fixed: #…" comment instead of not_planned. Low impact (repos like exult with ~700 alerts could plausibly accumulate >200 dismissals); worth a doc note or treating an incomplete dismissed listing as "unknown → keep open" rather than fixed.

Review findings from reviewer-2 (folded here because this head already carries its hive review):

Conclusion: the design is sound and every write is behind WritebackAllowed, but there is one verified crash path in the new filing loop that should be fixed before this lands. I read the diff against v6 (c430d97) plus the existing sweep_workers.go, label_approval.go and attention_queue.go; this is independent of the Copilot thread, and I note below where I think one of its findings is overstated.

1. An all-pathless rule produces an empty Group, and Body indexes Alerts[0] — the sweep goroutine panics (high)

  • src/pkg/codescanning/group.go Cluster: for a (tool, rule) bucket, distinctPaths(as) drops every alert with Path() == "". When all of a rule's alerts are pathless, packFiles([]) returns one empty bin (by design, see its comment), the in set is empty, in[a.Path()] is in[""] → false, and newGroup(k.tool, "", sub) is built with sub == nil.
  • src/pkg/codescanning/sweep.go Run: the g.Alerts[0] guard there is only on the excerpt branch (g.Package == "" && len(g.Paths) > 0), so the empty group reaches Title(g) / Body(in).
  • src/pkg/codescanning/render.go Body reads g.Alerts[0].Instance.CommitSHA, .Rule.HelpURI, .HTMLURL, and Title reads g.Alerts[0].Rule.Description → index out of range.
  • src/cmd/hive/sweep_workers.go:88-116 runSweepWorker calls fire(cfg, attempts) with no recover; the only recover() in cmd/hive is in shutdown_hooks.go. A panic here takes the hive process down, not just the pass.

Reachable with shipped config: exclude_rules: ["!SASTID"] (or any !-re-inclusion of a Scorecard repo-level check, which the docs advertise) plus a min_severity it clears, or any SARIF uploader that emits an alert without most_recent_instance.location. The mixed case (a rule with some pathless and some file alerts) does not panic but silently drops the pathless alerts from every bin, so they sit in pool forever and never count as Untracked. Suggest: give pathless alerts their own group per rule before packing files (the doc comment on Cluster already says "A repo-level alert (no file) is its own one-alert-per-rule issue" — the code doesn't do that yet), and a test with one pathless qualifying alert.

2. Dismissed listing cap discards complete (low)

sweep.go Run: ds, _, derr := f.ListAlerts(ctx, o.Repo, "dismissed", dismissedMaxPages) throws away the completeness flag. A tracked alert dismissed beyond the first 200 dismissed alerts is recorded as fixed, and an all-dismissed issue closes as completed instead of not_planned. The issue still closes, so this is cosmetic in the body and the state reason; worth a one-line "unknown" status when !complete rather than a fetch-per-alert.

3. On the Copilot "fail-open author check" finding — I'd rate it info, not high

src/pkg/github/code_scanning.go ListIssues: own && !isHiveAccount(...) && !IsHiveAuthorLogin(...) is the same shape as the existing attention_queue.go:377 marker adoption and label_approval.go:446 ("legacy any-author rule applies only when the hive has no identity configured and could not resolve its own login"). This PR follows the repository's established idiom for the no-identity case; tightening it is a cross-cutting decision, not a defect introduced here. The issue-filter is also label-scoped (hive/code-scanning), which a squatter would need to be able to apply.

What I confirmed is right

  • Every forge write (CreateIssue, EditIssueBody, CloseIssue) runs prepare (canary scan, scrub, mention neutralising) and gate → WritebackAllowed before the API call; CloseIssue reuses findOwnMarkerComment so a failed close does not double-post.
  • 403/404 → ErrNoAccess/ErrNotEnabled only via *gh.ErrorResponse; rate-limit errors are different types in go-github and fall through unchanged, so a rate limit does not trigger the 6h back-off or a false "missing permission" notice.
  • ListIssues refuses to return a partial dedupe set past 5 pages, and Run files nothing when it errors — a restart cannot double-file.
  • Truncated open listings (!complete) skip close/fixed detection and preserve prior rows, as the body claims.
  • Config: off by default, per-repo override, validation rejects unknown repos and sub-10m intervals; ParseLevel("") → LevelNone → DefaultMinLevel matches the documented high default.

Body matches diff throughout; the scale-envelope.md citation adjudicator-3 flagged was corrected in 4cacc28.

Evidence bundle `#17130c430d97` sha256:90c649a1a807485642305fa2e926c709483bda51d34be570e11ccd567e0605bb — download from the dashboard or `hivectl review evidence #17130`.

@hivecommons-hive
hivecommons-hive Bot merged commit 68200e4 into hivecommons:v6 Nov 8, 2026
70 of 71 checks passed
@hivecommons-hive

Copy link
Copy Markdown
Contributor

merged by Hive trusted-author auto-merge: author @Danathar holds role owner and GitHub permission maintain on repo; CI green at c430d97.

@hivecommons-hive hivecommons-hive Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Conclusion: read the sweep core, the gated forge, config and wiring; I found no defect. This looks correct to me. CI (test (rest 4/4), mobile-shots) was still pending when I read it — I have not waited on it.

What I verified (code first, body second)

  • src/pkg/codescanning/sweep.go Run: close happens only when complete && len(still)==0 && len(add)==0, so a truncated open-alert listing (Truncated) can never close or mark-fixed — matches the stated 1,000-alert guard. Alerts on closed tracked issues are skipped via seen[] (TrackedClosed), and that "never reopens / never refiles" rule is documented in docs/code-scanning.md and pinned by TestRunClosesFixedAndDismissedIssuesAndNeverRefiles.
  • src/pkg/github/code_scanning.go: every write (CreateIssue, EditIssueBody, CloseIssue) goes through prepare (canary → mention-neutralise → logscrub) and gate (WritebackAllowed as issue_file, HiveAuthored: true) before the // writeback:gated call. ListIssues drops non-hive authors when knowsOwnAccounts(), so a squatted marker cannot suppress a filing; past codeScanningIssuePages it returns an error rather than a partial dedupe set, and Run then files nothing. classifyCodeScanningError maps 403/404 onto ErrNoAccess/ErrNotEnabled; RunCodeScanningSweep treats a notice as back-off (6h), not Errors++.
  • src/pkg/config/code_scanning.go: repoOverride normalises both sides through NormalizeRepoForOrg, so repos.exult and repos.Danathar/exult resolve the same; validateCodeScanning rejects unknown repos, bad severities, negative caps and interval < 10m.
  • Body claim "calls are tagged hive:code_scanning": nothing in the diff tags them, but sweepJob.runTagged (src/cmd/hive/sweep_workers.go:49 on v6) applies hive:<job name> to every job, so the claim holds via the job name.

One low-severity edge, not a blocker

  • sweep.go: the dismissed listing is ListAlerts(ctx, repo, "dismissed", dismissedMaxPages) with dismissedMaxPages = 2 and the complete flag discarded. On a repo with >200 dismissed alerts (exult has 697 open; its dismissed count is plausibly past that), a tracked alert dismissed beyond page 2 is classified StatusFixed, so the row says fixed and the close reason becomes completed instead of not_planned. Cosmetic — no filing or closing decision changes — but worth either raising the bound or noting it in the doc.

Body and diff agree on everything else I checked (page bounds 10/5/2, cap 5, default high, Scorecard exclusion list applied via Policy.Judge). Docs, changelog fragment, settings-parity allowlist and notificationWriteSites inventory are all updated.

— hive: agent=reviewer backend=copilot model=claude-fable-5.1 copilot=1.0.88

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

dco-signoff: yes Indicates the PR's author has signed the DCO. size/XXL Denotes a PR that changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants