diff --git a/changelog.d/fixed-agent-issue-title-prefix.md b/changelog.d/fixed-agent-issue-title-prefix.md new file mode 100644 index 0000000000..d69f3c47a1 --- /dev/null +++ b/changelog.d/fixed-agent-issue-title-prefix.md @@ -0,0 +1 @@ +- Every issue the hive files now starts with its `[]` tag, with no producer left out: one `issueshape.AgentIssueTitle` function is the choke point for every issue-creation path — `CreateIssue`, the review-backlog, dedupe, hotspot (`[ci-maintainer]`, matching its `agent/ci-maintainer` label), self-report, upstream-watch, advisory and recommendations filers, and the proxy's `gh issue create` — puts the tag first (ahead of any emoji), never doubles it, and a guard test fails any new raw create that skips it. The Activity Monitor draws the tag as a chip ahead of the title instead of repeating it. Existing issue titles are left as they are; dedupe ignores the tag so they still match their tagged successors. diff --git a/src/crux/issueshape/issueshape.go b/src/crux/issueshape/issueshape.go index 02624f3e9e..dcec0abb70 100644 --- a/src/crux/issueshape/issueshape.go +++ b/src/crux/issueshape/issueshape.go @@ -99,48 +99,102 @@ func UnchosenOptionList(text string) (string, bool) { return m, m != "" } -// agentTitlePrefixRE matches the leading `[]` tag every hive-filed -// issue title carries (`[scanner] …`, `[reviewer] …`, `[selfreport] …`). A -// filer-chosen tag with spaces (`[ACMM L0] …`) counts too, so it is kept -// rather than stacked under a second tag. -var agentTitlePrefixRE = regexp.MustCompile(`^\s*\[([^\]\n]+)\]\s*`) +// Every issue the hive files starts with the filing agent in brackets: +// `[scanner] …`, `[reviewer] …`, `[selfreport] …` (the owner's rule: "agents +// that need to open issues need to use [agent name]"). A filer tag is the +// lowercased agent (lane) name as the dashboard shows it, so it has the slug +// shape filerTagRE describes; a bracketed tag of any other shape +// (`[ACMM L0]`, `[Tests]`) is part of the subject, not a filer. +var ( + // leadingTagRE matches a title's leading `[tag]`, optionally preceded by + // a short run of symbols (an emoji convention such as `🐛 [reviewer] …`) + // captured in group 1 so the tag can be moved in front of it. + leadingTagRE = regexp.MustCompile(`^\s*((?:[^\p{L}\p{N}\[\]\s]+\s*)?)\[([^\]\n]+)\]\s*`) + filerTagRE = regexp.MustCompile(`^[a-z0-9][a-z0-9_.-]*$`) +) -// TitleFor returns title carrying a leading `[]` tag, the convention -// every issue the hive files follows so a reader can tell which agent or -// subsystem filed it. The tag is the lowercased agent (lane) name as the -// dashboard shows it. It is idempotent: a title that already starts with a -// bracketed tag — the same agent, or a tag the filer chose itself such as -// `[Tests]` or `[DCO]` — is returned unchanged, so a title is never -// double-prefixed. An empty agent leaves the title as it is. -func TitleFor(agent, title string) string { +// AgentIssueTitle returns title carrying a leading `[]` tag. It is the +// one function every hive issue-creation path runs a title through, and it +// is idempotent: +// - a title already tagged with this agent (any case, or after a leading +// emoji) is normalised to `[agent] …` with the rest unchanged; +// - a title another hive filer already tagged (`[selfreport] …` relayed by +// the governor) is kept as it is, so a title is never double-tagged; +// - a filer-chosen bracket that is not a filer name (`[ACMM L0] …`) is part +// of the subject and gets the `[agent]` tag in front of it; +// - the tag always comes first, before any emoji the title opens with. +// +// An empty agent leaves the title as it is. +func AgentIssueTitle(agent, title string) string { title = strings.TrimSpace(title) agent = strings.ToLower(strings.TrimSpace(agent)) - if agent == "" || title == "" || HasAgentPrefix(title) { + if agent == "" || title == "" { return title } - return "[" + agent + "] " + title + m := leadingTagRE.FindStringSubmatch(title) + if m == nil { + return "[" + agent + "] " + title + } + lead, tag, rest := strings.TrimSpace(m[1]), strings.TrimSpace(m[2]), title[len(m[0]):] + switch { + case strings.EqualFold(tag, agent): + return joinTitle("["+agent+"]", lead, rest) + case !IsFilerTag(tag): + return "[" + agent + "] " + title + case lead == "": + return title + default: + return joinTitle("["+tag+"]", lead, rest) + } +} + +func joinTitle(parts ...string) string { + out := parts[:0] + for _, p := range parts { + if p != "" { + out = append(out, p) + } + } + return strings.Join(out, " ") +} + +// IsFilerTag reports whether tag (the text inside a title's leading +// brackets) has the shape of a hive filer name: a lowercase slug. +func IsFilerTag(tag string) bool { + return filerTagRE.MatchString(strings.TrimSpace(tag)) } -// HasAgentPrefix reports whether title starts with a bracketed `[tag]`. +// HasAgentPrefix reports whether title starts with a filer tag (`[scanner] …`). func HasAgentPrefix(title string) bool { - return agentTitlePrefixRE.MatchString(title) + return AgentPrefix(title) != "" } -// AgentPrefix returns the tag inside a title's leading `[tag]`, lowercased, -// or "" when the title carries none. +// AgentPrefix returns the filer tag a title leads with (`[scanner] …` → +// "scanner"), or "" when the title carries none. A leading bracket that is +// not filer-shaped (`[ACMM L0] …`) is not a filer tag. func AgentPrefix(title string) string { - m := agentTitlePrefixRE.FindStringSubmatch(title) - if m == nil { + m := leadingTagRE.FindStringSubmatch(title) + if m == nil || strings.TrimSpace(m[1]) != "" { return "" } - return strings.ToLower(m[1]) + tag := strings.TrimSpace(m[2]) + if !IsFilerTag(tag) { + return "" + } + return tag } -// StripAgentPrefix returns title without its leading `[tag]`, trimmed. It is -// the key dedupe compares on so an issue filed before titles carried the -// filing agent still matches its prefixed re-filing. +// StripAgentPrefix returns title without its leading filer tag, trimmed. It +// is the key dedupe compares on so an issue filed before titles carried the +// filing agent still matches its prefixed re-filing. A non-filer bracket +// (`[ACMM L0] …`) is part of the subject and stays. func StripAgentPrefix(title string) string { - return strings.TrimSpace(agentTitlePrefixRE.ReplaceAllString(strings.TrimSpace(title), "")) + title = strings.TrimSpace(title) + if AgentPrefix(title) == "" { + return title + } + m := leadingTagRE.FindStringSubmatch(title) + return strings.TrimSpace(title[len(m[0]):]) } // SameTitle reports whether two issue titles are the same title once the diff --git a/src/crux/issueshape/issueshape_test.go b/src/crux/issueshape/issueshape_test.go index 683b3d3be5..37f47c2d0f 100644 --- a/src/crux/issueshape/issueshape_test.go +++ b/src/crux/issueshape/issueshape_test.go @@ -103,26 +103,36 @@ func TestUnchosenOptionList(t *testing.T) { } } -// Every issue the hive files names its filer in the title; TitleFor is the -// one helper that adds the tag, and it never adds a second one. -func TestTitleForTagsOnceAndKeepsExistingTag(t *testing.T) { +// Every issue the hive files names its filer in the title; AgentIssueTitle +// is the one helper that adds the tag, it puts the tag first, and it never +// adds a second one. +func TestAgentIssueTitleTagsOnceAndTagFirst(t *testing.T) { cases := []struct{ agent, title, want string }{ {"reviewer", "Review backlog (security): token logged", "[reviewer] Review backlog (security): token logged"}, {"Reviewer", " Review backlog (style): x ", "[reviewer] Review backlog (style): x"}, {"reviewer", "[reviewer] Review backlog (security): token logged", "[reviewer] Review backlog (security): token logged"}, - {"tester", "[Tests] v5 test failure on 4536f90", "[Tests] v5 test failure on 4536f90"}, - {"dashboard", "[ACMM L0] Add CI/CD pipeline", "[ACMM L0] Add CI/CD pipeline"}, + {"reviewer", "[Reviewer]Review backlog (security): x", "[reviewer] Review backlog (security): x"}, + {"dedupe", "triage: duplicate and overlapping open issues/PRs to consolidate", "[dedupe] triage: duplicate and overlapping open issues/PRs to consolidate"}, + {"ci-maintainer", "refactor: src/a.go is a merge hotspot — split into 4 units", "[ci-maintainer] refactor: src/a.go is a merge hotspot — split into 4 units"}, {"selfreport", "[selfreport] unclassified_error_repeated: x", "[selfreport] unclassified_error_repeated: x"}, - {"governor", "refactor: src/a.go is a merge hotspot — split into 4 units", "[governor] refactor: src/a.go is a merge hotspot — split into 4 units"}, + // Another hive filer already tagged it: never a second tag. + {"governor", "[selfreport] relayed by the hub", "[selfreport] relayed by the hub"}, + // The tag comes first, before an emoji the title opens with. + {"governor", "🐝 Hive Advisory Report", "[governor] 🐝 Hive Advisory Report"}, + {"reviewer", "🐛 [reviewer] decision lost on refresh", "[reviewer] 🐛 decision lost on refresh"}, + {"governor", "🐝 [selfreport] relayed", "[selfreport] 🐝 relayed"}, + // A filer-chosen bracket that is not a filer name is the subject. + {"dashboard", "[ACMM L0] Add CI/CD pipeline", "[dashboard] [ACMM L0] Add CI/CD pipeline"}, + {"tester", "[Tests] v5 test failure on 4536f90", "[tester] [Tests] v5 test failure on 4536f90"}, {"", "untagged stays untagged", "untagged stays untagged"}, {"scanner", "", ""}, } for _, tc := range cases { - if got := TitleFor(tc.agent, tc.title); got != tc.want { - t.Errorf("TitleFor(%q, %q) = %q, want %q", tc.agent, tc.title, got, tc.want) + if got := AgentIssueTitle(tc.agent, tc.title); got != tc.want { + t.Errorf("AgentIssueTitle(%q, %q) = %q, want %q", tc.agent, tc.title, got, tc.want) } - if again := TitleFor(tc.agent, TitleFor(tc.agent, tc.title)); again != tc.want { - t.Errorf("TitleFor is not idempotent for (%q, %q): %q", tc.agent, tc.title, again) + if again := AgentIssueTitle(tc.agent, AgentIssueTitle(tc.agent, tc.title)); again != tc.want { + t.Errorf("AgentIssueTitle is not idempotent for (%q, %q): %q", tc.agent, tc.title, again) } } } @@ -136,15 +146,24 @@ func TestStripAgentPrefixAndSameTitle(t *testing.T) { if got := StripAgentPrefix(" no tag here "); got != "no tag here" { t.Fatalf("StripAgentPrefix(untagged) = %q", got) } - if got := AgentPrefix("[Scanner] split x.go"); got != "scanner" { + if got := StripAgentPrefix("[ACMM L0] Add CI/CD pipeline"); got != "[ACMM L0] Add CI/CD pipeline" { + t.Fatalf("StripAgentPrefix must keep a non-filer bracket: %q", got) + } + if got := AgentPrefix("[scanner] split x.go"); got != "scanner" { t.Fatalf("AgentPrefix = %q", got) } - if AgentPrefix("plain") != "" || HasAgentPrefix("plain") { - t.Fatal("untagged title reported a tag") + if AgentPrefix("plain") != "" || HasAgentPrefix("plain") || AgentPrefix("[Tests] failure") != "" || AgentPrefix("🐛 [reviewer] x") != "" { + t.Fatal("a title without a leading filer tag reported one") } if !SameTitle("Review backlog (security): x", "[reviewer] Review backlog (security): x") { t.Fatal("legacy untagged title must match its tagged successor") } + if !SameTitle("[ACMM L0] Add CI/CD pipeline", "[dashboard] [ACMM L0] Add CI/CD pipeline") { + t.Fatal("legacy ACMM gap title must match its tagged successor") + } + if !SameTitle("🐝 Hive Advisory Report", "[governor] 🐝 Hive Advisory Report") { + t.Fatal("legacy advisory title must match its tagged successor") + } if SameTitle("[reviewer] Review backlog (security): x", "[reviewer] Review backlog (security): y") { t.Fatal("different subjects must not match") } diff --git a/src/crux/proxy/github_proxy_violations.go b/src/crux/proxy/github_proxy_violations.go index d8088c48ef..6cebc15a04 100644 --- a/src/crux/proxy/github_proxy_violations.go +++ b/src/crux/proxy/github_proxy_violations.go @@ -190,7 +190,7 @@ func injectOriginLabel(method, path string, body []byte, agentName string) ([]by if raw, present := payload["title"]; present { var title string if err := json.Unmarshal(raw, &title); err == nil && title != "" { - if tagged := issueshape.TitleFor(lane, title); tagged != title { + if tagged := issueshape.AgentIssueTitle(lane, title); tagged != title { encoded, err := json.Marshal(tagged) if err != nil { return body, false diff --git a/src/crux/proxy/origin_label_inject_test.go b/src/crux/proxy/origin_label_inject_test.go index f08d4dcf00..d665e57a79 100644 --- a/src/crux/proxy/origin_label_inject_test.go +++ b/src/crux/proxy/origin_label_inject_test.go @@ -25,7 +25,9 @@ func TestInjectOriginLabelAddsLaneOnceAndKeepsAgentChoice(t *testing.T) { }{ {name: "no labels field", method: http.MethodPost, path: path, body: `{"title":"t","body":"b"}`, agent: "scanner", wantOK: true, wantLabels: []string{"agent/scanner"}, wantTitle: "[scanner] t"}, {name: "already tagged title kept, replica suffix stripped", method: http.MethodPost, path: path, body: `{"title":"[scanner] t","body":"b","labels":["agent/scanner"]}`, agent: "scanner-2", wantOK: false}, - {name: "foreign tag not double-prefixed", method: http.MethodPost, path: path, body: `{"title":"[Tests] t","body":"b"}`, agent: "tester", wantOK: true, wantLabels: []string{"agent/tester"}, wantTitle: "[Tests] t"}, + {name: "another filer's tag not double-prefixed", method: http.MethodPost, path: path, body: `{"title":"[selfreport] t","body":"b"}`, agent: "tester", wantOK: true, wantLabels: []string{"agent/tester"}, wantTitle: "[selfreport] t"}, + {name: "subject bracket is not a filer tag", method: http.MethodPost, path: path, body: `{"title":"[Tests] t","body":"b"}`, agent: "tester", wantOK: true, wantLabels: []string{"agent/tester"}, wantTitle: "[tester] [Tests] t"}, + {name: "tag moves ahead of a leading emoji", method: http.MethodPost, path: path, body: `{"title":"🐛 [scanner] t","body":"b"}`, agent: "scanner", wantOK: true, wantLabels: []string{"agent/scanner"}, wantTitle: "[scanner] 🐛 t"}, {name: "bare lane label dropped, replica suffix stripped", method: http.MethodPost, path: path, body: `{"title":"t","body":"b","labels":["agent/scanner","scanner","kind/bug"]}`, agent: "scanner-2", wantOK: true, wantLabels: []string{"agent/scanner", "kind/bug"}}, {name: "agent-supplied origin kept while bare filing lane drops", method: http.MethodPost, path: path, body: `{"title":"t","body":"b","labels":["origin/dashboard","agent/scanner","scanner"]}`, agent: "scanner", wantOK: true, wantLabels: []string{"origin/dashboard", "agent/scanner"}}, {name: "agent-supplied matching origin drops redundant origin and bare label", method: http.MethodPost, path: path, body: `{"title":"t","body":"b","labels":["origin/scanner","agent/scanner","scanner","kind/bug"]}`, agent: "scanner", wantOK: true, wantLabels: []string{"agent/scanner", "kind/bug"}}, diff --git a/src/docs/getting-started.md b/src/docs/getting-started.md index 34d57b5263..f293599c6a 100644 --- a/src/docs/getting-started.md +++ b/src/docs/getting-started.md @@ -160,7 +160,7 @@ Read it like a weekly digest, not a to-do list. You don't have to act on everyth ## How to read hive-filed issues -Every issue a hive agent opens has the agent's name in the title — for example `[scanner] Possible nil pointer dereference in handler.go:142` or `[quality] Missing test coverage for payment flow`. +Every issue a hive agent opens has the agent's name in the title — for example `[scanner] Possible nil pointer dereference in handler.go:142` or `[quality] Missing test coverage for payment flow`. The same holds for issues the hive files on its own behalf: `[reviewer] Review backlog (security): …`, `[dedupe] triage: …`, `[ci-maintainer] refactor: … is a merge hotspot`, `[selfreport] …`, `[governor] 🐝 Hive Advisory Report`. The tag always comes first, before any emoji, and the Activity Monitor draws it as a chip ahead of the title. When you see a new issue in your project, check the title prefix — it tells you which agent filed it and what kind of finding it is: diff --git a/src/docs/operator-reference.md b/src/docs/operator-reference.md index c5a4c1d3f6..57bd8c9436 100644 --- a/src/docs/operator-reference.md +++ b/src/docs/operator-reference.md @@ -1444,7 +1444,7 @@ The hive already predicts PR file overlap for the merge train. The advisor reuse - A file is a **hotspot** when, over the rolling window, at least `hotspot_min_prs` distinct PRs touched it and at least `hotspot_min_overlaps` pairs of them were open at the same time. Score = concurrent pairs × a size weight (1 / 1.25 / 1.5 / 2 at 800 / 1500 / 4000 lines) + 2 × attributed conflicts. Hunk-level "same region" weighting is not available from the train's records and is skipped. - **Don't splinter.** A split is only recommended for code when the file has at least `hotspot_min_lines` lines **and** two or more top-level symbol groups (Go: funcs and types via `go/ast`, methods grouped under their receiver; JS/TS/Python: top-level declarations; Markdown: `##` headings). The proposal targets at most 4 files of at least 150 lines, no behaviour change, exported API unchanged, tests move with the code. - **By kind.** Docs (`*.md`, `*.rst`, `*.txt`) are reported but only recommended for a by-section split above 1500 lines (the `docs/api-reference/.md` pattern). Generated files (`// Code generated … DO NOT EDIT`, `*.pb.go`, the dashboard SPA under `pkg/dashboard/static/` → `static-src/`) point at their source — unless that source tree is already split into more than 4 files, in which case they are report-only (regeneration makes the output touch every source change). Lock and data files are report-only. -- **One issue per file.** Title `refactor: is a merge hotspot — split into units`, labels `agent/ci-maintainer` + `kind/cleanup`, origin `governor`, body marker ``, evidence table, the top-level units, a concrete split proposal and the don't-splinter rule. While that issue is open no second one is filed; after it closes the file waits `hotspot_refile_days` before it can be filed again. **Capped.** At most `hotspot_max_open` modularize issues are open per repo at once (an issue that already has a PR still counts) and at most `hotspot_max_per_pass` are filed per advisor pass; the highest-ranked uncapped hotspot is filed when a slot frees, and the advisor logs one INFO line per pass when the cap holds it back. Issues go through the writeback gate as `issue_file` (a paused repo or `writeback.per_repo[].mode: off` stops them) and are skipped when the GitHub budget governor is skipping optional sweeps. +- **One issue per file.** Title `[ci-maintainer] refactor: is a merge hotspot — split into units` (the tag names the same agent as the label, as every hive-filed issue title does), labels `agent/ci-maintainer` + `kind/cleanup`, origin `governor`, body marker ``, evidence table, the top-level units, a concrete split proposal and the don't-splinter rule. While that issue is open no second one is filed; after it closes the file waits `hotspot_refile_days` before it can be filed again. **Capped.** At most `hotspot_max_open` modularize issues are open per repo at once (an issue that already has a PR still counts) and at most `hotspot_max_per_pass` are filed per advisor pass; the highest-ranked uncapped hotspot is filed when a slot frees, and the advisor logs one INFO line per pass when the cap holds it back. Issues go through the writeback gate as `issue_file` (a paused repo or `writeback.per_repo[].mode: off` stops them) and are skipped when the GitHub budget governor is skipping optional sweeps. - **Where to look.** `GET /api/hotspots` (or `hivectl governor hotspots [--repo owner/name]`) lists every hotspot with its recommendation and issue; `/api/status` carries `hotspots: {count, actionable, filed}`. State lives in `/data/hotspots.json`; the analysis runs at most hourly in the eval cycle, the intake on every merge-train sweep. A PR the train has not seen for two hours has its interval closed at its last sighting. | Key | Default | Meaning | diff --git a/src/docs/review-swarm.md b/src/docs/review-swarm.md index ea54ebfe82..296638500a 100644 --- a/src/docs/review-swarm.md +++ b/src/docs/review-swarm.md @@ -102,7 +102,7 @@ The default human threshold is `high`. Review-triggered fix cycles use the same ### Out-of-scope backlog filing -When the relay accepts a review verdict, cited out-of-scope findings (`review_scope: "out-of-scope"` with `file` and positive `line`) are filed as follow-up issues labeled `agent/reviewer` (the reviewer lane provenance/routing label — see [labels-and-control-signals.md](labels-and-control-signals/reference.md#label-axes); the retired `from-review`, `origin/review`, and `origin/reviewer` names are accepted in config and migrated on open items). Each issue is titled `[reviewer] Review backlog (): ` — like every issue the hive files, the title starts with the filing agent in square brackets (`issueshape.TitleFor`, applied once more in `CreateIssue` so no filer can forget it, and ignored by title dedupe so items filed before the tag still match). Each issue body links back to the reviewed PR and records the perspective, severity, evidence location, and finding summary. The relay deduplicates against open issues through the normal issue-create path and also persists a finding key in `/data/review-backlog-issues.json`, so re-reviewing a new commit does not file the same backlog issue or summary comment again. +When the relay accepts a review verdict, cited out-of-scope findings (`review_scope: "out-of-scope"` with `file` and positive `line`) are filed as follow-up issues labeled `agent/reviewer` (the reviewer lane provenance/routing label — see [labels-and-control-signals.md](labels-and-control-signals/reference.md#label-axes); the retired `from-review`, `origin/review`, and `origin/reviewer` names are accepted in config and migrated on open items). Each issue is titled `[reviewer] Review backlog (): ` — like every issue the hive files, the title starts with the filing agent in square brackets (`issueshape.AgentIssueTitle`, the one function every hive issue-creation path runs its title through — `CreateIssue`, the raw advisory/recommendations/upstream-watch creates and the egress proxy — so no filer can forget it; it puts the tag first, never doubles it, and title dedupe ignores it so items filed before the tag still match). Each issue body links back to the reviewed PR and records the perspective, severity, evidence location, and finding summary. The relay deduplicates against open issues through the normal issue-create path and also persists a finding key in `/data/review-backlog-issues.json`, so re-reviewing a new commit does not file the same backlog issue or summary comment again. The PR receives one summary comment listing the backlog issues filed from that review. Filing is enabled by default and bounded by `review.max_out_of_scope_backlog_issues` (default `3`) per PR; set `review.out_of_scope_backlog_disabled: true` to opt out. diff --git a/src/pkg/dashboard/api_acmm_eval_test.go b/src/pkg/dashboard/api_acmm_eval_test.go index 9d8d07657d..fcf081d94d 100644 --- a/src/pkg/dashboard/api_acmm_eval_test.go +++ b/src/pkg/dashboard/api_acmm_eval_test.go @@ -769,9 +769,11 @@ func TestHandleACMMCreateIssue_BodyFormattingAndLabels(t *testing.T) { t.Fatal("expected title in captured issue request") } title := body["title"].(string) - wantTitlePrefix := "[ACMM L0] Add " + criterion.Name - if title != wantTitlePrefix { - t.Fatalf("title = %q, want %q", title, wantTitlePrefix) + // The dashboard files it, so the title leads with [dashboard]; the + // operator-facing [ACMM L0] bracket is the subject and stays. + wantTitle := "[dashboard] [ACMM L0] Add " + criterion.Name + if title != wantTitle { + t.Fatalf("title = %q, want %q", title, wantTitle) } issueBody := body["body"].(string) diff --git a/src/pkg/dashboard/stage_tracker_motion_test.go b/src/pkg/dashboard/stage_tracker_motion_test.go index 8e3d42fcd0..5319d9c6cb 100644 --- a/src/pkg/dashboard/stage_tracker_motion_test.go +++ b/src/pkg/dashboard/stage_tracker_motion_test.go @@ -475,6 +475,8 @@ func TestStageTrackerMotionRowStamp(t *testing.T) { jsFunc(t, html, "stageTrackerRowHtml"), jsFunc(t, html, "stageTrackerPRIssueSlot"), jsFunc(t, html, "stageTrackerClosedChipHtml"), + jsFunc(t, html, "stageTrackerSplitTitleTag"), + jsFunc(t, html, "stageTrackerTitleHtml"), jsFunc(t, html, "stageTrackerItemURL"), }, "\n") + ` const now = Date.parse('2026-01-01T12:00:00Z'); @@ -610,6 +612,8 @@ func TestStageTrackerMotionPreviewSample(t *testing.T) { jsFunc(t, html, "stageTrackerRowHtml"), jsFunc(t, html, "stageTrackerPRIssueSlot"), jsFunc(t, html, "stageTrackerClosedChipHtml"), + jsFunc(t, html, "stageTrackerSplitTitleTag"), + jsFunc(t, html, "stageTrackerTitleHtml"), jsFunc(t, html, "stageTrackerItemURL"), jsFunc(t, html, "stageTrackerItemKey"), jsFunc(t, html, "stageTrackerMoveAttrs"), diff --git a/src/pkg/dashboard/stage_tracker_repo_grouping_test.go b/src/pkg/dashboard/stage_tracker_repo_grouping_test.go index 0e65758049..ce2e5e117d 100644 --- a/src/pkg/dashboard/stage_tracker_repo_grouping_test.go +++ b/src/pkg/dashboard/stage_tracker_repo_grouping_test.go @@ -201,6 +201,8 @@ func stageTrackerRepoGroupingHarness(t *testing.T, html string) string { jsFunc(t, html, "stageTrackerRowHtml"), jsFunc(t, html, "stageTrackerPRIssueSlot"), jsFunc(t, html, "stageTrackerClosedChipHtml"), + jsFunc(t, html, "stageTrackerSplitTitleTag"), + jsFunc(t, html, "stageTrackerTitleHtml"), jsFunc(t, html, "stageTrackerItemURL"), jsFunc(t, html, "stageTrackerItemKey"), jsFunc(t, html, "stageTrackerMoveAttrs"), diff --git a/src/pkg/dashboard/stage_tracker_ui_prelude_test.go b/src/pkg/dashboard/stage_tracker_ui_prelude_test.go index cc042a8ab2..7b5cb5ead3 100644 --- a/src/pkg/dashboard/stage_tracker_ui_prelude_test.go +++ b/src/pkg/dashboard/stage_tracker_ui_prelude_test.go @@ -152,6 +152,8 @@ func stageTrackerRowsPreludeJS(t *testing.T, html string) string { jsFunc(t, html, "stageTrackerRowHtml"), jsFunc(t, html, "stageTrackerPRIssueSlot"), jsFunc(t, html, "stageTrackerClosedChipHtml"), + jsFunc(t, html, "stageTrackerSplitTitleTag"), + jsFunc(t, html, "stageTrackerTitleHtml"), jsFunc(t, html, "stageTrackerItemURL"), jsFunc(t, html, "stageTrackerItemKey"), jsFunc(t, html, "stageTrackerMoveAttrs"), diff --git a/src/pkg/dashboard/stage_tracker_ui_rows_test.go b/src/pkg/dashboard/stage_tracker_ui_rows_test.go index 0128a66080..c3383fe467 100644 --- a/src/pkg/dashboard/stage_tracker_ui_rows_test.go +++ b/src/pkg/dashboard/stage_tracker_ui_rows_test.go @@ -41,6 +41,19 @@ assert.ok(!strip(row).includes('✓'), 'no ✓ in the strip before the PR merges assert.ok(tooltip(row).includes('Claimed by scanner') && tooltip(row).includes('@alice') && tooltip(row).includes('30 min ago'), tooltip(row)); assert.ok(!row.includes('✓'), 'no text check glyphs'); +// A hive-filed issue leads with its filing agent in brackets; the tag is +// drawn once as a chip ahead of the title, the title text no longer repeats +// it, and the full title stays in the tooltip. A bracket that is not an +// agent slug is part of the subject and stays in the title. +row = stageTrackerRowHtml({ repo: 'acme/console', number: 8, kind: 'issue', title: '[reviewer] Review backlog (security): token ', url: 'https://x/8', stage: 0, caption: 'No stage recorded yet' }, stages, ctx); +assert.ok(row.includes('reviewer Review backlog (security): token <logged>'), 'agent tag chip then the untagged title: ' + row); +assert.strictEqual((row.match(/\[reviewer\]/g) || []).length, 2, 'the tag appears only in the chip tooltip and the title tooltip, never twice in the text: ' + row); +row = stageTrackerRowHtml({ repo: 'acme/console', number: 10, kind: 'issue', title: '[ACMM L0] Add CI/CD pipeline', url: 'https://x/10', stage: 0, caption: 'No stage recorded yet' }, stages, ctx); +assert.ok(!row.includes('ham-title-tag') && row.includes('[ACMM L0] Add CI/CD pipeline'), 'a non-agent bracket is not a chip: ' + row); +// The chip also leads a PR row's linked-issue slot. +row = stageTrackerRowHtml({ repo: 'acme/console', number: 12, kind: 'pr', title: 'fix it', url: 'https://x/12', stage: 50, caption: 'In review', nested_under: 8, linked_issues: [{ number: 8, state: 'open', title: '[scanner] logscrub misses attrs', url: 'https://x/8' }] }, stages, ctx); +assert.ok(row.includes('scanner logscrub misses attrs'), 'linked issue slot draws the chip: ' + row); + // Open but held: the Open segment itself names the hold state and the row // tooltip names the matching hold label, while the trailing flag pill remains. row = stageTrackerRowHtml({ repo: 'acme/console', number: 9, kind: 'pr', title: 'Paused', stage: 0, caption: 'No stage recorded yet', labels: ['do-not-merge/hold'], modifiers: ['hold'] }, stages, ctx); diff --git a/src/pkg/dashboard/static-src/css/tracker.css b/src/pkg/dashboard/static-src/css/tracker.css index ed0b5f71c7..0e2dc5a3b6 100644 --- a/src/pkg/dashboard/static-src/css/tracker.css +++ b/src/pkg/dashboard/static-src/css/tracker.css @@ -160,6 +160,7 @@ .ham-issue-closed .ham-closed-not-planned { color: var(--text-faint); font-style: italic; } /* Issue slot naming an issue the PR only refers to (`Refs #N`, a `(#N, part 1)` title): a muted "refs" chip tells it from a closing link. */ .ham-issue-refs-chip { flex: 0 0 auto; margin-left: var(--sp-1); font-style: italic; } + .ham-title-tag { flex: 0 0 auto; font-family: var(--font-mono); } /* Repo chip before the number: monospace, tinted per repo from the --ham-repo-tint-N palette (slot = string hash), muted for the primary repo; a button that sets the Repo filter. Owner/repo rides its title. */ diff --git a/src/pkg/dashboard/static-src/js/tracker-row.js b/src/pkg/dashboard/static-src/js/tracker-row.js index 02a5af7967..900fc9b099 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row.js +++ b/src/pkg/dashboard/static-src/js/tracker-row.js @@ -1219,6 +1219,24 @@ const tip = repo + (primary ? ' (primary repo)' : '') + (active ? ' — showing only this repo; click to show all repos' : ' — click to show only this repo'); return ``; } + // Every hive-filed issue title leads with its filing agent in brackets + // (`[scanner] …`, `[reviewer] Review backlog (security): …`). The tag is + // drawn once, as a chip ahead of the title, and the title text that + // follows no longer repeats it; the full title stays in the tooltip. A + // bracket that is not an agent slug (`[ACMM L0]`, `[Tests]`) is part of + // the subject and is left in the title. + function stageTrackerSplitTitleTag(title) { + const m = /^\s*\[([a-z0-9][a-z0-9_.-]*)\]\s*(.*)$/s.exec(String(title || '')); + if (!m || !m[2]) return { tag: '', text: String(title || '') }; + return { tag: m[1], text: m[2] }; + } + function stageTrackerTitleHtml(title, extraClass) { + const full = String(title || ''); + const { tag, text } = stageTrackerSplitTitleTag(full); + const cls = 'ham-title' + (extraClass ? ' ' + extraClass : ''); + const chip = tag ? `${esc(tag)} ` : ''; + return `${chip}${esc(text)}`; + } // Column name for a group header's distribution tooltip (as the column header draws it). function stageTrackerColName(idx, stages) { if (idx >= STAGE_TRACKER_PATH.length) return 'Merged'; @@ -1352,7 +1370,7 @@ leadHtml = `
${stageTrackerIcon('issue', 'ham-kind-ico')}${chip} #${Number(item.number) || 0} - ${esc(title)} + ${stageTrackerTitleHtml(title)} ${item.claim_reference ? `refs` : ''} ${typeof stageTrackerLinkedElsewhereHtml === 'function' ? stageTrackerLinkedElsewhereHtml(item) : ''} ${item.is_tracker ? `tracker${item.children && item.children.total ? ' ' + Number(item.children.completed) + '/' + Number(item.children.total) : ''}` : ''} @@ -1364,7 +1382,7 @@ ? `
${stageTrackerIcon('issue', 'ham-kind-ico')}${chip} #${li.number} - ${li.title ? `${esc(li.title)}` : `${esc(li.placeholder)}`}${li.soft ? ` refs` : ''}${li.closed ? ' ' + stageTrackerClosedChipHtml(item, li) : ''} + ${li.title ? stageTrackerTitleHtml(li.title) : `${esc(li.placeholder)}`}${li.soft ? ` refs` : ''}${li.closed ? ' ' + stageTrackerClosedChipHtml(item, li) : ''}
` : `
${stageTrackerIcon('issue', 'ham-kind-ico')}${chip} diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index bc2b8b0576..f16fe85064 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -1489,6 +1489,7 @@ .ham-issue-closed .ham-closed-not-planned { color: var(--text-faint); font-style: italic; } /* Issue slot naming an issue the PR only refers to (`Refs #N`, a `(#N, part 1)` title): a muted "refs" chip tells it from a closing link. */ .ham-issue-refs-chip { flex: 0 0 auto; margin-left: var(--sp-1); font-style: italic; } + .ham-title-tag { flex: 0 0 auto; font-family: var(--font-mono); } /* Repo chip before the number: monospace, tinted per repo from the --ham-repo-tint-N palette (slot = string hash), muted for the primary repo; a button that sets the Repo filter. Owner/repo rides its title. */ @@ -17438,6 +17439,24 @@

