๐คฏ 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
๐ท ci(alint): report findings as an ALint check and one PR summary comment (#19968)
Arvin Xud3f1fb72a232
diff --git a/.github/workflows/test.yml b/.github/workflows/test.ymlindex 2fef53b2af8..c00ac97577d 100644--- a/.github/workflows/test.yml+++ b/.github/workflows/test.yml@@ -248,6 +248,13 @@ jobs:name: ALint & Test Desktop Appruns-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.+ permissions:+ actions: read+ checks: write+ contents: read+ pull-requests: writeenv:ALINT_API_KEY: ${{ secrets.DEEPSEEK_API_KEY }}@@ -295,9 +302,11 @@ jobs:flags: desktop# ---- alint: model-backed lint rules (packages/alint) on this push's diff ----- # Advisory: findings land as inline warning annotations and a job summary,- # never as a failure. Skipped when the provider secret is unavailable (forks).- # Runs here to reuse the root install instead of paying for another job.+ # 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). Runs here to reuse the root+ # install instead of paying for another job.- name: alint ยท expose the diff against the base as dirty changesif: ${{ !cancelled() && env.ALINT_API_KEY != '' }}continue-on-error: true@@ -328,14 +337,20 @@ jobs:- name: alint ยท lint changed filesif: ${{ !cancelled() && env.ALINT_API_KEY != '' }}continue-on-error: true+ env:+ GITHUB_TOKEN: ${{ github.token }}+ HEAD_SHA: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}+ HEAD_REF: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.ref || github.ref_name }}+ PR_NUMBER: ${{ github.event.pull_request.number }}+ RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}run: |bun run alint:setupnode_modules/.bin/alint plugin installnode_modules/.bin/alint --dirty --format json > alint-output.json || status=$?- # 1 = findings at error level (none of ours yet), 2 = alint could not run+ # 1 = findings at error level (reported by the ALint check), 2 = alint could not runif [ "${status:-0}" = "2" ]; then cat alint-output.json; exit 2; fi- if [ ! -s alint-output.json ]; then echo "nothing to lint"; exit 0; fi- bun packages/alint/annotate.ts alint-output.json+ if [ ! -s alint-output.json ]; then echo '{"diagnostics":[]}' > alint-output.json; fi+ bun packages/alint/report.ts alint-output.json- name: alint ยท calibrate rule fixtures (when rules or fixtures changed)if: ${{ !cancelled() && env.ALINT_API_KEY != '' }}diff --git a/alint.config.toml b/alint.config.tomlindex a8c4801e094..5e8b62dfa08 100644--- a/alint.config.toml+++ b/alint.config.toml@@ -5,6 +5,10 @@## Scope rules with group `files`; never with `includeFiles` inside a rule# (it only filters reports, doubles the jobs, and disables the cache).+#+# Severity: `error` is reserved for rules measured at zero false positives on+# real PRs; an error turns the ALint check red. Everything else stays `warn`.+# Fixture groups stay `warn` so a rule PR does not fail on its own bad fixtures.[[config.group]]ignores = [@@ -28,7 +32,7 @@ ignores = [ "**/*.test.ts", "**/__tests__/**", "**/migrations/**" ]lobehub = "./packages/alint/rules"[config.group.rules]-"lobehub/pmap-over-promise-all" = "warn"+"lobehub/pmap-over-promise-all" = "error""lobehub/no-dynamic-import-in-server" = "warn"# Database models layer: cross-table write transactions belong in repositories.@@ -40,7 +44,7 @@ ignores = [ "**/*.test.ts", "**/__tests__/**" ]lobehub = "./packages/alint/rules"[config.group.rules]-"lobehub/no-transactions-in-models" = "warn"+"lobehub/no-transactions-in-models" = "error"# Web client components.[[config.group]]@@ -51,24 +55,9 @@ ignores = [ "**/*.test.tsx" ]lobehub = "./packages/alint/rules"[config.group.rules]-"lobehub/no-effect-fetching" = "warn"+"lobehub/no-effect-fetching" = "error""lobehub/no-mode-flags" = "warn"-# Vitest files, wherever they live: the SPA, every app, and every package.-# Naming only `apps/server` here silently skipped the ~230 tests under-# `apps/cli` and `apps/desktop`, which is where this rule earns its keep.-[[config.group]]-files = [- "src/**/*.test.{ts,tsx}",- "apps/*/src/**/*.test.{ts,tsx}",- "packages/*/src/**/*.test.{ts,tsx}",-]--[config.group.plugins]-lobehub = "./packages/alint/rules"--[config.group.rules]-"lobehub/test-the-exit-not-the-entry" = "warn"# Calibration fixtures: one group per rule so a fixture only meets its own rule.[[config.group]]@@ -105,10 +94,3 @@ files = [ "packages/alint/fixtures/no-transactions-in-models/**" ]lobehub = "./packages/alint/rules"[config.group.rules]"lobehub/no-transactions-in-models" = "warn"--[[config.group]]-files = [ "packages/alint/fixtures/test-the-exit-not-the-entry/**" ]-[config.group.plugins]-lobehub = "./packages/alint/rules"-[config.group.rules]-"lobehub/test-the-exit-not-the-entry" = "warn"diff --git a/packages/alint/README.md b/packages/alint/README.mdindex b6ccf49e2d7..878a8785a39 100644--- a/packages/alint/README.md+++ b/packages/alint/README.md@@ -6,14 +6,15 @@ This is Phase 0: the rule set is a private workspace package (`@lobechat/alint`)## Rules-| Rule | Scope | Source of the rule |-| ----------------------------- | -------------------------------------- | ----------------------------------------------- |-| `pmap-over-promise-all` | `apps/server/src`, `packages/database` | fan-out over a runtime-sized list needs `pMap` |-| `no-dynamic-import-in-server` | same | backend code uses static top-level imports |-| `no-effect-fetching` | `src/**/*.tsx` | `data-fetching-architecture` skill |-| `no-mode-flags` | `src/**/*.tsx` | `compose-atoms` skill |-| `no-transactions-in-models` | `packages/database/src/models` | cross-table write transactions use repositories |-| `test-the-exit-not-the-entry` | Vitest files | tests assert outcomes, not only that a mock ran |+| Rule | Severity | Scope | Source of the rule |+| ----------------------------- | -------- | -------------------------------------- | ----------------------------------------------- |+| `pmap-over-promise-all` | error | `apps/server/src`, `packages/database` | fan-out over a runtime-sized list needs `pMap` |+| `no-transactions-in-models` | error | `packages/database/src/models` | cross-table write transactions use repositories |+| `no-effect-fetching` | error | `src/**/*.tsx` | `data-fetching-architecture` skill |+| `no-dynamic-import-in-server` | warn | `apps/server/src`, `packages/database` | backend code uses static top-level imports |+| `no-mode-flags` | warn | `src/**/*.tsx` | `compose-atoms` skill |++`error` is reserved for rules measured at zero false positives on real PRs; an error turns the ALint check red. A rule starts at `warn` and is promoted only after its findings have been read on real PRs. A rule whose findings are mostly true but not worth acting on per PR does not belong here: `test-the-exit-not-the-entry` was removed after five days because it produced 92% of all findings and drowned out the rest.Scopes are declared as `[[config.group]]` entries in the root `alint.config.toml`. Never scope a rule with `includeFiles` inside `rule.alint.toml`: it only filters reports, so every file still runs (double the jobs), and it marks the rule uncacheable.@@ -31,14 +32,16 @@ bun run alint src/features/Foo # any files or directoriesDefaults are DeepSeek `deepseek-flash` at `https://api.deepseek.com/v1`; override with `ALINT_PROVIDER_ENDPOINT` and `ALINT_MODEL`. Any OpenAI-compatible endpoint with tool calling works. `thinking` is disabled on the model because alint forces a tool call for structured output and DeepSeek V4 rejects that while reasoning is on.-Findings are warnings. Treat them like a reviewer's comment: fix, or explain in the PR why the rule's carve-out applies.+Treat findings like a reviewer's comment: fix them, or explain in the PR why the rule's carve-out applies. Locally, `bun run check --alint` fails on `error` findings like any other lint error.## CI-The `alint ยท` steps at the end of the "ALint & Test Desktop App" job in `.github/workflows/test.yml` run on every push and pull request, on the change's diff only, and never fail the check (they reuse that job's root install instead of paying for a runner of their own):+The `alint ยท` steps at the end of the "ALint & Test Desktop App" job in `.github/workflows/test.yml` run on every push and pull request, on the change's diff only (they reuse that job's root install instead of paying for a runner of their own). The desktop job itself never fails because of alint:- `alint --dirty` lints the working tree against `HEAD` and keeps only findings on changed lines. The steps fetch the merge base (against the PR base, or `canary` on a push) and run `git reset --mixed <merge-base>`, which turns the whole change into dirty changes, so the scope is exactly its diff and nothing older is reported. On a push to `canary` itself the diff is empty and nothing runs.-- Findings become inline warning annotations (`packages/alint/annotate.ts`) plus a table in the job summary.+- `packages/alint/report.ts` publishes the result as a separate **ALint** check run on the head commit: red when any `error` finding exists, neutral with only warnings, green when clean. Findings are attached to it as line annotations. The check is not a required status, so it does not block merging, but a red check reaches whoever watches CI, including agents woken by CI failures.+- The same table goes into one summary comment on the open PR for the branch, rewritten in place on every push. It is created only once there is something to report; when a later push is clean the comment flips to a green verdict instead of disappearing.+- Findings on the calibration fixtures are dropped from the check and the comment; the fixture suite covers them.- The provider key comes from the `DEEPSEEK_API_KEY` repository secret. Fork PRs cannot read it, so the steps are skipped.- When `alint.config.toml` or anything under `packages/alint` changed, the fixture suite runs too, so a rule edit is calibrated before it lands.- `.alintcache` is restored from the last run with the same rule set, keyed by the rule and config files.@@ -51,7 +54,7 @@ The `alint ยท` steps at the end of the "ALint & Test Desktop App" job in `.githu| same, warm cache | 0 | 2 s | 0 || one file changed | 1 | 3 s | 873 |-About 14 input tokens per source line per rule. Two cold runs over the same files differed by one finding; a finding can appear or vanish between runs, which is why fixtures exist and why the severity stays at `warn`.+About 14 input tokens per source line per rule. Two cold runs over the same files differed by one finding; a finding can appear or vanish between runs, which is why fixtures exist and why only rules measured at zero false positives are promoted to `error`.## Adding a rulediff --git a/packages/alint/annotate.test.ts b/packages/alint/annotate.test.tsdeleted file mode 100644index 4344e165789..00000000000--- a/packages/alint/annotate.test.ts+++ /dev/null@@ -1,48 +0,0 @@-import { describe, expect, it } from 'vitest';--import { toAnnotation, toSummary } from './annotate';--const diagnostic = {- filePath: '/repo/apps/server/src/services/x.ts',- loc: { start: { column: 0, line: 12 } },- message: 'Promise.all fans out over rows, 100% of them\nSuggestion: use pMap',- ruleId: 'lobehub/pmap-over-promise-all',- severity: 'warn' as const,-};--describe('toAnnotation', () => {- it('emits a warning command on the finding line with escaped data', () => {- expect(toAnnotation(diagnostic, '/repo')).toBe(- '::warning file=apps/server/src/services/x.ts,line=12,title=lobehub/pmap-over-promise-all::Promise.all fans out over rows, 100%25 of them',- );- });-- it('maps alint errors to error annotations and defaults the line', () => {- expect(toAnnotation({ ...diagnostic, loc: undefined, severity: 'error' }, '/repo')).toMatch(- /^::error file=apps\/server\/src\/services\/x\.ts,line=1,/,- );- });-});--describe('toSummary', () => {- it('renders a header and one table row per finding', () => {- const summary = toSummary(- {- diagnostics: [diagnostic],- execution: { cached: 3, planned: 5 },- usage: { totalTokens: 900 },- },- '/repo',- );- expect(summary).toContain('1 finding ยท 5 files (3 cached) ยท 900 tokens');- expect(summary).toContain(- '| `apps/server/src/services/x.ts:12` | lobehub/pmap-over-promise-all |',- );- });-- it('skips the table when there is nothing to report', () => {- expect(toSummary({ diagnostics: [] }, '/repo')).toBe(- '### alint ยท 0 findings ยท 0 files (0 cached) ยท 0 tokens\n',- );- });-});diff --git a/packages/alint/annotate.ts b/packages/alint/annotate.tsdeleted file mode 100644index 06f1120e3da..00000000000--- a/packages/alint/annotate.ts+++ /dev/null@@ -1,69 +0,0 @@-/**- * Turn `alint --format json` output into GitHub workflow annotations so each- * finding shows up on its line in the PR's Files changed tab, plus a short- * table in the job summary. Findings are advisory: this always exits 0.- *- * bun packages/alint/annotate.ts alint-output.json- */-import { appendFile, readFile } from 'node:fs/promises';-import path from 'node:path';--export interface AlintDiagnostic {- filePath: string;- loc?: { start?: { line?: number } };- message: string;- ruleId: string;- severity: 'error' | 'warn';-}--export interface AlintOutput {- diagnostics: AlintDiagnostic[];- execution?: { cached?: number; completed?: number; planned?: number };- usage?: { totalTokens?: number };-}--/** Workflow-command escaping: `%`, `\r`, `\n` in the message; plus `,` and `:` in properties. */-const escapeData = (value: string) =>- value.replaceAll('%', '%25').replaceAll('\r', '%0D').replaceAll('\n', '%0A');-const escapeProperty = (value: string) =>- escapeData(value).replaceAll(':', '%3A').replaceAll(',', '%2C');--export const toAnnotation = (diagnostic: AlintDiagnostic, rootDir: string): string => {- const file = path.relative(rootDir, diagnostic.filePath);- const line = diagnostic.loc?.start?.line ?? 1;- const level = diagnostic.severity === 'error' ? 'error' : 'warning';- // Keep only the first paragraph: alint appends a "Suggestion:" line.- const message = diagnostic.message.split('\n')[0];- return `::${level} file=${escapeProperty(file)},line=${line},title=${escapeProperty(diagnostic.ruleId)}::${escapeData(message)}`;-};--export const toSummary = (output: AlintOutput, rootDir: string): string => {- const { diagnostics, execution = {}, usage = {} } = output;- const header = `### alint ยท ${diagnostics.length} finding${diagnostics.length === 1 ? '' : 's'} ยท ${execution.planned ?? 0} files (${execution.cached ?? 0} cached) ยท ${usage.totalTokens ?? 0} tokens`;- if (diagnostics.length === 0) return `${header}\n`;- const rows = diagnostics.map(- (diagnostic) =>- `| \`${path.relative(rootDir, diagnostic.filePath)}:${diagnostic.loc?.start?.line ?? 1}\` | ${diagnostic.ruleId} | ${diagnostic.message.split('\n')[0].replaceAll('|', '\\|')} |`,- );- return [header, '', '| Location | Rule | Finding |', '| --- | --- | --- |', ...rows, ''].join(- '\n',- );-};--const main = async () => {- const [inputPath] = process.argv.slice(2);- if (!inputPath) {- console.error('usage: bun packages/alint/annotate.ts <alint-output.json>');- process.exit(2);- }- const rootDir = process.cwd();- const output = JSON.parse(await readFile(inputPath, 'utf8')) as AlintOutput;-- for (const diagnostic of output.diagnostics) console.info(toAnnotation(diagnostic, rootDir));-- const summary = toSummary(output, rootDir);- if (process.env.GITHUB_STEP_SUMMARY) await appendFile(process.env.GITHUB_STEP_SUMMARY, summary);- else console.info(summary);-};--if (import.meta.main) await main();diff --git a/packages/alint/fixtures/test-the-exit-not-the-entry/bad-asserts-only-call.test-case.ts b/packages/alint/fixtures/test-the-exit-not-the-entry/bad-asserts-only-call.test-case.tsdeleted file mode 100644index a3f705af69d..00000000000--- a/packages/alint/fixtures/test-the-exit-not-the-entry/bad-asserts-only-call.test-case.ts+++ /dev/null@@ -1,19 +0,0 @@-// Fixture: the test proves the service was called, never that a topic exists afterwards.-import { describe, expect, it, vi } from 'vitest';--import { topicService } from '@/services/topic';--import { useChatStore } from '../store';--vi.mock('@/services/topic', () => ({- topicService: { createTopic: vi.fn().mockResolvedValue('tpc_1') },-}));--describe('createTopic', () => {- // alint-expect- it('creates a topic from the current session', async () => {- await useChatStore.getState().createTopic({ sessionId: 'ssn_1', title: 'hello' });-- expect(topicService.createTopic).toHaveBeenCalledWith({ sessionId: 'ssn_1', title: 'hello' });- });-});diff --git a/packages/alint/fixtures/test-the-exit-not-the-entry/good-asserts-exit.test-case.ts b/packages/alint/fixtures/test-the-exit-not-the-entry/good-asserts-exit.test-case.tsdeleted file mode 100644index bba7b3b844e..00000000000--- a/packages/alint/fixtures/test-the-exit-not-the-entry/good-asserts-exit.test-case.ts+++ /dev/null@@ -1,18 +0,0 @@-// Fixture: the test asserts the state the caller observes after the action.-import { describe, expect, it, vi } from 'vitest';--import { useChatStore } from '../store';--vi.mock('@/services/topic', () => ({- topicService: { createTopic: vi.fn().mockResolvedValue('tpc_1') },-}));--describe('createTopic', () => {- it('creates a topic and selects it', async () => {- const id = await useChatStore.getState().createTopic({ sessionId: 'ssn_1', title: 'hello' });-- expect(id).toBe('tpc_1');- expect(useChatStore.getState().activeTopicId).toBe('tpc_1');- expect(useChatStore.getState().topicMaps['ssn_1']?.map((t) => t.id)).toContain('tpc_1');- });-});diff --git a/packages/alint/report.test.ts b/packages/alint/report.test.tsnew file mode 100644index 00000000000..e3ac833761a--- /dev/null+++ b/packages/alint/report.test.ts@@ -0,0 +1,116 @@+import { describe, expect, it } from 'vitest';++import {+ COMMENT_MARKER,+ toAnnotations,+ toConclusion,+ toFindings,+ toMarkdown,+ toTitle,+} from './report';++const diagnostic = (overrides: Record<string, unknown> = {}) => ({+ filePath: '/repo/apps/server/src/services/x.ts',+ loc: { start: { column: 0, line: 12 } },+ message: 'Promise.all fans out over rows | unbounded\nSuggestion: use pMap with a cap',+ ruleId: 'lobehub/pmap-over-promise-all',+ severity: 'error' as const,+ ...overrides,+});++describe('toFindings', () => {+ it('splits message and suggestion, strips the plugin prefix, and sorts errors first', () => {+ const findings = toFindings(+ {+ diagnostics: [+ diagnostic({+ filePath: '/repo/src/a.tsx',+ ruleId: 'lobehub/no-mode-flags',+ severity: 'warn',+ }),+ diagnostic(),+ ],+ },+ '/repo',+ );+ expect(findings.map((f) => [f.severity, f.rule, f.file])).toEqual([+ ['error', 'pmap-over-promise-all', 'apps/server/src/services/x.ts'],+ ['warning', 'no-mode-flags', 'src/a.tsx'],+ ]);+ expect(findings[0]).toMatchObject({+ line: 12,+ message: 'Promise.all fans out over rows | unbounded',+ suggestion: 'use pMap with a cap',+ });+ });++ it('prefers the suggestion carried in evidence by declarative rules', () => {+ const [finding] = toFindings(+ {+ diagnostics: [+ diagnostic({ evidence: { suggestion: 'cap it with pMap' }, message: 'fans out' }),+ ],+ },+ '/repo',+ );+ expect(finding).toMatchObject({ message: 'fans out', suggestion: 'cap it with pMap' });+ });++ it('drops calibration fixtures, which fire by design', () => {+ const findings = toFindings(+ { diagnostics: [diagnostic({ filePath: '/repo/packages/alint/fixtures/pmap/bad.ts' })] },+ '/repo',+ );+ expect(findings).toEqual([]);+ });+});++describe('verdict', () => {+ const error = toFindings({ diagnostics: [diagnostic()] }, '/repo');+ const warning = toFindings({ diagnostics: [diagnostic({ severity: 'warn' })] }, '/repo');++ it('fails the check only when an error-level finding exists', () => {+ expect(toConclusion(error)).toBe('failure');+ expect(toConclusion(warning)).toBe('neutral');+ expect(toConclusion([])).toBe('success');+ });++ it('titles the check with the counts', () => {+ expect(toTitle([...error, ...warning, ...warning])).toBe('1 error, 2 warnings');+ expect(toTitle([])).toBe('No findings on the changed lines');+ });++ it('maps severities to check-run annotation levels and caps them at 50', () => {+ expect(toAnnotations(error)[0]).toMatchObject({+ annotation_level: 'failure',+ path: 'apps/server/src/services/x.ts',+ start_line: 12,+ title: 'pmap-over-promise-all',+ });+ expect(toAnnotations(Array.from({ length: 60 }, () => warning[0]))).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'), {+ repo: 'lobehub/lobehub',+ runUrl: 'https://example.com/run',+ sha: 'abcdef1234567',+ });+ expect(markdown.startsWith(COMMENT_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)',+ );+ expect(markdown).toContain('Promise.all fans out over rows \\| unbounded');+ expect(markdown).toContain('๐ก use pMap with a cap');+ expect(markdown).toContain('[run](https://example.com/run)');+ });++ it('renders a clean verdict when nothing was found', () => {+ expect(toMarkdown([], { repo: 'lobehub/lobehub', sha: 'abcdef1234567' })).toContain(+ '### โ ALint ยท No findings on the changed lines',+ );+ });+});diff --git a/packages/alint/report.ts b/packages/alint/report.tsnew file mode 100644index 00000000000..782ce331edc--- /dev/null+++ b/packages/alint/report.ts@@ -0,0 +1,215 @@+/**+ * Publish an `alint --format json` run to GitHub:+ *+ * - 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);+ * - the same table in the job's step summary.+ *+ * Calibration fixtures are dropped: bad fixtures fire by design and are+ * checked by the fixture suite instead.+ *+ * bun packages/alint/report.ts alint-output.json+ *+ * Env: GITHUB_TOKEN, GITHUB_REPOSITORY, HEAD_SHA, HEAD_REF (branch name),+ * PR_NUMBER (optional; looked up from HEAD_REF when absent), RUN_URL.+ */+import { appendFile, readFile } from 'node:fs/promises';+import path from 'node:path';++export interface AlintDiagnostic {+ evidence?: { suggestion?: unknown };+ filePath: string;+ loc?: { start?: { line?: number } };+ message: string;+ ruleId: string;+ severity: 'error' | 'warn';+}++export interface AlintOutput {+ diagnostics: AlintDiagnostic[];+ execution?: { cached?: number; completed?: number; planned?: number };+ usage?: { totalTokens?: number };+}++export interface Finding {+ file: string;+ line: number;+ message: string;+ rule: string;+ severity: 'error' | 'warning';+ suggestion?: string;+}++export const COMMENT_MARKER = '<!-- alint-summary -->';+const FIXTURES_DIR = 'packages/alint/fixtures/';++/** alint JSON โ findings relative to the repo root, fixtures dropped, errors first. */+export const toFindings = (output: AlintOutput, rootDir: string): Finding[] =>+ output.diagnostics+ .map((diagnostic) => {+ const [message, ...rest] = diagnostic.message.split('\n');+ // Declarative rules put the fix in `evidence.suggestion`; hand-written+ // rules append a "Suggestion:" paragraph to the message instead.+ const fromEvidence = diagnostic.evidence?.suggestion;+ const suggestion =+ typeof fromEvidence === 'string' && fromEvidence.trim()+ ? fromEvidence.trim()+ : rest+ .join(' ')+ .replace(/^\s*Suggestion:\s*/i, '')+ .trim();+ return {+ file: path.relative(rootDir, diagnostic.filePath),+ line: diagnostic.loc?.start?.line ?? 1,+ message: message.trim(),+ rule: diagnostic.ruleId.replace(/^lobehub\//, ''),+ severity: diagnostic.severity === 'error' ? ('error' as const) : ('warning' as const),+ suggestion: suggestion || undefined,+ };+ })+ .filter((finding) => !finding.file.startsWith(FIXTURES_DIR))+ .sort(+ (a, b) =>+ Number(b.severity === 'error') - Number(a.severity === 'error') ||+ a.file.localeCompare(b.file) ||+ a.line - b.line,+ );++const count = (n: number, noun: string) => `${n} ${noun}${n === 1 ? '' : 's'}`;++export const toTitle = (findings: Finding[]) => {+ const errors = findings.filter((f) => f.severity === 'error').length;+ const warnings = findings.length - errors;+ if (findings.length === 0) return 'No findings on the changed lines';+ return [errors ? count(errors, 'error') : '', warnings ? count(warnings, 'warning') : '']+ .filter(Boolean)+ .join(', ');+};++const cell = (value: string) => value.replaceAll('|', '\\|').replaceAll('\n', ' ');++/** Markdown body shared by the PR comment and the step summary. */+export const toMarkdown = (+ findings: Finding[],+ { repo, sha, runUrl }: { repo: string; runUrl?: string; sha: string },+): string => {+ const icon = findings.some((f) => f.severity === 'error') ? 'โ' : findings.length ? 'โ ๏ธ' : 'โ ';+ const lines = [`${COMMENT_MARKER}`, `### ${icon} ALint ยท ${toTitle(findings)}`, ''];+ if (findings.length === 0) {+ lines.push(`Checked the changed lines at \`${sha.slice(0, 7)}\`.`);+ } else {+ lines.push('| | Location | Rule | Finding |', '| --- | --- | --- | --- |');+ for (const finding of findings) {+ const link = `https://github.com/${repo}/blob/${sha}/${finding.file}#L${finding.line}`;+ const detail = finding.suggestion+ ? `${cell(finding.message)}<br><sub>๐ก ${cell(finding.suggestion)}</sub>`+ : cell(finding.message);+ lines.push(+ `| ${finding.severity === 'error' ? 'โ' : 'โ ๏ธ'} | [\`${finding.file}:${finding.line}\`](${link}) | \`${finding.rule}\` | ${detail} |`,+ );+ }+ lines.push(+ '',+ 'Errors fail the ALint check. Fix them, or explain in the PR why the rule does not apply. Rules live in `packages/alint/rules`.',+ );+ }+ lines.push('', `<sub>Commit \`${sha.slice(0, 7)}\`${runUrl ? ` ยท [run](${runUrl})` : ''}</sub>`);+ return lines.join('\n');+};++/** Check-run annotations; the API accepts at most 50 per request. */+export const toAnnotations = (findings: Finding[]) =>+ findings.slice(0, 50).map((finding) => ({+ annotation_level: finding.severity === 'error' ? 'failure' : 'warning',+ end_line: finding.line,+ message: finding.suggestion ? `${finding.message}\n\n${finding.suggestion}` : finding.message,+ path: finding.file,+ start_line: finding.line,+ title: finding.rule,+ }));++export const toConclusion = (findings: Finding[]) =>+ findings.some((f) => f.severity === 'error')+ ? 'failure'+ : findings.length+ ? 'neutral'+ : 'success';++/* ------------------------------------------------------------------ GitHub */++const api = async (method: string, url: string, body?: unknown) => {+ const response = await fetch(`https://api.github.com${url}`, {+ body: body === undefined ? undefined : JSON.stringify(body),+ headers: {+ 'Accept': 'application/vnd.github+json',+ 'Authorization': `Bearer ${process.env.GITHUB_TOKEN}`,+ 'X-GitHub-Api-Version': '2022-11-28',+ },+ method,+ });+ if (!response.ok)+ throw new Error(`${method} ${url} โ ${response.status} ${await response.text()}`);+ return response.status === 204 ? undefined : response.json();+};++const findPullRequest = async (repo: string, branch?: string) => {+ if (process.env.PR_NUMBER) return Number(process.env.PR_NUMBER);+ if (!branch) return undefined;+ const owner = repo.split('/')[0];+ const pulls = (await api(+ 'GET',+ `/repos/${repo}/pulls?state=open&head=${owner}:${encodeURIComponent(branch)}`,+ )) as { number: number }[];+ 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;+ 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 });+};++const main = async () => {+ const [inputPath] = process.argv.slice(2);+ if (!inputPath) {+ console.error('usage: bun packages/alint/report.ts <alint-output.json>');+ process.exit(2);+ }+ const findings = toFindings(+ JSON.parse(await readFile(inputPath, 'utf8')) as AlintOutput,+ process.cwd(),+ );+ const repo = process.env.GITHUB_REPOSITORY ?? '';+ const sha = process.env.HEAD_SHA ?? '';+ const markdown = toMarkdown(findings, { repo, runUrl: process.env.RUN_URL, sha });++ if (process.env.GITHUB_STEP_SUMMARY)+ await appendFile(process.env.GITHUB_STEP_SUMMARY, `${markdown}\n`);+ else console.info(markdown);++ if (!process.env.GITHUB_TOKEN || !repo || !sha) return;++ await api('POST', `/repos/${repo}/check-runs`, {+ conclusion: toConclusion(findings),+ head_sha: sha,+ name: 'ALint',+ output: { annotations: toAnnotations(findings), summary: markdown, title: toTitle(findings) },+ status: 'completed',+ });++ // The comment 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);+ } catch (error) {+ console.warn(`alint: could not update the PR comment: ${String(error)}`);+ }+};++if (import.meta.main) await main();diff --git a/packages/alint/rules/test-the-exit-not-the-entry/rule.alint.toml b/packages/alint/rules/test-the-exit-not-the-entry/rule.alint.tomldeleted file mode 100644index 0526550844a..00000000000--- a/packages/alint/rules/test-the-exit-not-the-entry/rule.alint.toml+++ /dev/null@@ -1,17 +0,0 @@-name = "test-the-exit-not-the-entry"-builtInAgent = "basic-structured"-instruction = """-You are reviewing one Vitest test file from LobeHub.--Team rule: a test must assert the exit of the behaviour, not only its entry. "Entry" means proving that some function was invoked (`toHaveBeenCalled`, `toHaveBeenCalledWith`, `toHaveBeenCalledTimes`). "Exit" means the observable outcome the caller cares about: returned value, state after the action, the row that was written, the event that was emitted, the error that surfaced, the UI that changed. Tests that stop at the entry pass when the action can no longer be committed, when the mocked collaborator would have rejected the call, or when the system does not react after the call; those are exactly the regressions LobeHub keeps shipping.--Report each test case (`it(...)` / `test(...)`) whose only assertions are call-shape assertions on mocks or spies, while the code under test has an observable exit the test could have asserted: a return value, a store/state change, a persisted or returned record, a dispatched message, a thrown or rejected error. Use the line of the `it(` / `test(` call. In the message, name what was only asserted as called and what outcome went unasserted. In the suggestion, say which exit to assert and how (for example "assert the store's `topics` map after the action" or "assert the resolved value").--Do not report:-- tests of thin delegation wrappers whose entire contract is forwarding arguments to one collaborator;-- tests explicitly about the call contract (argument shape, call count under retry, ordering) where the outcome is asserted in a sibling test in the same `describe`;-- tests that assert both the call and an outcome;-- tests that assert absence of a call as a guard ("does not call X when Y").--If uncertain, use low confidence rather than forcing a finding.-"""