Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(alint): findings 走 PR Review,按行 comment,超 5 条聚合 (#21732)

Arvin Xu248ebbc756ec
diff --git a/.agents/skills/alint-ruleset/SKILL.md b/.agents/skills/alint-ruleset/SKILL.md
index 630a5019780..f49bb4cefa0 100644
--- a/.agents/skills/alint-ruleset/SKILL.md
+++ b/.agents/skills/alint-ruleset/SKILL.md
@@ -89,8 +89,9 @@ interpret a skipped suite as a pass.
- **Runner** — `bun run check --alint` (changed lines by default; explicit paths lint whole
files), `bun run alint --dirty`, `bun run alint:audit`.
- **CI & reporting** — `.agents/scripts/check/alint.ts` (the `--alint` selector),
- `packages/alint/report.ts` (the ALint check run, its annotations, one PR summary comment
- with marker `<!-- alint-summary -->`, and a usage line), and the `ALint & Test Desktop App`
+ `packages/alint/report.ts` (the ALint check run, its annotations, one PR summary review
+ plus one inline comment per finding, aggregated per file above 5 findings, and a usage
+ line), and the `ALint & Test Desktop App`
job in `.github/workflows/test.yml`. The check is not required, so a red check informs
rather than blocks.
- **Scripts in this skill** — [`scripts/`](scripts/): `collect-rejections.ts`,
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index c7ca41a7380..6f6582637f5 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -260,7 +260,7 @@ jobs:
runs-on: ubuntu-latest
# checks + pull-requests: the alint steps publish an "ALint" check run and
- # keep one summary comment on the PR up to date.
+ # keep one summary review on the PR up to date.
permissions:
actions: read
checks: write
@@ -322,11 +322,16 @@ jobs:
# ---- alint: model-backed lint rules (packages/alint) on this push's diff ----
# Findings are published as a separate "ALint" check (red when a rule at
- # `error` level fires) plus one summary comment on the PR, rewritten on
- # every push. This job itself never fails because of alint. Skipped when
- # the provider secret is unavailable (forks) and for weekly release PRs and
- # pushes to main (see ALINT_SKIP_REASON). Runs here to reuse the root
- # install instead of paying for another job.
+ # `error` level fires) plus one PR review: its summary body is rewritten
+ # on every push, and every finding gets an inline comment on its own line
+ # — like an eslint run. A file that piles up more than 5 findings is
+ # commented once instead, which keeps a runaway run inside the 1000
+ # requests/hour GITHUB_TOKEN budget of the whole repository; at the
+ # observed volume (a handful of warnings, one per file) per-line comments
+ # cost one request each. This job itself never fails because of alint.
+ # Skipped when the provider secret is unavailable (forks) and for weekly
+ # release PRs and pushes to main (see ALINT_SKIP_REASON). Runs here to
+ # reuse the root install instead of paying for another job.
- name: alint · report a skipped run
if: ${{ !cancelled() && env.ALINT_API_KEY != '' && env.ALINT_SKIP_REASON != '' }}
run: echo "::notice::ALint skipped for this ${ALINT_SKIP_REASON}"
diff --git a/packages/alint/report.test.ts b/packages/alint/report.test.ts
index 6ce2c44b00d..336ce976a77 100644
--- a/packages/alint/report.test.ts
+++ b/packages/alint/report.test.ts
@@ -1,9 +1,12 @@
import { describe, expect, it } from 'vitest';
import {
- COMMENT_MARKER,
+ AGGREGATE_THRESHOLD,
+ REVIEW_MARKER,
+ findingMarker,
toAnnotations,
toConclusion,
+ toFindingComments,
toFindings,
toMarkdown,
toTitle,
@@ -114,6 +117,100 @@ describe('verdict', () => {
});
});
+describe('toFindingComments', () => {
+ const file = 'apps/server/src/services/x.ts';
+ const on = (line: number) =>
+ diagnostic({ loc: { start: { column: 0, line } }, message: `finding at ${line}` });
+ const commentsFor = (...lines: number[]) =>
+ toFindingComments(toFindings({ diagnostics: lines.map(on) }, '/repo'));
+
+ it('comments one line per finding, like an eslint run', () => {
+ expect(commentsFor(12, 40)).toEqual([
+ {
+ body: [
+ findingMarker(`${file}:12`),
+ '**`pmap-over-promise-all`** · error',
+ '',
+ 'finding at 12',
+ ].join('\n'),
+ key: `${file}:12`,
+ line: 12,
+ path: file,
+ side: 'RIGHT',
+ },
+ {
+ body: [
+ findingMarker(`${file}:40`),
+ '**`pmap-over-promise-all`** · error',
+ '',
+ 'finding at 40',
+ ].join('\n'),
+ key: `${file}:40`,
+ line: 40,
+ path: file,
+ side: 'RIGHT',
+ },
+ ]);
+ });
+
+ it('keys findings that share a line apart, so fixing one leaves no comment behind', () => {
+ const comments = toFindingComments(
+ toFindings(
+ {
+ diagnostics: [
+ diagnostic({ message: 'first rule' }),
+ diagnostic({ message: 'second rule', ruleId: 'lobehub/no-mode-flags' }),
+ diagnostic({ message: 'first rule, again' }),
+ ],
+ },
+ '/repo',
+ ),
+ );
+
+ expect(comments.map((comment) => comment.key)).toEqual([
+ `${file}:12:pmap-over-promise-all`,
+ `${file}:12:no-mode-flags`,
+ `${file}:12:pmap-over-promise-all#2`,
+ ]);
+ for (const comment of comments)
+ expect(comment.body.startsWith(findingMarker(comment.key))).toBe(true);
+ });
+
+ it(`keeps the per-line comments up to ${5} findings and aggregates above`, () => {
+ expect(commentsFor(1, 2, 3, 4, 5)).toHaveLength(AGGREGATE_THRESHOLD);
+
+ const [aggregated] = commentsFor(1, 2, 3, 4, 5, 6);
+ expect(aggregated.key).toBe(file);
+ expect(aggregated.line).toBe(1);
+ expect(aggregated.body).toContain('**ALint · 6 findings in this file**');
+ expect(aggregated.body.match(/^- /gm)).toHaveLength(6);
+ });
+
+ it('carries the suggestion inline, and leaves it out when the rule has none', () => {
+ const [withSuggestion] = toFindingComments(
+ toFindings({ diagnostics: [diagnostic()] }, '/repo'),
+ );
+ expect(withSuggestion.body).toContain('💡 use pMap with a cap');
+
+ const [without] = toFindingComments(
+ toFindings({ diagnostics: [diagnostic({ message: 'fans out' })] }, '/repo'),
+ );
+ expect(without.body).not.toContain('💡');
+ });
+
+ it('caps a run at 50 comments, like the annotations', () => {
+ const findings = toFindings(
+ {
+ diagnostics: Array.from({ length: 60 }, (_, index) =>
+ diagnostic({ filePath: `/repo/src/file-${index}.ts` }),
+ ),
+ },
+ '/repo',
+ );
+ expect(toFindingComments(findings)).toHaveLength(50);
+ });
+});
+
describe('toMarkdown', () => {
it('renders a marked comment with a linked row per finding and escaped cells', () => {
const markdown = toMarkdown(toFindings({ diagnostics: [diagnostic()] }, '/repo'), {
@@ -121,7 +218,7 @@ describe('toMarkdown', () => {
runUrl: 'https://example.com/run',
sha: 'abcdef1234567',
});
- expect(markdown.startsWith(COMMENT_MARKER)).toBe(true);
+ expect(markdown.startsWith(REVIEW_MARKER)).toBe(true);
expect(markdown).toContain('### ❌ ALint · 1 error');
expect(markdown).toContain(
'[`apps/server/src/services/x.ts:12`](https://github.com/lobehub/lobehub/blob/abcdef1234567/apps/server/src/services/x.ts#L12)',
diff --git a/packages/alint/report.ts b/packages/alint/report.ts
index ab29e4e8e7c..e4429e9413f 100644
--- a/packages/alint/report.ts
+++ b/packages/alint/report.ts
@@ -3,10 +3,22 @@
*
* - an "ALint" check run on the head commit, red when any finding is at
* `error` level, with the findings attached as line annotations;
- * - one summary comment on the open pull request for the branch, rewritten in
- * place on every push (created only once there is something to report);
+ * - one pull request review per PR: the summary body is rewritten in place on
+ * every push, plus a comment per finding on its own line, so it can be
+ * replied to and resolved where it was raised — files with more findings
+ * than AGGREGATE_THRESHOLD are commented once instead, to keep a run's
+ * request count bounded (created only once there is something to report);
* - the same table in the job's step summary.
*
+ * The review is submitted as `COMMENT`: it informs, it does not block. The
+ * ALint check is what turns red on errors.
+ *
+ * Every review comment costs a request, and GITHUB_TOKEN's budget is 1000
+ * requests/hour shared by the whole repository, so the shape follows the real
+ * numbers: a run finds a handful of findings spread over single lines (recent
+ * PRs: 0 errors, <=4 warnings, one per file), which is cheap to comment per
+ * line; a file that piles up findings is commented once instead.
+ *
* Calibration fixtures are dropped: bad fixtures fire by design and are
* checked by the fixture suite instead.
*
@@ -56,7 +68,23 @@ export interface Finding {
suggestion?: string;
}
-export const COMMENT_MARKER = '<!-- alint-summary -->';
+/** Marks the review summarizing the run, so later pushes update it in place. */
+export const REVIEW_MARKER = '<!-- alint-summary -->';
+
+/**
+ * Marks one inline comment and carries the key the next run looks it up by:
+ * `file:line` for a per-line comment, `file` for a file aggregated because it
+ * has too many findings.
+ */
+export const findingMarker = (key: string) => `<!-- alint-finding:${key} -->`;
+const markerKey = (body?: string | null) => body?.match(/<!-- alint-finding:(.+?) -->/)?.[1];
+
+/** Inline comments are capped like the annotations: 50 findings at most. */
+const INLINE_LIMIT = 50;
+
+/** A file with more findings than this gets one aggregated comment. */
+export const AGGREGATE_THRESHOLD = 5;
+
/**
* Calibration fixtures fire by design. Rules live in more than one place —
* repo-wide rules in `packages/alint`, package-level rules next to their
@@ -108,14 +136,16 @@ export const toTitle = (findings: Finding[]) => {
};
const cell = (value: string) => value.replaceAll('|', '\\|').replaceAll('\n', ' ');
+/** A list item is not a table cell: only newlines need collapsing there. */
+const oneLine = (value: string) => value.replaceAll('\n', ' ');
-/** Markdown body shared by the PR comment and the step summary. */
+/** Markdown body shared by the review and the step summary. */
export const toMarkdown = (
findings: Finding[],
{ repo, sha, runUrl, usage }: { repo: string; runUrl?: string; sha: string; usage?: string },
): string => {
const icon = findings.some((f) => f.severity === 'error') ? '❌' : findings.length ? '⚠️' : '✅';
- const lines = [`${COMMENT_MARKER}`, `### ${icon} ALint · ${toTitle(findings)}`, ''];
+ const lines = [`${REVIEW_MARKER}`, `### ${icon} ALint · ${toTitle(findings)}`, ''];
if (findings.length === 0) {
lines.push(`Checked the changed lines at \`${sha.slice(0, 7)}\`.`);
} else {
@@ -143,7 +173,7 @@ export const toMarkdown = (
/** Check-run annotations; the API accepts at most 50 per request. */
export const toAnnotations = (findings: Finding[]) =>
- findings.slice(0, 50).map((finding) => ({
+ findings.slice(0, INLINE_LIMIT).map((finding) => ({
annotation_level: finding.severity === 'error' ? 'failure' : 'warning',
end_line: finding.line,
message: finding.suggestion ? `${finding.message}\n\n${finding.suggestion}` : finding.message,
@@ -152,6 +182,94 @@ export const toAnnotations = (findings: Finding[]) =>
title: finding.rule,
}));
+export interface FindingComment {
+ body: string;
+ key: string;
+ line: number;
+ path: string;
+ side: 'RIGHT';
+}
+
+const severityIcon = (finding: Finding) => (finding.severity === 'error' ? '❌' : '⚠️');
+
+const toFindingBody = (finding: Finding, key: string) =>
+ [
+ findingMarker(key),
+ `**\`${finding.rule}\`** · ${finding.severity}`,
+ '',
+ oneLine(finding.message),
+ ...(finding.suggestion ? ['', `💡 ${oneLine(finding.suggestion)}`] : []),
+ ].join('\n');
+
+const toAggregatedBody = (file: string, findings: Finding[]) =>
+ [
+ findingMarker(file),
+ `**ALint · ${count(findings.length, 'finding')} in this file**`,
+ '',
+ ...findings.map((finding) => {
+ const head = `- ${severityIcon(finding)} \`${finding.rule}\` · L${finding.line} — ${oneLine(finding.message)}`;
+ return finding.suggestion ? `${head}\n <sub>💡 ${oneLine(finding.suggestion)}</sub>` : head;
+ }),
+ ].join('\n');
+
+/**
+ * One comment per finding, on its own line, so the review reads like an
+ * ESLint run. A file whose findings exceed AGGREGATE_THRESHOLD is commented
+ * once instead: the point of the threshold is to keep the request count of a
+ * runaway run bounded, not to hide lines that are cheap to annotate.
+ */
+export const toFindingComments = (findings: Finding[]): FindingComment[] => {
+ const inline = findings.slice(0, INLINE_LIMIT);
+ const groups = new Map<string, Finding[]>();
+ for (const finding of inline) {
+ const group = groups.get(finding.file);
+ if (group) group.push(finding);
+ else groups.set(finding.file, [finding]);
+ }
+ // Two rules can report the same line, so `file:line` is not always unique.
+ // Count the collisions once, up front: a key that shifts between runs would
+ // re-create a comment and leave the one for a fixed finding behind.
+ const perLine = new Map<string, number>();
+ for (const finding of inline) {
+ const line = `${finding.file}:${finding.line}`;
+ perLine.set(line, (perLine.get(line) ?? 0) + 1);
+ }
+ const keys = new Set<string>();
+ const keyFor = (finding: Finding) => {
+ const line = `${finding.file}:${finding.line}`;
+ const base = (perLine.get(line) ?? 0) > 1 ? `${line}:${finding.rule}` : line;
+ let key = base;
+ // The same rule can still report the same line twice; order the repeats.
+ for (let repeat = 2; keys.has(key); repeat += 1) key = `${base}#${repeat}`;
+ keys.add(key);
+ return key;
+ };
+ const comments: FindingComment[] = [];
+ for (const [file, group] of groups) {
+ if (group.length > AGGREGATE_THRESHOLD) {
+ comments.push({
+ body: toAggregatedBody(file, group),
+ key: file,
+ line: Math.min(...group.map((finding) => finding.line)),
+ path: file,
+ side: 'RIGHT',
+ });
+ continue;
+ }
+ for (const finding of group) {
+ const key = keyFor(finding);
+ comments.push({
+ body: toFindingBody(finding, key),
+ key,
+ line: finding.line,
+ path: file,
+ side: 'RIGHT',
+ });
+ }
+ }
+ return comments;
+};
+
export const toConclusion = (findings: Finding[]) =>
findings.some((f) => f.severity === 'error')
? 'failure'
@@ -176,6 +294,19 @@ const api = async (method: string, url: string, body?: unknown) => {
return response.status === 204 ? undefined : response.json();
};
+/** Every page of a list endpoint: a PR can carry more than one page of comments. */
+const apiPages = async <T>(url: string): Promise<T[]> => {
+ const items: T[] = [];
+ for (let page = 1; ; page += 1) {
+ const batch = (await api(
+ 'GET',
+ `${url}${url.includes('?') ? '&' : '?'}per_page=100&page=${page}`,
+ )) as T[];
+ items.push(...batch);
+ if (batch.length < 100) return items;
+ }
+};
+
const findPullRequest = async (repo: string, branch?: string) => {
if (process.env.PR_NUMBER) return Number(process.env.PR_NUMBER);
if (!branch) return undefined;
@@ -187,14 +318,123 @@ const findPullRequest = async (repo: string, branch?: string) => {
return pulls[0]?.number;
};
-const upsertComment = async (repo: string, pr: number, body: string, hasFindings: boolean) => {
- const comments = (await api('GET', `/repos/${repo}/issues/${pr}/comments?per_page=100`)) as {
- body?: string;
+/** The review comments this script wrote on an earlier run, keyed by marker. */
+const findFindingComments = async (repo: string, pr: number) => {
+ const comments = await apiPages<{
+ body?: string | null;
id: number;
- }[];
- const existing = comments.find((comment) => comment.body?.includes(COMMENT_MARKER));
- if (existing) await api('PATCH', `/repos/${repo}/issues/comments/${existing.id}`, { body });
- else if (hasFindings) await api('POST', `/repos/${repo}/issues/${pr}/comments`, { body });
+ line?: number | null;
+ }>(`/repos/${repo}/pulls/${pr}/comments`);
+ const byKey = new Map<string, { body?: string | null; id: number; line?: number | null }>();
+ for (const comment of comments) {
+ const key = markerKey(comment.body);
+ if (key) byKey.set(key, comment);
+ }
+ return byKey;
+};
+
+/**
+ * Keep the inline comments current across pushes. An identical body on an
+ * unchanged line costs nothing, a changed body is edited in place (the thread
+ * survives), and only a moved line is deleted and re-created. Comments for keys
+ * this run no longer produces — a fixed finding, a file that dropped below the
+ * aggregation threshold — are deleted.
+ *
+ * A line that is not part of the PR diff cannot carry a comment; the summary
+ * table and the check annotation still carry that finding.
+ */
+const syncFindingComments = async (
+ repo: string,
+ pr: number,
+ sha: string,
+ findings: Finding[],
+) => {
+ const existing = await findFindingComments(repo, pr);
+ const wanted = toFindingComments(findings);
+ const target = new Set(wanted.map((comment) => comment.key));
+
+ for (const [key, comment] of existing) {
+ if (target.has(key)) continue;
+ await api('DELETE', `/repos/${repo}/pulls/comments/${comment.id}`);
+ existing.delete(key);
+ }
+
+ for (const comment of wanted) {
+ const previous = existing.get(comment.key);
+ try {
+ if (previous && previous.line === comment.line) {
+ if (previous.body !== comment.body)
+ await api('PATCH', `/repos/${repo}/pulls/comments/${previous.id}`, {
+ body: comment.body,
+ });
+ continue;
+ }
+ if (previous) await api('DELETE', `/repos/${repo}/pulls/comments/${previous.id}`);
+ await api('POST', `/repos/${repo}/pulls/${pr}/comments`, {
+ body: comment.body,
+ commit_id: sha,
+ line: comment.line,
+ path: comment.path,
+ side: comment.side,
+ });
+ } catch (error) {
+ console.warn(`alint: no inline comment on ${comment.key}: ${String(error)}`);
+ }
+ }
+};
+
+/**
+ * The summary used to be an issue comment on the PR. The first run under the
+ * review shape retires it: the review replaces it, and leaving it behind would
+ * keep a fixed finding's table visible — and, on a clean run, be the only ALint
+ * message left on the PR.
+ */
+const retireLegacySummary = async (repo: string, pr: number) => {
+ const comments = await apiPages<{ body?: string | null; id: number }>(
+ `/repos/${repo}/issues/${pr}/comments`,
+ );
+ for (const comment of comments) {
+ if (!comment.body?.includes(REVIEW_MARKER)) continue;
+ try {
+ await api('DELETE', `/repos/${repo}/issues/comments/${comment.id}`);
+ } catch (error) {
+ console.warn(`alint: could not retire the old summary comment: ${String(error)}`);
+ }
+ }
+};
+
+/**
+ * Keep one review on the PR current across pushes. A submitted review cannot be
+ * deleted or replaced, only edited, so its summary body is rewritten in place.
+ */
+const publishReview = async (
+ repo: string,
+ pr: number,
+ sha: string,
+ markdown: string,
+ findings: Finding[],
+) => {
+ const reviews = await apiPages<{ body?: string | null; id: number }>(
+ `/repos/${repo}/pulls/${pr}/reviews`,
+ );
+ const existing = [...reviews].reverse().find((review) => review.body?.includes(REVIEW_MARKER));
+
+ if (existing) {
+ if (existing.body !== markdown)
+ await api('PUT', `/repos/${repo}/pulls/${pr}/reviews/${existing.id}`, { body: markdown });
+ } else {
+ // No review yet means this is the first run after the switch: drop the
+ // summary comment the previous shape left on the PR.
+ await retireLegacySummary(repo, pr);
+ if (findings.length > 0)
+ await api('POST', `/repos/${repo}/pulls/${pr}/reviews`, {
+ body: markdown,
+ commit_id: sha,
+ event: 'COMMENT',
+ });
+ }
+
+ await syncFindingComments(repo, pr, sha, findings);
};
const main = async () => {
@@ -224,12 +464,12 @@ const main = async () => {
status: 'completed',
});
- // The comment is a convenience; never let it fail the report.
+ // The review is a convenience; never let it fail the report.
try {
const pr = await findPullRequest(repo, process.env.HEAD_REF);
- if (pr) await upsertComment(repo, pr, markdown, findings.length > 0);
+ if (pr) await publishReview(repo, pr, sha, markdown, findings);
} catch (error) {
- console.warn(`alint: could not update the PR comment: ${String(error)}`);
+ console.warn(`alint: could not publish the PR review: ${String(error)}`);
}
};