Where to get help

const tip = repo + (primary ? ' (primary repo)' : '') + (active ? ' — showing only this repo; click to show all repos' : ' — click to show only this repo'); return ``; } + // Every hive-filed issue title leads with its filing agent in brackets + // (`[scanner] …`, `[reviewer] Review backlog (security): …`). The tag is + // drawn once, as a chip ahead of the title, and the title text that + // follows no longer repeats it; the full title stays in the tooltip. A + // bracket that is not an agent slug (`[ACMM L0]`, `[Tests]`) is part of + // the subject and is left in the title. + function stageTrackerSplitTitleTag(title) { + const m = /^\s*\[([a-z0-9][a-z0-9_.-]*)\]\s*(.*)$/s.exec(String(title || '')); + if (!m || !m[2]) return { tag: '', text: String(title || '') }; + return { tag: m[1], text: m[2] }; + } + function stageTrackerTitleHtml(title, extraClass) { + const full = String(title || ''); + const { tag, text } = stageTrackerSplitTitleTag(full); + const cls = 'ham-title' + (extraClass ? ' ' + extraClass : ''); + const chip = tag ? `${esc(tag)} ` : ''; + return `${chip}${esc(text)}`; + } // Column name for a group header's distribution tooltip (as the column header draws it). function stageTrackerColName(idx, stages) { if (idx >= STAGE_TRACKER_PATH.length) return 'Merged'; @@ -17571,7 +17590,7 @@

