🤯 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
👷 chore(check): add an opt-in alint rule set for judgement-call lint rules (#19719)
Arvin Xu93ff1694fd86
diff --git a/.agents/scripts/check/alint.ts b/.agents/scripts/check/alint.tsnew file mode 100644index 00000000000..c41db411ab1--- /dev/null+++ b/.agents/scripts/check/alint.ts@@ -0,0 +1,54 @@+import path from 'node:path';++import { run, toolCommand } from './exec';+import { exists, rootDir } from './paths';+import type { LintOutcome, LintProblem } from './types';++/**+ * Opt-in `--alint` selector: model-backed rules from `packages/alint/rules`+ * (see `packages/alint/README.md`). Files outside every config group are+ * skipped by alint itself, so the whole changed set can be passed through.+ */++interface AlintDiagnostic {+ filePath: string;+ loc?: { start?: { line?: number } };+ message: string;+ ruleId: string;+ severity: 'error' | 'warn';+}++/** `alint --format json` → LintProblem[]; null when stdout is not alint JSON. */+export const parseAlintJson = (stdout: string, root: string): LintProblem[] | null => {+ try {+ const { diagnostics } = JSON.parse(stdout) as { diagnostics: AlintDiagnostic[] };+ return diagnostics.map((diagnostic) => ({+ file: path.relative(root, diagnostic.filePath),+ line: diagnostic.loc?.start?.line ?? 0,+ // Keep only the first line: alint appends a "Suggestion:" paragraph.+ message: diagnostic.message.split('\n')[0],+ rule: diagnostic.ruleId,+ severity: diagnostic.severity === 'error' ? 'error' : 'warning',+ }));+ } catch {+ return null;+ }+};++export const runAlint = async (files: string[]): Promise<LintOutcome> => {+ const root = rootDir();+ if (!(await exists(path.join(root, '.alint/config.toml'))))+ return {+ fatal: ['alint: no provider setup — run `bun run alint:setup` (needs ALINT_API_KEY)'],+ problems: [],+ };++ const bin = await toolCommand(root, 'alint');+ const result = await run(bin, ['--format', 'json', ...files], root);+ const problems = parseAlintJson(result.stdout, root);+ if (problems) return { fatal: [], problems };+ return {+ fatal: [`alint: ${result.stderr.trim() || result.stdout.trim() || `exit ${result.code}`}`],+ problems: [],+ };+};diff --git a/.agents/scripts/check/check.test.ts b/.agents/scripts/check/check.test.tsindex 5391b351f51..02ae60b00ae 100644--- a/.agents/scripts/check/check.test.ts+++ b/.agents/scripts/check/check.test.ts@@ -5,6 +5,7 @@ import { fileURLToPath } from 'node:url';import { describe, expect, it } from 'vitest';import { findNewComponentTestAdvisories } from './advisories';+import { parseAlintJson } from './alint';import { diffStat, renderDiffsForStdout } from './autofix';import { lobehubPipelines } from './pipelines';import {@@ -230,3 +231,35 @@ describe('compactVitestOutput', () => {expect(compactVitestOutput(raw)).toBe('Error: config not found');});});++describe('parseAlintJson', () => {+ it('maps alint diagnostics to root-relative lint problems', () => {+ const stdout = JSON.stringify({+ diagnostics: [+ {+ evidence: { confidence: 'high' },+ filePath: '/repo/apps/server/src/services/x.ts',+ loc: { start: { column: 0, line: 12 } },+ message: 'Promise.all fans out over rows\nSuggestion: use pMap',+ ruleId: 'lobehub/pmap-over-promise-all',+ severity: 'warn',+ },+ ],+ execution: {},+ usage: {},+ });+ expect(parseAlintJson(stdout, '/repo')).toEqual([+ {+ file: 'apps/server/src/services/x.ts',+ line: 12,+ message: 'Promise.all fans out over rows',+ rule: 'lobehub/pmap-over-promise-all',+ severity: 'warning',+ },+ ]);+ });++ it('returns null when stdout is not alint JSON', () => {+ expect(parseAlintJson('alint: no .alint config', '/repo')).toBeNull();+ });+});diff --git a/.agents/scripts/check/index.ts b/.agents/scripts/check/index.tsindex 39195535b8b..66ca03297df 100644--- a/.agents/scripts/check/index.ts+++ b/.agents/scripts/check/index.ts@@ -20,6 +20,7 @@* mounts this repo's via `pipelines.ts`.*/import { findNewComponentTestAdvisories } from './advisories';+import { runAlint } from './alint';import { collectAutofixDiffs, snapshot, writeFullDiff } from './autofix';import { collectFromGit, normalizeArgs } from './collect';import { assertCheckRoot } from './delegate';@@ -31,15 +32,16 @@ import { pipelineFor, relatedTestCandidates, resolveMount } from './routing';import type { CheckConfig, FileDiff, LintProblem, RepoMount, TestOutcome } from './types';import { runTestGroups } from './vitest';-const USAGE = `Usage: bun run check [files...] [--lint] [--test] [--type] [--staged]+const USAGE = `Usage: bun run check [files...] [--lint] [--test] [--type] [--alint] [--staged]Selectors compose; no selector = --lint --test.files explicit paths; default = all working-tree changes (staged + unstaged + untracked)--staged collect staged files only (pre-commit scope); ignored with explicit files--lint lint pipelines (with autofix)--test related tests- --type full type-check; alone, file collection is skipped`;+ --type full type-check; alone, file collection is skipped+ --alint model-backed rules (packages/alint); opt-in, needs \`bun run alint:setup\``;-const KNOWN_FLAGS = new Set(['--lint', '--test', '--type', '--staged']);+const KNOWN_FLAGS = new Set(['--lint', '--test', '--type', '--alint', '--staged']);/** Keep only candidates that exist on disk, preserving order. */const filterExisting = async (candidates: string[]): Promise<string[]> => {@@ -69,14 +71,15 @@ export const runCli = async (config: CheckConfig) => {const wantLint = rawArgs.includes('--lint');const wantTest = rawArgs.includes('--test');const runType = rawArgs.includes('--type');- const noSelector = !wantLint && !wantTest && !runType;+ const wantAlint = rawArgs.includes('--alint');+ const noSelector = !wantLint && !wantTest && !runType && !wantAlint;const runLint = wantLint || noSelector;const runTest = wantTest || noSelector;const fileArgs = rawArgs.filter((arg) => !arg.startsWith('--'));let files: string[] = [];- if (runLint || runTest) {+ if (runLint || runTest || wantAlint) {files = await filterExisting(fileArgs.length > 0? normalizeArgs(fileArgs)@@ -123,6 +126,13 @@ export const runCli = async (config: CheckConfig) => {diffs = await collectAutofixDiffs(before);}+ /* ---- Model-backed rules (opt-in) ---- */+ if (wantAlint && files.length > 0) {+ const outcome = await runAlint(files);+ problems.push(...outcome.problems);+ fatal.push(...outcome.fatal);+ }+/* ---- Related tests ---- */let tests: TestOutcome | null = null;let testFiles: string[] = [];@@ -149,7 +159,7 @@ export const runCli = async (config: CheckConfig) => {fatal,fileCount: files.length,fullDiffPath,- lintRan: runLint,+ lintRan: runLint || wantAlint,problems,skipped,testFileCount: testFiles.length,diff --git a/.github/workflows/test.yml b/.github/workflows/test.ymlindex e970a0012c0..627a5e4b442 100644--- a/.github/workflows/test.yml+++ b/.github/workflows/test.yml@@ -253,9 +253,11 @@ jobs:test-desktop:needs: check-duplicate-runif: needs.check-duplicate-run.outputs.should_skip != 'true'- name: Test Desktop App+ name: ALint & Test Desktop Appruns-on: ubuntu-latest+ env:+ ALINT_API_KEY: ${{ secrets.DEEPSEEK_API_KEY }}steps:- name: Checkout@@ -300,6 +302,59 @@ jobs:files: ./apps/desktop/coverage/lcov.infoflags: 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.+ - name: alint · expose the diff against the base as dirty changes+ if: ${{ !cancelled() && env.ALINT_API_KEY != '' }}+ continue-on-error: true+ env:+ GH_TOKEN: ${{ github.token }}+ BASE: ${{ github.event_name == 'pull_request' && github.event.pull_request.base.sha || 'canary' }}+ HEAD_SHA: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}+ run: |+ MERGE_BASE=$(gh api "repos/${GITHUB_REPOSITORY}/compare/${BASE}...${HEAD_SHA}" --jq .merge_base_commit.sha)+ echo "merge base: ${MERGE_BASE}"+ git fetch --no-tags --depth=1 origin "${MERGE_BASE}"+ # alint --dirty lints the working tree against HEAD and keeps only the+ # findings on changed lines; moving HEAD to the merge base makes the+ # whole diff "dirty", so the scope is exactly this change.+ git reset --mixed "${MERGE_BASE}"+ git status --short | head -50++ - name: alint · restore cache+ if: ${{ !cancelled() && env.ALINT_API_KEY != '' }}+ continue-on-error: true+ uses: actions/cache@v4+ with:+ path: .alintcache+ key: alint-${{ hashFiles('alint.config.toml', 'packages/alint/rules/**') }}-${{ github.sha }}+ restore-keys: |+ alint-${{ hashFiles('alint.config.toml', 'packages/alint/rules/**') }}-++ - name: alint · lint changed files+ if: ${{ !cancelled() && env.ALINT_API_KEY != '' }}+ continue-on-error: true+ run: |+ bun run alint:setup+ node_modules/.bin/alint plugin install+ node_modules/.bin/alint --dirty --format json > alint-output.json || status=$?+ # 1 = findings at error level (none of ours yet), 2 = alint could not run+ if [ "${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++ - name: alint · calibrate rule fixtures (when rules or fixtures changed)+ if: ${{ !cancelled() && env.ALINT_API_KEY != '' }}+ continue-on-error: true+ run: |+ if git status --porcelain -- alint.config.toml packages/alint | grep -q .; then+ cd packages/alint && bunx vitest run fixtures.test.ts+ else+ echo "rules and fixtures unchanged; skipping calibration"+ fi+test-server:needs: check-duplicate-runif: needs.check-duplicate-run.outputs.should_skip != 'true'diff --git a/.gitignore b/.gitignoreindex aa9bd3fa2ef..176e4168fb2 100644--- a/.gitignore+++ b/.gitignore@@ -173,3 +173,7 @@ docs/superpowers/# synthesized by plugins/vite/completionSounds.tspublic/sounds/apps/desktop/resources/sounds/++# alint: local provider setup (holds the API key) and result cache+.alint/+.alintcachediff --git a/AGENTS.md b/AGENTS.mdindex de3aaa49d8b..164d43d706c 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -75,6 +75,7 @@ Use `bun run check [changed-files...]`.- Every bug fix needs a regression test that fails before the fix and passes after it. Skip pure style/CSS fixes when the only practical assertion would match stylesheet source strings.- Run once with the selectors needed: no selector means lint + related tests; `--lint`, `--test`, and `--type` compose. Default scope is all staged, unstaged and untracked changes; explicit paths override it.- Lint autofixes files: review the emitted diff. Tests use the nearest owning Vitest config. `--type` checks the full repo. Never run `bun run test`, which runs the full suite.+- `--alint` is opt-in: model-backed rules in `packages/alint/` for judgement calls eslint cannot express. It needs a provider (`bun run alint:setup`); findings are warnings to fix or justify in the PR.- For a manual package test, run from the owning package: `cd packages/database && bunx vitest run --silent='passed-only' '[file-path]'`.### Acceptancediff --git a/alint.config.toml b/alint.config.tomlnew file mode 100644index 00000000000..cb067c6b0b1--- /dev/null+++ b/alint.config.toml@@ -0,0 +1,96 @@+# alint: model-backed rules that eslint cannot express.+# Rules live in packages/alint/rules; each has calibration fixtures under+# packages/alint/fixtures. Set up a provider with `bun run alint:setup`, then+# `bun run check --alint` or `bun run alint --dirty`. See packages/alint/README.md.+#+# Scope rules with group `files`; never with `includeFiles` inside a rule+# (it only filters reports, doubles the jobs, and disables the cache).++[[config.group]]+ignores = [+ "**/node_modules/**",+ "**/dist/**",+ "**/.next/**",+ "**/*.d.ts",+ "packages/sdk/src/generated/**",+ "packages/heterogeneous-agents/src/codex/protocol/generated.ts",+]++[config.group.ignore]+gitignore = true++# Backend business logic.+[[config.group]]+files = [ "apps/server/src/**/*.ts", "packages/database/src/**/*.ts" ]+ignores = [ "**/*.test.ts", "**/__tests__/**", "**/migrations/**" ]++[config.group.plugins]+lobehub = "./packages/alint/rules"++[config.group.rules]+"lobehub/pmap-over-promise-all" = "warn"+"lobehub/no-dynamic-import-in-server" = "warn"++# Web client components.+[[config.group]]+files = [ "src/**/*.tsx" ]+ignores = [ "**/*.test.tsx" ]++[config.group.plugins]+lobehub = "./packages/alint/rules"++[config.group.rules]+"lobehub/no-effect-fetching" = "warn"+"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]]+files = [ "packages/alint/fixtures/pmap-over-promise-all/**" ]+[config.group.plugins]+lobehub = "./packages/alint/rules"+[config.group.rules]+"lobehub/pmap-over-promise-all" = "warn"++[[config.group]]+files = [ "packages/alint/fixtures/no-dynamic-import-in-server/**" ]+[config.group.plugins]+lobehub = "./packages/alint/rules"+[config.group.rules]+"lobehub/no-dynamic-import-in-server" = "warn"++[[config.group]]+files = [ "packages/alint/fixtures/no-effect-fetching/**" ]+[config.group.plugins]+lobehub = "./packages/alint/rules"+[config.group.rules]+"lobehub/no-effect-fetching" = "warn"++[[config.group]]+files = [ "packages/alint/fixtures/no-mode-flags/**" ]+[config.group.plugins]+lobehub = "./packages/alint/rules"+[config.group.rules]+"lobehub/no-mode-flags" = "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/package.json b/package.jsonindex e1f88e28a1c..f8299877af6 100644--- a/package.json+++ b/package.json@@ -42,6 +42,8 @@"apps/workbench"],"scripts": {+ "alint": "alint",+ "alint:setup": "bun packages/alint/setup.ts","build": "bun run build:spa && bun run build:spa:auth && bun run build:spa:workbench && bun run build:spa:share && bun run build:spa:copy && bun run build:next","build:analyze": "cross-env NODE_OPTIONS=--max-old-space-size=81920 next experimental-analyze","build:docker": "pnpm run build:spa && pnpm run build:spa:mobile && pnpm run build:spa:auth && pnpm run build:spa:workbench && pnpm run build:spa:share && cross-env WORKBENCH_REQUIRED=1 SHARE_REQUIRED=1 pnpm run build:spa:copy && cross-env NODE_OPTIONS=--max-old-space-size=8192 DOCKER=true next build",@@ -486,6 +488,7 @@"zustand-utils": "^2.1.1"},"devDependencies": {+ "@alint-js/cli": "0.7.1","@commitlint/cli": "^19.8.1","@edge-runtime/vm": "^5.0.0","@huggingface/tasks": "^0.19.90",diff --git a/packages/alint/README.md b/packages/alint/README.mdnew file mode 100644index 00000000000..2af0decce7b--- /dev/null+++ b/packages/alint/README.md@@ -0,0 +1,61 @@+# LobeHub alint rules++Model-backed lint rules for the judgement calls eslint cannot express. Each rule is a prompt plus a structured-output schema, run per file by [alint](https://github.com/moeru-ai/alint) and cached by file content, so a repeated run over unchanged files costs nothing.++This is Phase 0: the rule set is a private workspace package (`@lobechat/alint`) of declarative `rule.alint.toml` files. Rules that prove generic move to `@lobehub/lint` as a published plugin later; repo-specific rules stay here.++## 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 |+| `test-the-exit-not-the-entry` | Vitest files | tests assert outcomes, not only that a mock ran |++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.++## Setup and run++```bash+export ALINT_API_KEY=... # or DEEPSEEK_API_KEY+bun run alint:setup # writes .alint/config.toml (gitignored)+bun run alint plugin install # registers ./packages/alint/rules (once, and after adding a rule)++bun run check --alint # changed files, alongside the other selectors+bun run alint --dirty # the same scope, alint's own reporter+bun run alint src/features/Foo # any files or directories+```++Defaults 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.++## 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):++- `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.+- 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.++## Cost and behaviour, measured 2026-09-20++| Run | Jobs | Wall | Tokens |+| ------------------------------------- | ---- | ---- | ---------- |+| 80 files (20.8k lines), 2 rules, cold | 80 | 23 s | 290k input |+| 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`.++## Adding a rule++1. Create `rules/<name>/rule.alint.toml` with `name`, `builtInAgent = "basic-structured"`, and an `instruction`. Write the rule as the reviewer would: what to report, which line to anchor on, what the message and suggestion must contain, and an explicit "do not report" list. The carve-outs are where the false positives live.+2. Add a `[[config.group]]` for its scope in `alint.config.toml`, and a fixture group `packages/alint/fixtures/<name>/**`.+3. Add fixtures under `fixtures/<name>/`: at least one `bad-*` file with a standalone `// alint-expect` comment on the line above the one the finding must anchor to, and one `good-*` file per carve-out. Keep them short and realistic.+4. Run `bun run alint plugin install`, then `cd packages/alint && bunx vitest run fixtures.test.ts` with a provider set up. The suite skips itself when there is no setup.+5. Before enabling the rule on a scope, run it over a few dozen real files and read every finding.diff --git a/packages/alint/annotate.test.ts b/packages/alint/annotate.test.tsnew file mode 100644index 00000000000..4344e165789--- /dev/null+++ b/packages/alint/annotate.test.ts@@ -0,0 +1,48 @@+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.tsnew file mode 100644index 00000000000..06f1120e3da--- /dev/null+++ b/packages/alint/annotate.ts@@ -0,0 +1,69 @@+/**+ * 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.ts b/packages/alint/fixtures.test.tsnew file mode 100644index 00000000000..23f2d9fdd8f--- /dev/null+++ b/packages/alint/fixtures.test.ts@@ -0,0 +1,71 @@+import { readdir, readFile } from 'node:fs/promises';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++import { describe, expect, it } from 'vitest';++import { runFixtureLint } from './runFixtures';++/**+ * Calibration: every `bad-*` fixture must produce a finding for its rule on+ * the line below each standalone `// alint-expect` comment (±1 line), every+ * `good-*` fixture must produce none. Runs only when a provider is set up (`bun run alint:setup`);+ * without `.alint/config.toml` the suite is skipped, not failed.+ */+const alintDir = path.dirname(fileURLToPath(import.meta.url));+const rootDir = path.resolve(alintDir, '../..');+const fixturesDir = path.join(alintDir, 'fixtures');++const hasSetup = await readFile(path.join(rootDir, '.alint/config.toml'), 'utf8')+ .then(() => true)+ .catch(() => false);++const ruleDirs = (await readdir(fixturesDir, { withFileTypes: true }))+ .filter((entry) => entry.isDirectory())+ .map((entry) => entry.name)+ .sort();++const fixtureFiles = (+ await Promise.all(+ ruleDirs.map(async (rule) =>+ (await readdir(path.join(fixturesDir, rule)))+ .sort()+ .map((file) => path.join('packages/alint/fixtures', rule, file)),+ ),+ )+).flat();++const expectedLines = async (file: string) =>+ (await readFile(path.join(rootDir, file), 'utf8'))+ .split('\n')+ .flatMap((line, index) => (line.trim() === '// alint-expect' ? [index + 2] : []));++describe.skipIf(!hasSetup)('alint rule fixtures', async () => {+ const diagnostics = hasSetup ? await runFixtureLint(rootDir, fixtureFiles) : [];+ const byFile = (file: string) => diagnostics.filter((d) => d.file === file);++ it.each(fixtureFiles)('%s', async (file) => {+ const rule = `lobehub/${path.basename(path.dirname(file))}`;+ const findings = byFile(file);+ const foreign = findings.filter((d) => d.rule !== rule).map((d) => d.rule);+ expect(foreign, 'a fixture only meets its own rule').toEqual([]);++ if (path.basename(file).startsWith('good-')) {+ expect(findings.map((d) => `${d.line}: ${d.message}`)).toEqual([]);+ return;+ }++ const expected = await expectedLines(file);+ expect(+ expected.length,+ 'bad fixtures put // alint-expect on the line above the offending one',+ ).toBeGreaterThan(0);+ for (const line of expected) {+ const hit = findings.find((d) => Math.abs(d.line - line) <= 1);+ expect(+ hit,+ `expected a ${rule} finding near line ${line}; got ${JSON.stringify(findings)}`,+ ).toBeDefined();+ }+ });+});diff --git a/packages/alint/fixtures/no-dynamic-import-in-server/bad-lazy-service.ts b/packages/alint/fixtures/no-dynamic-import-in-server/bad-lazy-service.tsnew file mode 100644index 00000000000..d6d0dbb7321--- /dev/null+++ b/packages/alint/fixtures/no-dynamic-import-in-server/bad-lazy-service.ts@@ -0,0 +1,6 @@+// Fixture: a service deferring a sibling module with await import().+export const summarizeTopic = async (topicId: string) => {+ // alint-expect+ const { TopicSummaryService } = await import('./TopicSummaryService');+ return new TopicSummaryService().run(topicId);+};diff --git a/packages/alint/fixtures/no-dynamic-import-in-server/good-optional-native.ts b/packages/alint/fixtures/no-dynamic-import-in-server/good-optional-native.tsnew file mode 100644index 00000000000..193b98074cf--- /dev/null+++ b/packages/alint/fixtures/no-dynamic-import-in-server/good-optional-native.ts@@ -0,0 +1,11 @@+// Fixture: a justified dynamic import of an optional native dependency.+export const loadNativeWatcher = async () => {+ try {+ // `@parcel/watcher` is an optional native addon; it is absent on the+ // slim Docker image, so resolve it lazily and fall back to polling.+ const watcher = await import('@parcel/watcher');+ return watcher.subscribe;+ } catch {+ return null;+ }+};diff --git a/packages/alint/fixtures/no-dynamic-import-in-server/good-static-import.ts b/packages/alint/fixtures/no-dynamic-import-in-server/good-static-import.tsnew file mode 100644index 00000000000..fa2d69199ef--- /dev/null+++ b/packages/alint/fixtures/no-dynamic-import-in-server/good-static-import.ts@@ -0,0 +1,4 @@+// Fixture: the same dependency as a static top-level import.+import { TopicSummaryService } from './TopicSummaryService';++export const summarizeTopic = async (topicId: string) => new TopicSummaryService().run(topicId);diff --git a/packages/alint/fixtures/no-effect-fetching/bad-effect-service.tsx b/packages/alint/fixtures/no-effect-fetching/bad-effect-service.tsxnew file mode 100644index 00000000000..fdd8d5a9d94--- /dev/null+++ b/packages/alint/fixtures/no-effect-fetching/bad-effect-service.tsx@@ -0,0 +1,17 @@+// Fixture: remote read inside useEffect copied into useState.+import { memo, useEffect, useState } from 'react';++import { agentService } from '@/services/agent';++const AgentTitle = memo<{ id: string }>(({ id }) => {+ const [title, setTitle] = useState<string>('');++ // alint-expect+ useEffect(() => {+ agentService.getAgentConfig(id).then((config) => setTitle(config.title ?? ''));+ }, [id]);++ return <span>{title}</span>;+});++export default AgentTitle;diff --git a/packages/alint/fixtures/no-effect-fetching/good-electron-ipc.tsx b/packages/alint/fixtures/no-effect-fetching/good-electron-ipc.tsxnew file mode 100644index 00000000000..62dd4dcac61--- /dev/null+++ b/packages/alint/fixtures/no-effect-fetching/good-electron-ipc.tsx@@ -0,0 +1,21 @@+// Fixture: a local Electron IPC read is not a remote fetch.+import { memo, useEffect, useState } from 'react';++import { isDesktop } from '@/const/version';+import { autoUpdateService } from '@/services/electron/autoUpdate';++const UpdateChannel = memo(() => {+ const [channel, setChannel] = useState<'stable' | 'beta'>('stable');++ useEffect(() => {+ if (!isDesktop) return;+ autoUpdateService+ .getUpdateChannel()+ .then(setChannel)+ .catch(() => {});+ }, []);++ return <span>{channel}</span>;+});++export default UpdateChannel;diff --git a/packages/alint/fixtures/no-effect-fetching/good-swr.tsx b/packages/alint/fixtures/no-effect-fetching/good-swr.tsxnew file mode 100644index 00000000000..2ffb00cba20--- /dev/null+++ b/packages/alint/fixtures/no-effect-fetching/good-swr.tsx@@ -0,0 +1,13 @@+// Fixture: the same read through the SWR path.+import { memo } from 'react';++import { useClientDataSWR } from '@/libs/swr';+import { agentService } from '@/services/agent';++const AgentTitle = memo<{ id: string }>(({ id }) => {+ const { data } = useClientDataSWR(['agent-config', id], () => agentService.getAgentConfig(id));++ return <span>{data?.title ?? ''}</span>;+});++export default AgentTitle;diff --git a/packages/alint/fixtures/no-mode-flags/bad-readonly-viewer.tsx b/packages/alint/fixtures/no-mode-flags/bad-readonly-viewer.tsxnew file mode 100644index 00000000000..2c67de519d9--- /dev/null+++ b/packages/alint/fixtures/no-mode-flags/bad-readonly-viewer.tsx@@ -0,0 +1,30 @@+// Fixture: one fat viewer that switches off editing, hotkeys and upload with readOnly.+import { Markdown } from '@lobehub/ui';+import { memo } from 'react';++import { DocumentEditor } from '@/features/DocumentEditor';+import { useDocumentHotkeys } from '@/features/DocumentEditor/hooks/useDocumentHotkeys';+import { useUploadDropZone } from '@/features/Upload/useUploadDropZone';+import { useDocumentSWR } from '@/store/document/hooks';++interface Props {+ id: string;+ readOnly?: boolean;+}++// alint-expect+const DocumentViewer = memo<Props>(({ id, readOnly }) => {+ const { data } = useDocumentSWR(id);+ useDocumentHotkeys({ enabled: !readOnly });+ const dropZone = useUploadDropZone({ disabled: readOnly });++ if (readOnly) return <Markdown>{data?.content ?? ''}</Markdown>;++ return (+ <div {...dropZone.bind}>+ <DocumentEditor content={data?.content ?? ''} id={id} />+ </div>+ );+});++export default DocumentViewer;diff --git a/packages/alint/fixtures/no-mode-flags/good-split-atoms.tsx b/packages/alint/fixtures/no-mode-flags/good-split-atoms.tsxnew file mode 100644index 00000000000..c403213713f--- /dev/null+++ b/packages/alint/fixtures/no-mode-flags/good-split-atoms.tsx@@ -0,0 +1,12 @@+// Fixture: read and edit are separate atoms; each host mounts what it needs.+import { Markdown } from '@lobehub/ui';+import { memo } from 'react';++import { useDocumentContent } from '@/store/document/hooks/useDocumentContent';++export const DocumentReader = memo<{ id: string }>(({ id }) => {+ const { data } = useDocumentContent(id);+ return <Markdown>{data?.content ?? ''}</Markdown>;+});++export default DocumentReader;diff --git a/packages/alint/fixtures/no-mode-flags/good-visual-variant.tsx b/packages/alint/fixtures/no-mode-flags/good-visual-variant.tsxnew file mode 100644index 00000000000..9ce3709064e--- /dev/null+++ b/packages/alint/fixtures/no-mode-flags/good-visual-variant.tsx@@ -0,0 +1,14 @@+// Fixture: a size variant only changes styling.+import { Avatar } from '@lobehub/ui/base-ui';+import { memo } from 'react';++interface Props {+ avatar: string;+ size?: 'small' | 'large';+}++const AgentAvatar = memo<Props>(({ avatar, size = 'small' }) => (+ <Avatar avatar={avatar} size={size === 'large' ? 64 : 28} />+));++export default AgentAvatar;diff --git a/packages/alint/fixtures/pmap-over-promise-all/bad-map-over-rows.ts b/packages/alint/fixtures/pmap-over-promise-all/bad-map-over-rows.tsnew file mode 100644index 00000000000..91536705f62--- /dev/null+++ b/packages/alint/fixtures/pmap-over-promise-all/bad-map-over-rows.ts@@ -0,0 +1,10 @@+// Fixture: fan-out over a query result with Promise.all.+import { enrichTopic } from './enrich';+import { topicModel } from './model';++export const listEnrichedTopics = async (userId: string) => {+ const rows = await topicModel.findByUser(userId);++ // alint-expect+ return Promise.all(rows.map(async (row) => enrichTopic(row)));+};diff --git a/packages/alint/fixtures/pmap-over-promise-all/good-fixed-tuple.ts b/packages/alint/fixtures/pmap-over-promise-all/good-fixed-tuple.tsnew file mode 100644index 00000000000..ba813e62780--- /dev/null+++ b/packages/alint/fixtures/pmap-over-promise-all/good-fixed-tuple.ts@@ -0,0 +1,19 @@+// Fixture: fixed tuples stay on Promise.all, including inside a loop.+import { agentModel, topicModel } from './model';++export const loadPair = async (agentId: string, topicId: string) => {+ const [agent, topic] = await Promise.all([+ agentModel.findById(agentId),+ topicModel.findById(topicId),+ ]);+ return { agent, topic };+};++export const loadEach = async (ids: string[]) => {+ const out = [];+ for (const id of ids) {+ const [meta, stats] = await Promise.all([agentModel.findMeta(id), agentModel.findStats(id)]);+ out.push({ meta, stats });+ }+ return out;+};diff --git a/packages/alint/fixtures/pmap-over-promise-all/good-pmap.ts b/packages/alint/fixtures/pmap-over-promise-all/good-pmap.tsnew file mode 100644index 00000000000..5ade2d7a31c--- /dev/null+++ b/packages/alint/fixtures/pmap-over-promise-all/good-pmap.ts@@ -0,0 +1,10 @@+// Fixture: runtime-sized fan-out already capped with pMap.+import pMap from 'p-map';++import { enrichTopic } from './enrich';+import { topicModel } from './model';++export const listEnrichedTopics = async (userId: string) => {+ const rows = await topicModel.findByUser(userId);+ return pMap(rows, (row) => enrichTopic(row), { concurrency: 8 });+};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.tsnew file mode 100644index 00000000000..a3f705af69d--- /dev/null+++ b/packages/alint/fixtures/test-the-exit-not-the-entry/bad-asserts-only-call.test-case.ts@@ -0,0 +1,19 @@+// 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.tsnew file mode 100644index 00000000000..bba7b3b844e--- /dev/null+++ b/packages/alint/fixtures/test-the-exit-not-the-entry/good-asserts-exit.test-case.ts@@ -0,0 +1,18 @@+// 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/package.json b/packages/alint/package.jsonnew file mode 100644index 00000000000..b40b8eb4f36--- /dev/null+++ b/packages/alint/package.json@@ -0,0 +1,11 @@+{+ "name": "@lobechat/alint",+ "version": "1.0.0",+ "private": true,+ "description": "LobeHub alint rule set: model-backed lint rules, calibration fixtures, and CI annotation helpers",+ "type": "module",+ "scripts": {+ "setup": "bun setup.ts",+ "test": "vitest run"+ }+}diff --git a/packages/alint/rules/no-dynamic-import-in-server/rule.alint.toml b/packages/alint/rules/no-dynamic-import-in-server/rule.alint.tomlnew file mode 100644index 00000000000..9a5da0e46ab--- /dev/null+++ b/packages/alint/rules/no-dynamic-import-in-server/rule.alint.toml@@ -0,0 +1,16 @@+name = "no-dynamic-import-in-server"+builtInAgent = "basic-structured"+instruction = """+You are reviewing one TypeScript file from the LobeHub backend (server runtime, routers, services, database package, agent runtime).++Team rule: backend code uses static top-level `import` declarations. `await import('...')` / `import('...')` expressions in backend code hide the dependency graph from the bundler and the circular-import checker, defer module errors to request time, and make cold paths slow on the first request. Splitting bundles is a client concern, not a server one.++Report each dynamic `import(...)` expression in this file. Use the line of the `import(` call. In the message, name the imported module. In the suggestion, say to hoist it to a static top-level import, and if the author's likely motive is a circular dependency, say to break the cycle (move the shared piece into its own module) instead of deferring the import.++Do not report:+- a dynamic import that a nearby comment justifies as loading an optional or platform-specific dependency that may be absent at runtime (for example a native addon, a dev-only tool, or a package guarded by a feature flag);+- `import type` or `typeof import('...')` used purely in type positions;+- test files, scripts, and Next.js route shells (they are not backend business logic).++If uncertain, use low confidence rather than forcing a finding.+"""diff --git a/packages/alint/rules/no-effect-fetching/rule.alint.toml b/packages/alint/rules/no-effect-fetching/rule.alint.tomlnew file mode 100644index 00000000000..2aebc6af926--- /dev/null+++ b/packages/alint/rules/no-effect-fetching/rule.alint.toml@@ -0,0 +1,18 @@+name = "no-effect-fetching"+builtInAgent = "basic-structured"+instruction = """+You are reviewing one React component or hook file from the LobeHub web client.++Team rule (data-fetching-architecture): remote data is read through SWR hooks (`useSWR`, `useClientDataSWR`, `useOnlyFetchOnceSWR`, or the `useFetch*` / `useSWR*` hooks that zustand stores expose), never by calling a service inside `useEffect` and copying the result into `useState`. The SWR path gives request dedupe, cache, revalidation, and shared loading/error state; an effect-based fetch loses all of that, races on unmount, and refetches on every mount.++Report each `useEffect` (or `useLayoutEffect`) whose body, directly or through an async helper defined in the same file, performs a remote read and stores the result in component state: a `*Service.*` call that hits the server, a tRPC client call (`lambdaClient`, `edgeClient`, `trpc.*`), or `fetch`. Use the line of the `useEffect` call. Name the call in the message. In the suggestion, sketch the SWR hook shape (key, fetcher, and which local state it replaces).++Do not report effects that:+- only subscribe or unsubscribe to events, timers, observers, or websocket messages;+- write (mutations, analytics, telemetry) in response to a user action or lifecycle;+- sync props or URL state into local state;+- read from a zustand store, `localStorage`, or a synchronous source;+- talk to a local-only bridge rather than the server: Electron IPC (`electronSystemService`, `autoUpdateService`, `desktop*Service`, `window.electron`, anything backed by `ipcRenderer`), the local file system, or the device gateway.++If uncertain, use low confidence rather than forcing a finding.+"""diff --git a/packages/alint/rules/no-mode-flags/rule.alint.toml b/packages/alint/rules/no-mode-flags/rule.alint.tomlnew file mode 100644index 00000000000..e1cdfc99316--- /dev/null+++ b/packages/alint/rules/no-mode-flags/rule.alint.toml@@ -0,0 +1,17 @@+name = "no-mode-flags"+builtInAgent = "basic-structured"+instruction = """+You are reviewing one React component file from the LobeHub web client.++Team rule (compose-atoms): when one feature must render in several hosts (the full page, a portal or drawer, a public share page, a micro-app), split it on mountable capabilities and let each host assemble only the atoms it needs. Do not hide unused work behind a mode flag. A prop such as `readOnly`, `mode`, `variant`, `isShare`, `isPortal`, `isPreview`, `compact` that disables editing, fetching, toolbars, hotkeys, or stores inside one fat component still imports and mounts all of that work in every host: the share page ships the editor, the portal registers hotkeys it never uses, and each new host adds another branch.++Report a component when a boolean or enum prop is used to switch off whole capabilities (a data-fetching hook, a store subscription, an editor, a toolbar, a hotkey registration, an upload path) that are still imported and mounted by the same component. Use the line of the component declaration. In the message, name the prop and the capabilities it gates. In the suggestion, name the atoms to extract and which host would mount which.++Do not report:+- visual variants (size, tone, density, layout direction) that only change styling or copy;+- a `readOnly` / `disabled` prop forwarded to a form control, an input, or a small leaf component;+- a flag that gates one small conditional render without an owning import or hook behind it;+- feature flags or permission checks (`canEdit`, `isOwner`) that decide access, not host composition.++If uncertain, use low confidence rather than forcing a finding.+"""diff --git a/packages/alint/rules/pmap-over-promise-all/rule.alint.toml b/packages/alint/rules/pmap-over-promise-all/rule.alint.tomlnew file mode 100644index 00000000000..84634d406d8--- /dev/null+++ b/packages/alint/rules/pmap-over-promise-all/rule.alint.toml@@ -0,0 +1,16 @@+name = "pmap-over-promise-all"+builtInAgent = "basic-structured"+instruction = """+You are reviewing one TypeScript file from the LobeHub backend (server services, routers, database models, agent runtime).++Team rule: a fan-out over a runtime-sized list must go through `pMap` from `p-map` with an explicit `concurrency` cap. "Runtime-sized" means the length is only known when the code runs: rows returned by a query, ids taken from a request, entries of a directory, items of a batch, a `k` read from configuration. `Promise.all` / `Promise.allSettled` stay acceptable for a literal tuple of two or three independent calls whose count is fixed at authoring time.++Report each `Promise.all` or `Promise.allSettled` whose input is built by mapping over a runtime-sized collection (`list.map(async ...)`, `Array.from(..., async ...)`, an array pushed in a loop, etc.). Use the line of the `Promise.all` call. In the message, name the collection, say where its size comes from, and mention what each iteration does (a DB read, a network call, a workflow trigger). In the suggestion, give the `pMap(list, fn, { concurrency: N })` shape.++Do not report:+- `Promise.all` over a literal tuple of fixed calls, even when that tuple sits inside a `for` loop: the loop is sequential and the tuple is fixed.+- Collections that are provably bounded by a small constant in the same file (a fixed enum, a hard-coded list).+- Code that already goes through `pMap`, a queue, or another concurrency limiter.++If uncertain, use low confidence rather than forcing a finding.+"""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.tomlnew file mode 100644index 00000000000..0526550844a--- /dev/null+++ b/packages/alint/rules/test-the-exit-not-the-entry/rule.alint.toml@@ -0,0 +1,17 @@+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.+"""diff --git a/packages/alint/runFixtures.ts b/packages/alint/runFixtures.tsnew file mode 100644index 00000000000..2574f2c6de4--- /dev/null+++ b/packages/alint/runFixtures.ts@@ -0,0 +1,49 @@+import { spawn } from 'node:child_process';+import path from 'node:path';++export interface FixtureDiagnostic {+ file: string;+ line: number;+ message: string;+ rule: string;+}++interface AlintOutput {+ diagnostics: {+ filePath: string;+ loc?: { start?: { line?: number } };+ message: string;+ ruleId: string;+ }[];+}++/** Run the repo's alint once over the fixture files and return root-relative diagnostics. */+export const runFixtureLint = (rootDir: string, files: string[]): Promise<FixtureDiagnostic[]> =>+ new Promise((resolve, reject) => {+ const bin = path.join(rootDir, 'node_modules/.bin/alint');+ const child = spawn(bin, ['--format', 'json', ...files], {+ cwd: rootDir,+ env: { ...process.env, NO_COLOR: '1' },+ stdio: ['ignore', 'pipe', 'pipe'],+ });+ let stdout = '';+ let stderr = '';+ child.stdout.on('data', (chunk) => (stdout += chunk));+ child.stderr.on('data', (chunk) => (stderr += chunk));+ child.on('error', reject);+ child.on('close', (code) => {+ if (code === 2 || !stdout.trim()) {+ reject(new Error(`alint exited ${code}: ${stderr.trim()}`));+ return;+ }+ const output = JSON.parse(stdout) as AlintOutput;+ resolve(+ output.diagnostics.map((diagnostic) => ({+ file: path.relative(rootDir, diagnostic.filePath),+ line: diagnostic.loc?.start?.line ?? 0,+ message: diagnostic.message.split('\n')[0],+ rule: diagnostic.ruleId,+ })),+ );+ });+ });diff --git a/packages/alint/setup.ts b/packages/alint/setup.tsnew file mode 100644index 00000000000..6326f7d5145--- /dev/null+++ b/packages/alint/setup.ts@@ -0,0 +1,55 @@+/**+ * Write the local alint provider setup (`.alint/config.toml`, gitignored)+ * from environment variables so the API key never lands in the repo.+ *+ * ALINT_API_KEY (or DEEPSEEK_API_KEY) required+ * ALINT_PROVIDER_ENDPOINT default https://api.deepseek.com/v1+ * ALINT_MODEL default deepseek-flash+ *+ * `thinking` is disabled on the model: alint forces a tool call for+ * structured output and DeepSeek V4 rejects that while reasoning is on.+ */+import { mkdir, writeFile } from 'node:fs/promises';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++const rootDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');++const apiKey = process.env.ALINT_API_KEY ?? process.env.DEEPSEEK_API_KEY;+const endpoint = process.env.ALINT_PROVIDER_ENDPOINT ?? 'https://api.deepseek.com/v1';+const model = process.env.ALINT_MODEL ?? 'deepseek-flash';++if (!apiKey) {+ console.error('✗ set ALINT_API_KEY (or DEEPSEEK_API_KEY) before running alint:setup');+ process.exit(2);+}++const providerId = new URL(endpoint).hostname;++const toml = `# Generated by \`bun run alint:setup\`; gitignored because it holds the key.+version = 1++[[providers]]+id = "${providerId}"+type = "openai-compatible"+endpoint = "${endpoint}"++[providers.headers]+Authorization = "Bearer ${apiKey}"++[[providers.models]]+id = "${model}"+name = "${model}"+size = "small"+aliases = [ "default" ]+capabilities = [ "tool-call" ]++[providers.models.default_params]+thinking = { type = "disabled" }+`;++const target = path.join(rootDir, '.alint/config.toml');+await mkdir(path.dirname(target), { recursive: true });+await writeFile(target, toml, { mode: 0o600 });+console.info(`✓ wrote ${path.relative(rootDir, target)} (${providerId} / ${model})`);+console.info(' next: bun run alint plugin install && bun run check --alint');diff --git a/packages/alint/vitest.config.mts b/packages/alint/vitest.config.mtsnew file mode 100644index 00000000000..fd7462c8f4d--- /dev/null+++ b/packages/alint/vitest.config.mts@@ -0,0 +1,14 @@+import { defineConfig } from 'vitest/config';++/**+ * Package config: plain Node environment, and fixtures are excluded because+ * they are inputs for alint, not tests, even when they carry a `.test-case.ts`+ * suffix for the rule they calibrate.+ */+export default defineConfig({+ test: {+ environment: 'node',+ exclude: ['**/node_modules/**', 'fixtures/**'],+ testTimeout: 180_000,+ },+});diff --git a/tsconfig.json b/tsconfig.jsonindex 981aec0b9c4..34f4836e74b 100644--- a/tsconfig.json+++ b/tsconfig.json@@ -47,7 +47,8 @@"temp",".temp","e2e/**",- "knip.ts"+ "knip.ts",+ "packages/alint/fixtures/**"],"include": ["src/**/*.d.ts",