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.

πŸ”§ chore(alint): recalibrate the rule set against all of canary, move path checks to ESLint (#20158)

Arvin Xucc212307c1dc
diff --git a/.agents/scripts/check/alint.ts b/.agents/scripts/check/alint.ts
index c41db411ab1..7d3b432ed82 100644
--- a/.agents/scripts/check/alint.ts
+++ b/.agents/scripts/check/alint.ts
@@ -8,6 +8,10 @@ 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.
+ *
+ * With no explicit paths the scope matches CI: `alint --dirty` keeps only
+ * findings on changed lines, so touching a file does not surface every older
+ * violation in it. Explicit paths lint those files whole.
*/
interface AlintDiagnostic {
@@ -35,7 +39,27 @@ export const parseAlintJson = (stdout: string, root: string): LintProblem[] | nu
}
};
-export const runAlint = async (files: string[]): Promise<LintOutcome> => {
+interface AlintScope {
+ /** Default git scope: lint changed lines only, like CI. False for explicit paths. */
+ changedLinesOnly: boolean;
+}
+
+/** CLI arguments that select what alint lints. */
+export const alintScopeArgs = (files: string[], { changedLinesOnly }: AlintScope): string[] =>
+ changedLinesOnly ? ['--dirty'] : files;
+
+/** `--dirty` also covers unstaged files; keep only the selected set (e.g. `--staged`). */
+export const keepSelectedFiles = (
+ problems: LintProblem[],
+ files: string[],
+ { changedLinesOnly }: AlintScope,
+): LintProblem[] => {
+ if (!changedLinesOnly) return problems;
+ const selected = new Set(files);
+ return problems.filter((problem) => selected.has(problem.file));
+};
+
+export const runAlint = async (files: string[], scope: AlintScope): Promise<LintOutcome> => {
const root = rootDir();
if (!(await exists(path.join(root, '.alint/config.toml'))))
return {
@@ -44,9 +68,9 @@ export const runAlint = async (files: string[]): Promise<LintOutcome> => {
};
const bin = await toolCommand(root, 'alint');
- const result = await run(bin, ['--format', 'json', ...files], root);
+ const result = await run(bin, ['--format', 'json', ...alintScopeArgs(files, scope)], root);
const problems = parseAlintJson(result.stdout, root);
- if (problems) return { fatal: [], problems };
+ if (problems) return { fatal: [], problems: keepSelectedFiles(problems, files, scope) };
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.ts
index 02ae60b00ae..64e0da93602 100644
--- a/.agents/scripts/check/check.test.ts
+++ b/.agents/scripts/check/check.test.ts
@@ -5,7 +5,7 @@ import { fileURLToPath } from 'node:url';
import { describe, expect, it } from 'vitest';
import { findNewComponentTestAdvisories } from './advisories';
-import { parseAlintJson } from './alint';
+import { alintScopeArgs, keepSelectedFiles, parseAlintJson } from './alint';
import { diffStat, renderDiffsForStdout } from './autofix';
import { lobehubPipelines } from './pipelines';
import {
@@ -263,3 +263,30 @@ describe('parseAlintJson', () => {
expect(parseAlintJson('alint: no .alint config', '/repo')).toBeNull();
});
});
+
+describe('alint scope', () => {
+ const files = ['packages/database/src/models/goalGraph.ts'];
+ const problem = (file: string) => ({
+ file,
+ line: 383,
+ message: 'transaction writes two tables',
+ rule: 'lobehub/no-transactions-in-models',
+ severity: 'error' as const,
+ });
+
+ it('lints changed lines only for the default git scope, like CI', () => {
+ expect(alintScopeArgs(files, { changedLinesOnly: true })).toEqual(['--dirty']);
+ });
+
+ it('lints explicit paths whole', () => {
+ expect(alintScopeArgs(files, { changedLinesOnly: false })).toEqual(files);
+ });
+
+ it('drops dirty findings outside the selected files (e.g. --staged)', () => {
+ const problems = [problem(files[0]), problem('src/unstaged.tsx')];
+ expect(keepSelectedFiles(problems, files, { changedLinesOnly: true })).toEqual([
+ problem(files[0]),
+ ]);
+ expect(keepSelectedFiles(problems, files, { changedLinesOnly: false })).toEqual(problems);
+ });
+});
diff --git a/.agents/scripts/check/index.ts b/.agents/scripts/check/index.ts
index 66ca03297df..48361c53b7a 100644
--- a/.agents/scripts/check/index.ts
+++ b/.agents/scripts/check/index.ts
@@ -128,7 +128,7 @@ export const runCli = async (config: CheckConfig) => {
/* ---- Model-backed rules (opt-in) ---- */
if (wantAlint && files.length > 0) {
- const outcome = await runAlint(files);
+ const outcome = await runAlint(files, { changedLinesOnly: fileArgs.length === 0 });
problems.push(...outcome.problems);
fatal.push(...outcome.fatal);
}
diff --git a/alint.config.toml b/alint.config.toml
index c823be0428d..8c31d9ab8fa 100644
--- a/alint.config.toml
+++ b/alint.config.toml
@@ -61,8 +61,10 @@ lobehub = "./packages/alint/rules"
"lobehub/no-mode-flags" = "warn"
-# Browser code, everywhere: nothing Node-only may be imported where the SPA
-# (or the Electron renderer) runs it. Global rule, in packages/alint/rules.
+# Browser code, everywhere: no third-party package that needs Node may be
+# imported where the SPA (or the Electron renderer) runs it. Node built-ins and
+# server / database aliases are enforced exactly by ESLint (the browser runtime
+# block in eslint.config.mjs); this rule only judges npm packages.
# `src/app` and `src/libs` are left out on purpose: they mix Next.js shells and
# server helpers (instrumentation, OIDC, MCP) with web code.
[[config.group]]
diff --git a/apps/server/src/services/toolExecution/archiveToolResult.ts b/apps/server/src/services/toolExecution/archiveToolResult.ts
index 769ac8fde78..4e556501fdc 100644
--- a/apps/server/src/services/toolExecution/archiveToolResult.ts
+++ b/apps/server/src/services/toolExecution/archiveToolResult.ts
@@ -7,16 +7,16 @@ import {
formatTextWindowNotice,
type TextWindow,
} from '@lobechat/prompts/textWindow';
+import {
+ ARCHIVE_BYPASS_IDENTIFIERS,
+ DEFAULT_TOOL_RESULT_MAX_LENGTH,
+ sliceToolResult,
+} from '@lobechat/prompts/toolResult';
import debug from 'debug';
import { sql } from 'drizzle-orm';
import { TopicDocumentModel } from '@/database/models/topicDocument';
import { AgentDocumentVfsService } from '@/server/services/agentDocumentVfs';
-import {
- ARCHIVE_BYPASS_IDENTIFIERS,
- DEFAULT_TOOL_RESULT_MAX_LENGTH,
- sliceToolResult,
-} from '@/server/utils/truncateToolResult';
import { TOOL_RESULTS_DIR_NAME } from './constants';
diff --git a/apps/server/src/services/toolExecution/index.ts b/apps/server/src/services/toolExecution/index.ts
index 81fd90f603e..891870d117c 100644
--- a/apps/server/src/services/toolExecution/index.ts
+++ b/apps/server/src/services/toolExecution/index.ts
@@ -1,3 +1,4 @@
+import { DEFAULT_TOOL_RESULT_MAX_LENGTH, truncateToolResult } from '@lobechat/prompts/toolResult';
import { type ChatToolPayload } from '@lobechat/types';
import { isLocalOrPrivateUrl, safeParseJSON } from '@lobechat/utils';
import debug from 'debug';
@@ -18,10 +19,6 @@ import { resolveDeviceClientKind } from '@/server/services/deviceGateway/deviceC
import { resolveDeviceDispatchAuthorizationFailure } from '@/server/services/deviceGateway/dispatchAuthorization';
import { getScopedOnlineDevices } from '@/server/services/deviceGateway/scopedDevices';
import { contentBlocksToString } from '@/server/services/mcp/contentProcessor';
-import {
- DEFAULT_TOOL_RESULT_MAX_LENGTH,
- truncateToolResult,
-} from '@/server/utils/truncateToolResult';
import { DiscoverService } from '../discover';
import { type MCPService } from '../mcp';
diff --git a/eslint.config.mjs b/eslint.config.mjs
index 6b821ff515a..8e59f90c148 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -104,18 +104,74 @@ const runtimeRestrictedImportPatterns = [
},
];
-const createRestrictedImportRule = ({ paths = [], patterns } = {}) => [
+// Browser runtime boundary for the SPA and the Electron renderer: server code,
+// database access and Node built-ins never run there. Vite stubs a Node
+// built-in with a module that throws on first access, and a server import
+// drags its whole graph (database drivers, env) into the bundle. Type imports
+// are erased and stay allowed. Server-side trees under src/ (Next.js shells,
+// src/libs, instrumentation, proxy) opt out with `serverSide: true`.
+// Whether a third-party package needs Node is a judgement call; the alint
+// rule `lobehub/no-node-in-browser` covers that part.
+const NODE_BUILTINS = [
+ 'child_process',
+ 'cluster',
+ 'dgram',
+ 'dns',
+ 'fs',
+ 'fs/promises',
+ 'http',
+ 'http2',
+ 'https',
+ 'module',
+ 'net',
+ 'os',
+ 'path',
+ 'readline',
+ 'stream',
+ 'tls',
+ 'v8',
+ 'vm',
+ 'worker_threads',
+ 'zlib',
+];
+const browserRuntimeRestrictedImportPaths = NODE_BUILTINS.flatMap((name) => [
+ name,
+ `node:${name}`,
+]).map((name) => ({
+ allowTypeImports: true,
+ message:
+ 'Node built-ins do not exist in the browser. Move the work behind a server endpoint or an Electron IPC call; type imports are fine.',
+ name,
+}));
+const browserRuntimeRestrictedImportPatterns = [
+ {
+ allowTypeImports: true,
+ message:
+ 'Server code does not run in the browser. Call it through a TRPC service, or move a pure helper into a shared package; type imports are fine.',
+ regex: String.raw`^@/(server|app/\(backend\))/`,
+ },
+ {
+ allowTypeImports: true,
+ message:
+ 'Database models, repositories and clients are server-only. Read through a TRPC service; schemas and type imports are fine.',
+ regex: '^(@/database|@lobechat/database)/(models|repositories|server|core)(/|$)',
+ },
+];
+
+const createRestrictedImportRule = ({ paths = [], patterns, serverSide = false } = {}) => [
'error',
{
...baseRestrictedImportOptions,
paths: [
...(baseRestrictedImportOptions.paths ?? []),
...performanceRestrictedImportPaths,
+ ...(serverSide ? [] : browserRuntimeRestrictedImportPaths),
...paths,
],
patterns: [
...(baseRestrictedImportOptions.patterns ?? []),
...runtimeRestrictedImportPatterns,
+ ...(serverSide ? [] : browserRuntimeRestrictedImportPatterns),
...(patterns ?? []),
],
},
@@ -230,6 +286,20 @@ export default eslint(
'no-restricted-imports': createRestrictedImportRule(),
},
},
+ {
+ // Server-side trees under src/: Next.js shells and route handlers, server
+ // helpers, instrumentation and the proxy may import server code.
+ files: [
+ 'src/app/**/*.{ts,tsx}',
+ 'src/libs/**/*.{ts,tsx}',
+ 'src/scripts/**/*.{ts,tsx}',
+ 'src/*.{ts,tsx}',
+ 'src/**/*.server.{ts,tsx}',
+ ],
+ rules: {
+ 'no-restricted-imports': createRestrictedImportRule({ serverSide: true }),
+ },
+ },
{
// Bundle-size restrictions target shipped code; tests may reach the barrels.
files: ['src/**/*.test.{ts,tsx}'],
diff --git a/packages/alint/README.md b/packages/alint/README.md
index 03c4eb6f5dd..7bac22040f7 100644
--- a/packages/alint/README.md
+++ b/packages/alint/README.md
@@ -6,14 +6,14 @@ This is Phase 0: the rule set is a private workspace package (`@lobechat/alint`)
## Rules
-| 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 |
-| `no-node-in-browser` | error | browser code in `src/` (not `app/`, `libs/`), package `*.tsx` | nothing Node-only where the SPA runs it |
+| 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-aggregate 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 |
+| `no-node-in-browser` | error | browser code in `src/` (not `app/`, `libs/`), package `*.tsx` | no Node-only npm package where the SPA runs it (paths: ESLint) |
Package-level rules, kept next to the package they describe:
@@ -26,6 +26,8 @@ Package-level rules, kept next to the package they describe:
`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.
+**What belongs here, and what belongs in ESLint.** A check that an AST or a path list decides β€” an import path, a banned call, a naming pattern β€” goes into ESLint, where it is exact, free and runs in the editor. alint takes only what needs judgement: whether a list is runtime-sized, whether a table is another aggregate, whether an effect reads the server. Leaving a deterministic check to a model buys false positives: `no-node-in-browser` once flagged 34 imports on canary and 33 were type-only or browser-safe, while the same boundary written as `no-restricted-imports` (the browser runtime block in `eslint.config.mjs`) found exactly the one real violation. The model also emits findings whose own message concludes "no violation"; a prompt does not reliably suppress that, so every rule states its carve-outs as "return no finding".
+
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.
## Where a rule lives
@@ -46,8 +48,9 @@ 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 check --alint # changed lines of changed files, like CI
+bun run check --alint src/a.ts # explicit paths are linted whole
+bun run alint --dirty # the same scope as the first line, alint's own reporter
bun run alint src/features/Foo # any files or directories
```
@@ -77,6 +80,22 @@ The `alint Β·` steps at the end of the "ALint & Test Desktop App" job in `.githu
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`.
+## Whole-repo calibration, 2026-09-29
+
+Every rule was run cold over all of canary (apps/server, packages, src: 14.7k model calls, 40M input tokens, about 10 minutes at `--rule-concurrency 32`), and each finding was read or sampled. Findings are legacy code; CI and `check --alint` only report changed lines, so they surface when someone edits that line.
+
+| Rule | Before | After | What changed |
+| ----------------------------- | ------ | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `no-node-in-browser` | 34 | 0 | 33 were type-only (`import { type X }` is erased without `verbatimModuleSyntax`) or browser-safe; the path part moved to ESLint, which found the one real violation |
+| `no-transactions-in-models` | 109 | 51 | redefined on aggregates: owned child rows, event / history rows, link rows and cascade deletes are the same aggregate |
+| `no-mode-flags` | 98 | 17 | only flags that name a host (`inShare`, `embedded`, `mobile` page compositions) and gate fetching or editing |
+| `no-effect-fetching` | 48 | 43 | writes then refresh, prefetch, auth / QR handshakes, locale chunks and repeat call sites dropped; store actions fetching on mount added |
+| `pmap-over-promise-all` | 211 | 216 | high precision; code-level registries (adapter maps) no longer reported |
+| `no-dynamic-import-in-server` | 51 | 51 | matches the rule as written; left as `warn` |
+| `hetero/*` | 0 | 0 | |
+
+Known remaining false positives: `no-transactions-in-models` still reports a subtype row deleted with its `user_memories` base row and a topic usage rollup recomputed after a message write (six findings) β€” one file at a time the model sees another table with its own Model.
+
## 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.
diff --git a/packages/alint/fixtures/no-effect-fetching/bad-store-fetch-on-mount.tsx b/packages/alint/fixtures/no-effect-fetching/bad-store-fetch-on-mount.tsx
new file mode 100644
index 00000000000..ef77e759c39
--- /dev/null
+++ b/packages/alint/fixtures/no-effect-fetching/bad-store-fetch-on-mount.tsx
@@ -0,0 +1,24 @@
+// Fixture: a store action that reads from the server on every mount.
+import { memo, useEffect } from 'react';
+
+import { useToolStore } from '@/store/tool';
+
+const ConnectorList = memo(() => {
+ const connectors = useToolStore((s) => s.connectors);
+ const fetchConnectors = useToolStore((s) => s.fetchConnectors);
+
+ // alint-expect
+ useEffect(() => {
+ fetchConnectors();
+ }, [fetchConnectors]);
+
+ return (
+ <ul>
+ {connectors.map((connector) => (
+ <li key={connector.id}>{connector.name}</li>
+ ))}
+ </ul>
+ );
+});
+
+export default ConnectorList;
diff --git a/packages/alint/fixtures/no-effect-fetching/good-locale-chunk.tsx b/packages/alint/fixtures/no-effect-fetching/good-locale-chunk.tsx
new file mode 100644
index 00000000000..13e280e144e
--- /dev/null
+++ b/packages/alint/fixtures/no-effect-fetching/good-locale-chunk.tsx
@@ -0,0 +1,24 @@
+// Fixture: loading a locale chunk is code loading, not server data.
+import { ConfigProvider } from 'antd';
+import type { Locale } from 'antd/es/locale';
+import { memo, type PropsWithChildren, useEffect, useState } from 'react';
+
+import { getAntdLocale } from '@/utils/locale';
+
+const LocaleProvider = memo<PropsWithChildren<{ lang: string }>>(({ children, lang }) => {
+ const [locale, setLocale] = useState<Locale>();
+
+ useEffect(() => {
+ let active = true;
+ getAntdLocale(lang).then((next) => {
+ if (active) setLocale(next);
+ });
+ return () => {
+ active = false;
+ };
+ }, [lang]);
+
+ return <ConfigProvider locale={locale}>{children}</ConfigProvider>;
+});
+
+export default LocaleProvider;
diff --git a/packages/alint/fixtures/no-effect-fetching/good-write-then-refresh.tsx b/packages/alint/fixtures/no-effect-fetching/good-write-then-refresh.tsx
new file mode 100644
index 00000000000..89867da9cff
--- /dev/null
+++ b/packages/alint/fixtures/no-effect-fetching/good-write-then-refresh.tsx
@@ -0,0 +1,25 @@
+// Fixture: a write on open, then SWR revalidation of the result.
+import { memo, useEffect, useState } from 'react';
+import useSWR from 'swr';
+
+import { topicService } from '@/services/topic';
+
+const ShareStatus = memo<{ topicId: string }>(({ topicId }) => {
+ const [failed, setFailed] = useState(false);
+ const { data, mutate } = useSWR(['topic-share', topicId], () =>
+ topicService.getShareInfo(topicId),
+ );
+
+ useEffect(() => {
+ if (data?.visibility) return;
+ topicService
+ .enableSharing(topicId, 'private')
+ .then(() => mutate())
+ .catch(() => setFailed(true));
+ }, [data?.visibility, mutate, topicId]);
+
+ if (failed) return <span>Sharing failed</span>;
+ return <span>{data?.visibility ?? 'private'}</span>;
+});
+
+export default ShareStatus;
diff --git a/packages/alint/fixtures/no-mode-flags/good-behaviour-toggle.tsx b/packages/alint/fixtures/no-mode-flags/good-behaviour-toggle.tsx
new file mode 100644
index 00000000000..bf683588d0b
--- /dev/null
+++ b/packages/alint/fixtures/no-mode-flags/good-behaviour-toggle.tsx
@@ -0,0 +1,31 @@
+// Fixture: behaviour toggles and callbacks tune one capability, not a host.
+import { Button, Input } from '@lobehub/ui/base-ui';
+import { memo, useState } from 'react';
+
+import { AgentPicker } from '@/features/AgentPicker';
+
+interface CreateTaskEntryProps {
+ defaultAgentId: string;
+ disableSend?: boolean;
+ lockAssignee?: boolean;
+ onCreate: (title: string, agentId: string) => void;
+}
+
+const CreateTaskEntry = memo<CreateTaskEntryProps>(
+ ({ defaultAgentId, disableSend, lockAssignee, onCreate }) => {
+ const [title, setTitle] = useState('');
+ const [agentId, setAgentId] = useState(defaultAgentId);
+
+ return (
+ <div>
+ <Input value={title} onChange={(event) => setTitle(event.target.value)} />
+ {!lockAssignee && <AgentPicker value={agentId} onChange={setAgentId} />}
+ <Button disabled={disableSend || !title} onClick={() => onCreate(title, agentId)}>
+ Create
+ </Button>
+ </div>
+ );
+ },
+);
+
+export default CreateTaskEntry;
diff --git a/packages/alint/fixtures/no-node-in-browser/bad-node-only-package.tsx b/packages/alint/fixtures/no-node-in-browser/bad-node-only-package.tsx
new file mode 100644
index 00000000000..2e7e57e741e
--- /dev/null
+++ b/packages/alint/fixtures/no-node-in-browser/bad-node-only-package.tsx
@@ -0,0 +1,14 @@
+// Fixture: a browser component importing a package that spawns git.
+import { memo, useEffect, useState } from 'react';
+// alint-expect
+import { simpleGit } from 'simple-git';
+
+export const BranchBadge = memo<{ cwd: string }>(({ cwd }) => {
+ const [branch, setBranch] = useState('');
+ useEffect(() => {
+ simpleGit(cwd)
+ .branchLocal()
+ .then((result) => setBranch(result.current));
+ }, [cwd]);
+ return <span>{branch}</span>;
+});
diff --git a/packages/alint/fixtures/no-node-in-browser/bad-store-spawn-entry.ts b/packages/alint/fixtures/no-node-in-browser/bad-store-spawn-entry.ts
deleted file mode 100644
index 775a96a0c4f..00000000000
--- a/packages/alint/fixtures/no-node-in-browser/bad-store-spawn-entry.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-// Fixture: a client store action importing the Node-only spawn entry of a workspace package.
-// alint-expect
-import { AgentStreamPipeline } from '@lobechat/heterogeneous-agents/spawn';
-
-export const createLocalPipeline = (operationId: string) =>
- new AgentStreamPipeline({ agentType: 'kimi-code', operationId });
diff --git a/packages/alint/fixtures/no-node-in-browser/bad-usage-footer.tsx b/packages/alint/fixtures/no-node-in-browser/bad-usage-footer.tsx
deleted file mode 100644
index e8679781eb9..00000000000
--- a/packages/alint/fixtures/no-node-in-browser/bad-usage-footer.tsx
+++ /dev/null
@@ -1,13 +0,0 @@
-// Fixture: a client component reading a CLI session log straight from disk.
-// alint-expect
-import { readFile } from 'node:fs/promises';
-
-import { memo, useEffect, useState } from 'react';
-
-export const UsageFooter = memo<{ logPath: string }>(({ logPath }) => {
- const [total, setTotal] = useState(0);
- useEffect(() => {
- readFile(logPath, 'utf8').then((content) => setTotal(content.split('\n').length));
- }, [logPath]);
- return <span>{total} requests</span>;
-});
diff --git a/packages/alint/fixtures/no-node-in-browser/good-eslint-covered-alias.ts b/packages/alint/fixtures/no-node-in-browser/good-eslint-covered-alias.ts
new file mode 100644
index 00000000000..297551b7ff9
--- /dev/null
+++ b/packages/alint/fixtures/no-node-in-browser/good-eslint-covered-alias.ts
@@ -0,0 +1,6 @@
+// Fixture: workspace aliases are ESLint's job; this rule leaves them alone.
+import { type SidebarAgentItem } from '@/database/repositories/home';
+import { lambdaClient } from '@/libs/trpc/client';
+
+export const fetchSidebarAgents = (): Promise<SidebarAgentItem[]> =>
+ lambdaClient.home.getSidebarAgents.query();
diff --git a/packages/alint/fixtures/no-node-in-browser/good-inline-type-specifiers.tsx b/packages/alint/fixtures/no-node-in-browser/good-inline-type-specifiers.tsx
new file mode 100644
index 00000000000..553cb559a1f
--- /dev/null
+++ b/packages/alint/fixtures/no-node-in-browser/good-inline-type-specifiers.tsx
@@ -0,0 +1,19 @@
+// Fixture: every specifier is an inline `type`, so the whole import is erased.
+import { memo } from 'react';
+
+import { type SidebarAgentItem } from '@/database/repositories/home';
+import { type GetGenerationStatusResult } from '@/server/routers/lambda/generation';
+
+interface AgentRowProps {
+ agent: SidebarAgentItem;
+ status?: GetGenerationStatusResult;
+}
+
+const AgentRow = memo<AgentRowProps>(({ agent, status }) => (
+ <div>
+ {agent.title}
+ {status ? ` Β· ${status.status}` : null}
+ </div>
+));
+
+export default AgentRow;
diff --git a/packages/alint/fixtures/no-node-in-browser/good-schema-constant.tsx b/packages/alint/fixtures/no-node-in-browser/good-schema-constant.tsx
new file mode 100644
index 00000000000..68b158d114f
--- /dev/null
+++ b/packages/alint/fixtures/no-node-in-browser/good-schema-constant.tsx
@@ -0,0 +1,26 @@
+// Fixture: schema constants and the hetero root entry are browser-safe.
+import { getHeterogeneousTypeLabel } from '@lobechat/heterogeneous-agents';
+import { Select } from '@lobehub/ui/base-ui';
+import { memo } from 'react';
+
+import { ConnectorToolPermission } from '@/database/schemas';
+
+interface PermissionPickerProps {
+ agentType: string;
+ onChange: (value: string) => void;
+ value: string;
+}
+
+const PermissionPicker = memo<PermissionPickerProps>(({ agentType, onChange, value }) => (
+ <Select
+ aria-label={getHeterogeneousTypeLabel(agentType)}
+ value={value}
+ options={Object.values(ConnectorToolPermission).map((permission) => ({
+ label: permission,
+ value: permission,
+ }))}
+ onChange={onChange}
+ />
+));
+
+export default PermissionPicker;
diff --git a/packages/alint/fixtures/no-transactions-in-models/bad-writes-other-aggregate.ts b/packages/alint/fixtures/no-transactions-in-models/bad-writes-other-aggregate.ts
new file mode 100644
index 00000000000..f44d79143b7
--- /dev/null
+++ b/packages/alint/fixtures/no-transactions-in-models/bad-writes-other-aggregate.ts
@@ -0,0 +1,27 @@
+// Fixture: changing a member's role also rewrites another aggregate's rows.
+import { and, eq } from 'drizzle-orm';
+
+import { tasks, workspaceMembers } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+
+export class WorkspaceMemberModel {
+ constructor(private readonly db: LobeChatDatabase) {}
+
+ async updateRole(workspaceId: string, userId: string, role: string) {
+ // alint-expect
+ return this.db.transaction(async (tx) => {
+ await tx
+ .update(workspaceMembers)
+ .set({ role })
+ .where(
+ and(eq(workspaceMembers.workspaceId, workspaceId), eq(workspaceMembers.userId, userId)),
+ );
+ if (role === 'viewer') {
+ await tx
+ .update(tasks)
+ .set({ assigneeUserId: null })
+ .where(and(eq(tasks.workspaceId, workspaceId), eq(tasks.assigneeUserId, userId)));
+ }
+ });
+ }
+}
diff --git a/packages/alint/fixtures/no-transactions-in-models/good-owned-children-and-events.ts b/packages/alint/fixtures/no-transactions-in-models/good-owned-children-and-events.ts
new file mode 100644
index 00000000000..b9c86b3a002
--- /dev/null
+++ b/packages/alint/fixtures/no-transactions-in-models/good-owned-children-and-events.ts
@@ -0,0 +1,24 @@
+// Fixture: a root row, its owned child rows and its event log are one aggregate.
+import { eq } from 'drizzle-orm';
+
+import { goalEvents, goalNodes, messagePlugins, messages } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+
+export class GoalNodeModel {
+ constructor(private readonly db: LobeChatDatabase) {}
+
+ async updateStatus(id: string, status: string) {
+ return this.db.transaction(async (tx) => {
+ await tx.update(goalNodes).set({ status }).where(eq(goalNodes.id, id));
+ await tx.insert(goalEvents).values({ nodeId: id, type: 'status', payload: { status } });
+ });
+ }
+
+ async createToolMessage(content: string, toolCallId: string) {
+ return this.db.transaction(async (tx) => {
+ const [message] = await tx.insert(messages).values({ content, role: 'tool' }).returning();
+ await tx.insert(messagePlugins).values({ id: message.id, toolCallId });
+ return message;
+ });
+ }
+}
diff --git a/packages/alint/fixtures/no-transactions-in-models/good-subtype-and-rollup.ts b/packages/alint/fixtures/no-transactions-in-models/good-subtype-and-rollup.ts
new file mode 100644
index 00000000000..c7b67cb077f
--- /dev/null
+++ b/packages/alint/fixtures/no-transactions-in-models/good-subtype-and-rollup.ts
@@ -0,0 +1,29 @@
+// Fixture: a subtype row with its base row, and a rollup on the parent.
+import { eq, sql } from 'drizzle-orm';
+
+import { messages, topics, userMemories, userMemoriesPreferences } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+
+export class UserMemoryPreferenceModel {
+ constructor(private readonly db: LobeChatDatabase) {}
+
+ async delete(id: string) {
+ return this.db.transaction(async (tx) => {
+ const [row] = await tx
+ .delete(userMemoriesPreferences)
+ .where(eq(userMemoriesPreferences.id, id))
+ .returning();
+ if (row) await tx.delete(userMemories).where(eq(userMemories.id, row.userMemoryId));
+ });
+ }
+
+ async updateMessage(id: string, topicId: string, content: string) {
+ return this.db.transaction(async (tx) => {
+ await tx.update(messages).set({ content }).where(eq(messages.id, id));
+ await tx
+ .update(topics)
+ .set({ messageCount: sql`(select count(*) from messages where topic_id = ${topicId})` })
+ .where(eq(topics.id, topicId));
+ });
+ }
+}
diff --git a/packages/alint/fixtures/pmap-over-promise-all/good-registry-fanout.ts b/packages/alint/fixtures/pmap-over-promise-all/good-registry-fanout.ts
new file mode 100644
index 00000000000..827b52b8e2a
--- /dev/null
+++ b/packages/alint/fixtures/pmap-over-promise-all/good-registry-fanout.ts
@@ -0,0 +1,19 @@
+// Fixture: fanning out over registered adapters is bounded by code, not data.
+import type { LobeChatDatabase } from '../../type';
+
+interface WorkTypeAdapter {
+ count: (db: LobeChatDatabase, userId: string) => Promise<number>;
+ type: string;
+}
+
+const WORK_TYPE_ADAPTERS: Record<string, WorkTypeAdapter> = {};
+
+const resolveWorkTypeAdapters = (includeFiles: boolean) =>
+ Object.values(WORK_TYPE_ADAPTERS).filter((adapter) => includeFiles || adapter.type !== 'file');
+
+export const countWorks = async (db: LobeChatDatabase, userId: string, includeFiles: boolean) => {
+ const counts = await Promise.all(
+ resolveWorkTypeAdapters(includeFiles).map((adapter) => adapter.count(db, userId)),
+ );
+ return counts.reduce((sum, count) => sum + count, 0);
+};
diff --git a/packages/alint/rules/no-effect-fetching/rule.alint.toml b/packages/alint/rules/no-effect-fetching/rule.alint.toml
index 2aebc6af926..76bd5d8ff61 100644
--- a/packages/alint/rules/no-effect-fetching/rule.alint.toml
+++ b/packages/alint/rules/no-effect-fetching/rule.alint.toml
@@ -5,14 +5,21 @@ 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).
+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 state: a `*Service.*` call that hits the server, a tRPC client call (`lambdaClient`, `edgeClient`, `trpc.*`), `fetch`, or a zustand store action that fetches from the server on mount (`fetchConnectors()`, `fetchAuthProviders()`, … β€” the store should expose a `useFetch*` SWR hook instead). 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.
+Report a given loader once, on the effect that first runs it on mount. When the same loader is re-run from a polling interval, a focus/visibility listener, or a retry button, those call sites are part of the same finding, not new ones.
+
+Do not report β€” these are the false positives this rule has produced on real code:
+- effects that WRITE: a mutation, `enable*` / `create*` / `sync*` / `prioritize*` / `ensure*` call, analytics or telemetry, even when a `mutate()` / `refresh*()` follows to re-read the result. A refresh after a write is SWR revalidation, not an effect-based fetch;
+- prefetch calls that only warm a cache or store and put nothing into this component's state (`prefetchMessages`, `preload*`, `router.preload`);
+- auth and session plumbing: bootstrapping a login session on mount, token refresh timers, OAuth / QR-code handshakes and their polling loops (`createWechatQrSession` + `poll*`). These are protocol state machines, not cached data;
+- loading code or static assets rather than server data: `import()` of a locale, dictionary or component chunk (`getAntdLocale`, `getUILocaleAndResources`, `loadLocale`), a font or a wasm module;
+- effects that only subscribe or unsubscribe to events, timers, observers, or websocket messages;
+- effects that sync props or URL state into local state, or read from a zustand store, `localStorage`, or a synchronous source;
+- a cleanup function (the effect's return value) that refreshes something on unmount;
+- anything that talks to a local-only bridge rather than the server: Electron IPC (`electronSystemService`, `autoUpdateService`, `binaryService`, `desktop*Service`, `window.electron`, anything backed by `ipcRenderer`), the local file system, or the device gateway.
+
+If an exclusion applies, return no finding for that effect; never emit a finding whose message says the effect is probably out of scope.
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.toml
index e1cdfc99316..ade69f48c74 100644
--- a/packages/alint/rules/no-mode-flags/rule.alint.toml
+++ b/packages/alint/rules/no-mode-flags/rule.alint.toml
@@ -5,13 +5,23 @@ 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.
+Report a component only when ALL of these hold:
+1. the prop (or a context value read the same way, such as `embedded` from a scope hook) names a HOST or a host-level mode: `isShare`, `inShare`, `isPortal`, `inPortal*`, `embedded`, `isPreview`, `readOnly` on a whole viewer or page, `mobile` choosing between two page compositions, `mode` / `viewMode` / `variant` whose values are hosts or surfaces;
+2. it switches off whole capabilities β€” a data-fetching hook, a store subscription, an editor, a toolbar, a hotkey registration, an upload path β€” that stay imported and mounted by the same component;
+3. at least one host is visible in this file or its name (a share page, a portal, a modal, a public page), so the split has somewhere to go.
+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:
+Do not report β€” these are the false positives this rule has produced on real code:
+- behaviour toggles that tune one capability instead of choosing a host: `disableSend`, `lockAssignee`, `autoFocus`, `syncActiveAgent`, `withSingletonActionsBar`;
+- feature gates, Labs toggles and permission checks (`labelsEnabled`, `canEdit`, `isOwner`, `showCollaborators` driven by plan or role) that decide access, not host composition;
+- per-item configuration objects that describe the item being rendered (a provider's `settings.showApiKey`, `showChecker`) β€” they differ by data, not by host;
+- callbacks such as `onSelect` / `onClick`, even when their presence changes the rendering;
- 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.
+- a parent that merely passes such a prop to a child: report the component that branches on it, once.
+
+If an exclusion applies, return no finding.
If uncertain, use low confidence rather than forcing a finding.
"""
diff --git a/packages/alint/rules/no-node-in-browser/rule.alint.toml b/packages/alint/rules/no-node-in-browser/rule.alint.toml
index c9c0a7fe30d..aef6d454f24 100644
--- a/packages/alint/rules/no-node-in-browser/rule.alint.toml
+++ b/packages/alint/rules/no-node-in-browser/rule.alint.toml
@@ -3,20 +3,21 @@ builtInAgent = "basic-structured"
instruction = """
You are reviewing one TypeScript file from LobeHub's web client: the Vite SPA under `src/` (features, routes, store, services, hooks, components, helpers) or a package module the SPA bundles (React UI, client helpers).
-Team rule: code that runs in the browser must not import anything that only exists in Node. The SPA is bundled by Vite, which replaces a Node built-in with a stub that throws on first access; one such import anywhere in the module graph blanks the whole app in development, and production only survives if tree-shaking happens to drop it. The Electron renderer is browser code too β€” it reaches Node only through IPC.
+Team rule: code that runs in the browser must not import anything that only exists in Node. The Electron renderer is browser code too β€” it reaches Node only through IPC.
-Report each static `import` or `export ... from` in this file whose module is Node-only:
-- a Node built-in, with or without the `node:` prefix (`fs`, `fs/promises`, `path`, `os`, `child_process`, `crypto` used as the Node module, `stream`, `net`, `http`, `worker_threads`, `module`, `url` used for `fileURLToPath`, …);
-- a package that needs Node at runtime (a database driver, `sharp`, `electron` main-process APIs, `server-only`, SDKs that read files or spawn processes);
-- a server-only alias or entry: `@/server/*`, `@/database/*` models or repositories, `@lobechat/database` models, or a workspace package subpath documented as Node-only (for `@lobechat/heterogeneous-agents`: `/spawn`, `/rpc`, `/quota-sampler`, `/scanHost`, `/resolveCliCommand`, `/workingDirectory`, `/askUser`, `/builtinMcp`, `/models`).
+ESLint already enforces the deterministic part of this rule (`no-restricted-imports` in eslint.config.mjs): Node built-ins, `@/server/*`, `@/app/(backend)/*`, database models / repositories / clients, and the Node-only subpaths of `@lobechat/heterogeneous-agents`. Do NOT report any of those; they are not your job here.
-Anchor the finding on the import line. In the message, name the module and say why it cannot run in the browser. In the suggestion, say where the work belongs instead: behind a server endpoint (TRPC/service), behind an Electron IPC call, or in a Node-only subpath of the package, with the browser keeping only a pure part (types, parsing, formatting).
+Your job is the part a path list cannot decide: a THIRD-PARTY npm package whose runtime needs Node, imported as a value. Typical examples: database drivers and ORMs' Node adapters (`pg`, `postgres`, `@neondatabase/serverless` pools, `drizzle-orm/node-postgres`), `ioredis`, `sharp`, `simple-git`, `execa`, `node-pty`, `chokidar`, `electron` main-process APIs (`app`, `BrowserWindow`, `ipcMain`), `server-only`, SDKs documented as Node-only or that read files, spawn processes or open raw sockets.
+
+Anchor the finding on the import line. In the message, name the package and what it needs from Node. In the suggestion, say where the work belongs instead: behind a server endpoint (TRPC/service), behind an Electron IPC call, or in a Node-only entry of the package, with the browser keeping only a pure part (types, parsing, formatting).
Do not report:
-- `import type` / `export type` and `typeof import('...')` in type positions β€” they vanish at build time;
-- a dynamic `import('...')` inside code that only runs on the server or in Electron main, when the file clearly also serves that side (say so only if the file is the browser's);
-- files that run on the server or outside the browser: Next.js route handlers and shells (`src/app/(backend)/**`, `route.ts`, server actions), middleware / proxy, `instrumentation*`, files that import `server-only`, `*.server.ts`, config files, scripts, and tests;
-- browser-safe packages that merely share a name with a Node module (`path-browserify`, `buffer` polyfills, `url` used only for the WHATWG `URL`).
+- anything ESLint covers (listed above), including workspace aliases (`@/…`, `@lobechat/…`);
+- type-only imports: `import type { … }`, `export type { … }`, `typeof import('...')`, and `import { type A, type B } from '…'` where every specifier carries `type` β€” the repo does not enable `verbatimModuleSyntax`, so these are erased;
+- packages that are browser-safe or declare a browser build that Vite resolves (`exceljs`, `jszip`, `pdfjs-dist`, `mammoth`, `drizzle-orm` core and `pg-core` schema builders, `nanoid`, `dayjs`, `zod`, `path-browserify`, `buffer` polyfills, `url` used only for the WHATWG `URL`);
+- files that run on the server or outside the browser: Next.js route handlers and shells, middleware / proxy, `instrumentation*`, files that import `server-only`, `*.server.ts`, config files, scripts, and tests.
+
+Report only violations. If an exclusion applies, return no finding; never emit a finding whose message concludes that the import is fine.
-If you cannot tell whether the file runs in the browser, use low confidence rather than forcing a finding.
+If you cannot tell whether the package needs Node at runtime, use low confidence rather than forcing a finding.
"""
diff --git a/packages/alint/rules/no-transactions-in-models/rule.alint.toml b/packages/alint/rules/no-transactions-in-models/rule.alint.toml
index 1bb8fec44d5..631c0dc445c 100644
--- a/packages/alint/rules/no-transactions-in-models/rule.alint.toml
+++ b/packages/alint/rules/no-transactions-in-models/rule.alint.toml
@@ -3,15 +3,27 @@ builtInAgent = "basic-structured"
instruction = """
You are reviewing one file from the LobeHub database package's models layer (packages/database/src/models).
-Team rule: the models layer holds one Model class per aggregate (table). When a write path needs a transaction spanning MORE THAN ONE table β€” a cross-aggregate unit of work such as upserting an environment, its instance, a project link and a directory row inside one `db.transaction` β€” that flow belongs in a Repository under packages/database/src/repositories, not in a Model. Models stay limited to single-aggregate access; repositories own composite, transactional persistence and compose the models.
+Team rule: the models layer holds one Model class per aggregate. An aggregate is a root table plus the rows it owns. When a write path composes SEVERAL AGGREGATES in one transaction β€” for example binding a project directory by upserting an environment, its instance, a project link and a directory row, each of which has a lifecycle of its own β€” that flow belongs in a Repository under packages/database/src/repositories, not in a Model. Models own their aggregate; repositories own cross-aggregate units of work and compose the models.
-Report a Model method whose `this.db.transaction(...)` (or a `tx` / `trx` handle it receives) writes β€” insert, update, delete β€” to two or more different tables. Anchor the finding on the line where the transaction starts (the `.transaction(` call). In the message, name the method and the tables it writes. In the suggestion, name the Repository to extract the flow into, and which single-aggregate pieces can remain Model methods that the repository composes.
+A table is part of THIS model's aggregate, so writing it together with the root is fine, when it is one of:
+- owned child rows that have no meaning without the root row and are only written through it: a message's plugins / files / query chunks, an experiment's benchmark links, a flow's nodes and edges, a document's versions, a persona's history rows;
+- an append-only event, audit, history or outbox row that records the change being made (`appendEvent`, `*_events`, `*_history`, `*_revisions`);
+- the join / link row between this root and another entity, written when this root is created, re-linked or deleted (`agents_to_sessions`, `*_bindings`, `*_members` for this root);
+- cascade cleanup of dependents while deleting this root (`delete` of rows keyed by the root id).
+- the base row of a subtype table: when this model's table extends a shared base table one-to-one (each `user_memories_*` row pairs with a `user_memories` row), creating or deleting the pair is one entity;
+- a derived rollup or counter on a parent, recomputed from this aggregate's rows (`recomputeTopicUsage`, `*Count`, `updatedAt` touches): it caches a fact this aggregate owns rather than composing the parent.
+
+Report a Model method whose `this.db.transaction(...)` (or a `tx` / `trx` handle it receives) creates or updates the primary rows of ANOTHER aggregate β€” a table that has its own Model class or its own lifecycle (users, topics, tasks, agents, sessions, files, documents, projects, devices, environments, …) β€” beyond the exceptions above. Anchor the finding on the line where the transaction starts (the `.transaction(` call). In the message, name the method, this model's aggregate, and the other aggregate it writes. In the suggestion, name the Repository to extract the flow into, and which single-aggregate pieces can remain Model methods that the repository composes.
Do not report:
+- a transaction whose extra tables all fall under the exceptions above;
+- a table that is only read (`select`, joins, `for('update')` locks) inside the transaction: only insert / update / delete count as writes;
- read-only queries, including joins across many tables β€” reading widely is what models do;
-- a transaction that writes only one table, such as a `.for('update')` lock followed by an update of that same table, or a batch update / reorder of one table;
+- a transaction that writes only one table, such as a lock followed by an update of that same table, or a batch update / reorder of one table;
- single-table upserts (`onConflictDoNothing`, `onConflictDoUpdate`) without an explicit transaction;
- files outside the models layer (repositories, services, routers) β€” transactions are expected there.
+If an exclusion applies, return no finding for that method.
+
If uncertain whether a write hits a second table, 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.toml
index 84634d406d8..73d4c276f61 100644
--- a/packages/alint/rules/pmap-over-promise-all/rule.alint.toml
+++ b/packages/alint/rules/pmap-over-promise-all/rule.alint.toml
@@ -10,6 +10,8 @@ Report each `Promise.all` or `Promise.allSettled` whose input is built by mappin
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).
+- Collections built from a code-level registry whose entries are fixed when the code is written: adapter or handler maps, `Object.values(SOME_CONST)`, a list returned by `resolve*Adapters()` / `get*Handlers()` over registered types. Their size changes only with a code change, not with data.
+- Iterations that do no I/O at all (pure synchronous transforms wrapped in `async`).
- 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/prompts/package.json b/packages/prompts/package.json
index 95f4f98b754..356ec528ea9 100644
--- a/packages/prompts/package.json
+++ b/packages/prompts/package.json
@@ -5,7 +5,8 @@
"exports": {
".": "./src/index.ts",
"./fileSystem": "./src/prompts/fileSystem/index.ts",
- "./textWindow": "./src/textWindow/index.ts"
+ "./textWindow": "./src/textWindow/index.ts",
+ "./toolResult": "./src/toolResult/index.ts"
},
"main": "./src/index.ts",
"scripts": {
diff --git a/apps/server/src/utils/__tests__/truncateToolResult.test.ts b/packages/prompts/src/toolResult/index.test.ts
similarity index 99%
rename from apps/server/src/utils/__tests__/truncateToolResult.test.ts
rename to packages/prompts/src/toolResult/index.test.ts
index 880d31c16ef..69958c11521 100644
--- a/apps/server/src/utils/__tests__/truncateToolResult.test.ts
+++ b/packages/prompts/src/toolResult/index.test.ts
@@ -1,7 +1,7 @@
// @vitest-environment node
import { describe, expect, it } from 'vitest';
-import { truncateToolResult, truncateToolResultWithState } from '../truncateToolResult';
+import { truncateToolResult, truncateToolResultWithState } from './index';
const validEmoji = '\uD83D\uDC1B';
const familyEmoji = '\uD83D\uDC68\u200D\uD83D\uDC69\u200D\uD83D\uDC67\u200D\uD83D\uDC66';
diff --git a/apps/server/src/utils/truncateToolResult.ts b/packages/prompts/src/toolResult/index.ts
similarity index 94%
rename from apps/server/src/utils/truncateToolResult.ts
rename to packages/prompts/src/toolResult/index.ts
index 0aabdf90f59..525c6c24b53 100644
--- a/apps/server/src/utils/truncateToolResult.ts
+++ b/packages/prompts/src/toolResult/index.ts
@@ -1,8 +1,4 @@
-import {
- appendTextWindowNotice,
- sliceTextWindow,
- type TextWindow,
-} from '@lobechat/prompts/textWindow';
+import { appendTextWindowNotice, sliceTextWindow, type TextWindow } from '../textWindow';
/**
* Shared utility for truncating tool execution results
diff --git a/src/services/toolResultArchive.ts b/src/services/toolResultArchive.ts
index f75b97e1733..d87cdfa7bfa 100644
--- a/src/services/toolResultArchive.ts
+++ b/src/services/toolResultArchive.ts
@@ -1,5 +1,6 @@
+import { ARCHIVE_BYPASS_IDENTIFIERS, truncateToolResult } from '@lobechat/prompts/toolResult';
+
import { lambdaClient } from '@/libs/trpc/client';
-import { ARCHIVE_BYPASS_IDENTIFIERS, truncateToolResult } from '@/server/utils/truncateToolResult';
import { chatConfigByIdSelectors } from '@/store/agent/selectors';
import { getAgentStoreState } from '@/store/agent/store';