Where to get help

leadHtml = `
${stageTrackerIcon('issue', 'ham-kind-ico')}${chip} #${Number(item.number) || 0} - ${esc(title)} + ${stageTrackerTitleHtml(title)} ${item.claim_reference ? `refs` : ''} ${typeof stageTrackerLinkedElsewhereHtml === 'function' ? stageTrackerLinkedElsewhereHtml(item) : ''} ${item.is_tracker ? `tracker${item.children && item.children.total ? ' ' + Number(item.children.completed) + '/' + Number(item.children.total) : ''}` : ''} @@ -17583,7 +17602,7 @@

Where to get help

? `
${stageTrackerIcon('issue', 'ham-kind-ico')}${chip} #${li.number} - ${li.title ? `${esc(li.title)}` : `${esc(li.placeholder)}`}${li.soft ? ` refs` : ''}${li.closed ? ' ' + stageTrackerClosedChipHtml(item, li) : ''} + ${li.title ? stageTrackerTitleHtml(li.title) : `${esc(li.placeholder)}`}${li.soft ? ` refs` : ''}${li.closed ? ' ' + stageTrackerClosedChipHtml(item, li) : ''}
` : `
${stageTrackerIcon('issue', 'ham-kind-ico')}${chip} diff --git a/src/pkg/github/advisory.go b/src/pkg/github/advisory.go index 82e096a9d4..b19668703a 100644 --- a/src/pkg/github/advisory.go +++ b/src/pkg/github/advisory.go @@ -14,6 +14,7 @@ import ( gh "github.com/google/go-github/v72/github" "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/issueshape" "github.com/hivecommons/hive/pkg/effects" "github.com/hivecommons/hive/crux/logscrub" ) @@ -25,6 +26,14 @@ const ( advisoryLabelClr = "0e8a16" ) +// isAdvisoryTitle reports whether title is the advisory issue's, with the +// leading `[governor]` tag ignored: an advisory issue filed before titles +// carried the filer is the same standing issue as one filed after, so a +// hive upgrade never opens a second advisory per repo. +func isAdvisoryTitle(title string) bool { + return issueshape.SameTitle(title, advisoryTitle) +} + // IssuesDisabledError reports that the advisory issue cannot be created or // resolved because the target repo has its Issues feature turned off // (has_issues=false). GitHub disables Issues on forks by default, so this is @@ -238,7 +247,7 @@ func (c *Client) EnsureAdvisoryIssue(ctx context.Context, repo string) (int, err } req := &gh.IssueRequest{ - Title: gh.Ptr(advisoryTitle), + Title: gh.Ptr(issueshape.AgentIssueTitle(config.OriginSourceGovernor, advisoryTitle)), Body: gh.Ptr(body), } var labels []string @@ -779,7 +788,7 @@ func (c *Client) findAdvisoryIssueListed(ctx context.Context, owner, repo string }) if err == nil { for _, issue := range result.Issues { - if issue.GetTitle() == advisoryTitle { + if isAdvisoryTitle(issue.GetTitle()) { return issue.GetNumber(), nil } } @@ -796,7 +805,7 @@ func (c *Client) findAdvisoryIssueListed(ctx context.Context, owner, repo string issues, _, listErr := c.client.Issues.ListByRepo(ctx, owner, repo, opts) if listErr == nil { for _, issue := range issues { - if issue.GetTitle() == advisoryTitle { + if isAdvisoryTitle(issue.GetTitle()) { return issue.GetNumber(), nil } } @@ -820,7 +829,7 @@ func (c *Client) findAdvisoryIssueListed(ctx context.Context, owner, repo string if issue.IsPullRequest() { continue } - if issue.GetTitle() == advisoryTitle { + if isAdvisoryTitle(issue.GetTitle()) { c.logger.Info("found advisory issue via title scan (missing label)", slog.Int("number", issue.GetNumber())) c.ensureAdvisoryLabel(ctx, owner, repo, issue.GetNumber()) return issue.GetNumber(), nil @@ -874,7 +883,7 @@ func (c *Client) findClosedAdvisoryIssue(ctx context.Context, owner, repo string if issue.IsPullRequest() { continue } - if issue.GetTitle() == advisoryTitle { + if isAdvisoryTitle(issue.GetTitle()) { return issue.GetNumber(), true } } diff --git a/src/pkg/github/advisory_forgestate.go b/src/pkg/github/advisory_forgestate.go index 1d3410256f..19ae09d894 100644 --- a/src/pkg/github/advisory_forgestate.go +++ b/src/pkg/github/advisory_forgestate.go @@ -106,7 +106,7 @@ func (c *Client) findAdvisoryIssueCached(ctx context.Context, owner, repo string continue } issue, _, err := c.client.Issues.Get(ctx, owner, repo, n) - if err != nil || issue.IsPullRequest() || issue.GetTitle() != advisoryTitle { + if err != nil || issue.IsPullRequest() || !isAdvisoryTitle(issue.GetTitle()) { continue } if issue.GetState() != "open" { @@ -141,7 +141,7 @@ func (c *Client) confirmAdvisoryIssue(ctx context.Context, store forgeStateReade return 0, errAdvisoryCacheMiss case getErr != nil: return 0, fmt.Errorf("confirming advisory issue #%d: %w", n, getErr) - case issue.IsPullRequest() || issue.GetTitle() != advisoryTitle: + case issue.IsPullRequest() || !isAdvisoryTitle(issue.GetTitle()): c.rememberAdvisoryIssue(full, 0) return 0, errAdvisoryCacheMiss case issue.GetState() == "open": diff --git a/src/pkg/github/issue_request_watcher.go b/src/pkg/github/issue_request_watcher.go index ef716e2317..65df5c0fba 100644 --- a/src/pkg/github/issue_request_watcher.go +++ b/src/pkg/github/issue_request_watcher.go @@ -1287,9 +1287,9 @@ func (c *Client) createIssue(ctx context.Context, req CreateIssueRequest) (Creat } // Every issue the hive files names its filer in the title (`[reviewer] // Review backlog (security): …`). Hive-internal filers and the watcher - // both land here, so a caller cannot forget it; TitleFor is idempotent + // both land here, so a caller cannot forget it; AgentIssueTitle is idempotent // for a title an agent already tagged. - title = issueshape.TitleFor(req.TitleFiler(), title) + title = issueshape.AgentIssueTitle(req.TitleFiler(), title) // Same posture and same placement as validateRepoRef above: a request that // is still carrying its template cannot become a useful issue, and unlike a // bad repo ref it would SUCCEED, leaving a human to triage an empty report diff --git a/src/pkg/github/recommendations.go b/src/pkg/github/recommendations.go index d0fe3332df..14bbc74be1 100644 --- a/src/pkg/github/recommendations.go +++ b/src/pkg/github/recommendations.go @@ -10,6 +10,7 @@ import ( gh "github.com/google/go-github/v72/github" "github.com/hivecommons/hive/pkg/advisory" "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/issueshape" "github.com/hivecommons/hive/crux/logscrub" ) @@ -96,7 +97,7 @@ func (c *Client) PostRecommendations(ctx context.Context, repo, title, body stri } } created, _, err := c.client.Issues.Create(ctx, owner, repoName, &gh.IssueRequest{ - Title: gh.Ptr(title), + Title: gh.Ptr(issueshape.AgentIssueTitle(config.OriginSourceGovernor, title)), Body: gh.Ptr(body), Labels: gh.Ptr(labels), }) @@ -174,7 +175,7 @@ func (c *Client) findRecommendationsIssue(ctx context.Context, owner, repo, titl return nil, err } for _, is := range issues { - if is.IsPullRequest() || strings.TrimSpace(is.GetTitle()) != title { + if is.IsPullRequest() || !issueshape.SameTitle(is.GetTitle(), title) { continue } if c.appAuth == nil { diff --git a/src/pkg/github/review_backlog.go b/src/pkg/github/review_backlog.go index b1e6ecf904..e44f4043be 100644 --- a/src/pkg/github/review_backlog.go +++ b/src/pkg/github/review_backlog.go @@ -596,7 +596,7 @@ func reviewBacklogIssueTitle(p review.Perspective, f outputschema.Finding) strin if title == "" { title = "out-of-scope review finding" } - return issueshape.TitleFor(config.OriginSourceReviewer, fmt.Sprintf("Review backlog (%s): %s", p, title)) + return issueshape.AgentIssueTitle(config.OriginSourceReviewer, fmt.Sprintf("Review backlog (%s): %s", p, title)) } func reviewBacklogSummaryComment(issues []reviewBacklogFiled, cap int) string { diff --git a/src/pkg/github/standing_issues.go b/src/pkg/github/standing_issues.go index 4a4619124e..2ee6960c72 100644 --- a/src/pkg/github/standing_issues.go +++ b/src/pkg/github/standing_issues.go @@ -47,7 +47,7 @@ const ( ) func standingMetaIssueKindFor(title, author string, labels []string) standingMetaIssueKind { - if title == advisoryTitle { + if isAdvisoryTitle(title) { return standingMetaHiveAdvisory } for _, label := range labels { diff --git a/src/pkg/hotspot/hotspot_test.go b/src/pkg/hotspot/hotspot_test.go index 898d8483fe..e276091ae7 100644 --- a/src/pkg/hotspot/hotspot_test.go +++ b/src/pkg/hotspot/hotspot_test.go @@ -284,7 +284,7 @@ func TestFilerDedupeAndRefileWindow(t *testing.T) { if !strings.HasPrefix(cr.body, Marker(h.File)) { t.Errorf("body must start with dedupe marker, got %q", cr.body[:60]) } - if cr.title != "[governor] refactor: pkg/dashboard/api.go is a merge hotspot — split into 4 units" { + if cr.title != "[ci-maintainer] refactor: pkg/dashboard/api.go is a merge hotspot — split into 4 units" { t.Errorf("title=%q", cr.title) } if strings.Join(cr.labels, ",") != "agent/ci-maintainer,kind/cleanup" { @@ -361,7 +361,7 @@ func TestBodyGolden(t *testing.T) { if !strings.Contains(gb, "**generated**") || strings.Contains(gb, "## Split proposal") { t.Errorf("generated body wrong:\n%s", gb) } - if got := Title(gen, 4); got != "[governor] refactor: pkg/dashboard/static/index.html is a merge hotspot — split its source pkg/dashboard/static-src into 4 units" { + if got := Title(gen, 4); got != "[ci-maintainer] refactor: pkg/dashboard/static/index.html is a merge hotspot — split its source pkg/dashboard/static-src into 4 units" { t.Errorf("generated title=%q", got) } } diff --git a/src/pkg/hotspot/issue.go b/src/pkg/hotspot/issue.go index 8eb07de583..60bb59cdb1 100644 --- a/src/pkg/hotspot/issue.go +++ b/src/pkg/hotspot/issue.go @@ -12,13 +12,18 @@ import ( "github.com/hivecommons/hive/pkg/issueshape" ) +// Agent is the agent lane a hotspot issue is filed for: the title's +// `[ci-maintainer]` tag and the agent/ci-maintainer label name the same +// agent, the one that works the split. +const Agent = "ci-maintainer" + // Labels applied to every modularize issue. Both exist on hivecommons/hive; // the writer's label-ensure step creates them elsewhere. -var Labels = []string{"agent/ci-maintainer", "kind/cleanup"} +var Labels = []string{config.AgentLaneLabel(Agent), "kind/cleanup"} -// Title is the issue title for a hotspot. The governor's hotspot advisor -// files it, so it carries the `[governor]` tag every hive-filed issue title -// starts with; the agent/ci-maintainer label says who works it. +// Title is the issue title for a hotspot. It starts with the `[ci-maintainer]` +// tag every hive-filed issue title carries, matching its agent/ci-maintainer +// label (the governor's hotspot advisor files it on that lane's behalf). func Title(h Hotspot, units int) string { var title string switch h.Recommendation { @@ -29,7 +34,7 @@ func Title(h Hotspot, units int) string { default: title = fmt.Sprintf("refactor: %s is a merge hotspot — split into %d units", h.File, units) } - return issueshape.TitleFor(config.OriginSourceGovernor, title) + return issueshape.AgentIssueTitle(Agent, title) } // Body renders the issue body: plain-language summary (≤ 300 words), diff --git a/src/pkg/issueshape/choke_point_test.go b/src/pkg/issueshape/choke_point_test.go new file mode 100644 index 0000000000..8df80b8332 --- /dev/null +++ b/src/pkg/issueshape/choke_point_test.go @@ -0,0 +1,102 @@ +package issueshape_test + +import ( + "os" + "path/filepath" + "regexp" + "strings" + "testing" + + "github.com/hivecommons/hive/pkg/fleetreport" + "github.com/hivecommons/hive/pkg/hotspot" + "github.com/hivecommons/hive/pkg/issueshape" + "github.com/hivecommons/hive/pkg/upstreamwatch" +) + +// hiveTitleRE is the shape every hive-filed issue title has: the filing +// agent in brackets, then a space, then the subject. +var hiveTitleRE = regexp.MustCompile(`^\[[a-z0-9][a-z0-9_.-]*\] \S`) + +// Every Go file that creates a GitHub issue directly — a go-github +// Issues.Create call, or a CreateIssueRequest handed to the client — must +// run the title through issueshape.AgentIssueTitle in that same file (the +// client's createIssue does it for every CreateIssueRequest). A new raw +// create that skips the tag fails here, not in production. +func TestEveryIssueCreatePathTagsTheTitle(t *testing.T) { + root := filepath.Join("..", "..") + rawCreate := regexp.MustCompile(`\.Issues\.Create\(`) + var rawSites []string + err := filepath.WalkDir(root, func(path string, d os.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() { + if path == root { + return nil + } + if name := d.Name(); name == "node_modules" || name == "testdata" || strings.HasPrefix(name, ".") { + return filepath.SkipDir + } + return nil + } + if !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") { + return nil + } + src, err := os.ReadFile(path) + if err != nil { + return err + } + if !rawCreate.Match(src) { + return nil + } + rel, _ := filepath.Rel(root, path) + rawSites = append(rawSites, rel) + if !strings.Contains(string(src), "issueshape.AgentIssueTitle(") { + t.Errorf("%s calls Issues.Create without running the title through issueshape.AgentIssueTitle", rel) + } + return nil + }) + if err != nil { + t.Fatal(err) + } + // The scan must have seen the client's own create path, or it walked + // the wrong tree and proved nothing. + if !containsSuffix(rawSites, filepath.Join("pkg", "github", "issue_request_watcher.go")) { + t.Fatalf("scan did not reach the client's createIssue; raw create sites seen: %v", rawSites) + } +} + +func containsSuffix(paths []string, suffix string) bool { + for _, p := range paths { + if strings.HasSuffix(p, suffix) { + return true + } + } + return false +} + +// Each title builder a hive filer uses produces a `[] …` title that +// names the agent its label names. +func TestProducerTitlesStartWithTheirAgentTag(t *testing.T) { + cases := map[string]struct{ agent, title string }{ + "hotspot (ci-maintainer)": {hotspot.Agent, hotspot.Title(hotspot.Hotspot{File: "src/pkg/a.go"}, 4)}, + "upstream watch (governor)": {"governor", upstreamwatch.RenderIssue("acme/up", + upstreamwatch.Item{Kind: upstreamwatch.KindPR, Ref: "upstream#9", Title: "fix: thing"}, + upstreamwatch.Judgement{Applicable: true}, "").Title}, + "self report (selfreport)": {"selfreport", fleetreport.SelfReportTitlePrefix + "unclassified_error_repeated: x"}, + "review backlog (reviewer)": {"reviewer", issueshape.AgentIssueTitle("reviewer", "Review backlog (security): token logged")}, + "dedupe advisory (dedupe)": {"dedupe", issueshape.AgentIssueTitle("dedupe", "triage: duplicate and overlapping open issues/PRs to consolidate")}, + } + for name, tc := range cases { + if !hiveTitleRE.MatchString(tc.title) { + t.Errorf("%s: title %q does not start with an [agent] tag", name, tc.title) + continue + } + if got := issueshape.AgentPrefix(tc.title); got != tc.agent { + t.Errorf("%s: title %q is tagged %q, want %q", name, tc.title, got, tc.agent) + } + if again := issueshape.AgentIssueTitle(tc.agent, tc.title); again != tc.title { + t.Errorf("%s: re-tagging changed the title: %q -> %q", name, tc.title, again) + } + } +} diff --git a/src/pkg/issueshape/issueshape.go b/src/pkg/issueshape/issueshape.go index 58100f1208..2ce19a75d7 100644 --- a/src/pkg/issueshape/issueshape.go +++ b/src/pkg/issueshape/issueshape.go @@ -13,7 +13,8 @@ var ( UnsubstitutedTemplatePlaceholder = cruxissueshape.UnsubstitutedTemplatePlaceholder BodyHasMisEscapedNewlines = cruxissueshape.BodyHasMisEscapedNewlines UnchosenOptionList = cruxissueshape.UnchosenOptionList - TitleFor = cruxissueshape.TitleFor + AgentIssueTitle = cruxissueshape.AgentIssueTitle + IsFilerTag = cruxissueshape.IsFilerTag HasAgentPrefix = cruxissueshape.HasAgentPrefix AgentPrefix = cruxissueshape.AgentPrefix StripAgentPrefix = cruxissueshape.StripAgentPrefix diff --git a/src/pkg/upstreamwatch/github_filer.go b/src/pkg/upstreamwatch/github_filer.go index 6c4e6c72f1..df32dfa88e 100644 --- a/src/pkg/upstreamwatch/github_filer.go +++ b/src/pkg/upstreamwatch/github_filer.go @@ -9,6 +9,9 @@ import ( "time" gh "github.com/google/go-github/v72/github" + + "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/issueshape" ) // stateReasonNotPlanned is the GitHub state_reason of an issue closed as @@ -116,7 +119,9 @@ func (g *GitHubFiler) waitFor(ctx context.Context, d time.Duration) error { // makes a store loss, or a save failure after a successful create, re-find // the existing fork issue instead of filing a second one (#11579). func (g *GitHubFiler) File(ctx context.Context, issue Issue) (int, error) { - req := &gh.IssueRequest{Title: gh.Ptr(issue.Title), Body: gh.Ptr(issue.Body)} + // RenderIssue already tags the title; this is the raw create, so it is + // the last place the `[governor]` tag can be guaranteed. + req := &gh.IssueRequest{Title: gh.Ptr(issueshape.AgentIssueTitle(config.OriginSourceGovernor, issue.Title)), Body: gh.Ptr(issue.Body)} if len(issue.Labels) > 0 { labels := append([]string(nil), issue.Labels...) req.Labels = &labels diff --git a/src/pkg/upstreamwatch/render.go b/src/pkg/upstreamwatch/render.go index 1ae4fd725d..9a1ea9128a 100644 --- a/src/pkg/upstreamwatch/render.go +++ b/src/pkg/upstreamwatch/render.go @@ -95,7 +95,7 @@ func RenderIssue(upstream string, item Item, j Judgement, label string) Issue { // The watch files on the governor's behalf; origin/governor is its // provenance label (the forge auto-creates unknown labels on create). labels = config.WithOriginLabel(labels, config.OriginSourceGovernor) - return Issue{Title: issueshape.TitleFor(config.OriginSourceGovernor, titlePrefix+title), Body: b.String(), Labels: labels} + return Issue{Title: issueshape.AgentIssueTitle(config.OriginSourceGovernor, titlePrefix+title), Body: b.String(), Labels: labels} } // summarize trims the upstream body to a bounded summary. diff --git a/src/pkg/upstreamwatch/render_test.go b/src/pkg/upstreamwatch/render_test.go index 9fe6ac3b1a..601b58479f 100644 --- a/src/pkg/upstreamwatch/render_test.go +++ b/src/pkg/upstreamwatch/render_test.go @@ -175,7 +175,7 @@ func TestGitHubFiler_File(t *testing.T) { if err != nil || n != 77 { t.Fatalf("File = %d, %v", n, err) } - if !strings.Contains(body, `"labels":["upstream/port"]`) || !strings.Contains(body, `"title":"upstream: x"`) { + if !strings.Contains(body, `"labels":["upstream/port"]`) || !strings.Contains(body, `"title":"[governor] upstream: x"`) { t.Fatalf("request body = %s", body) }