🤯 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: add source-layout skills and enforce the 800-line limit in check (#20863)
YuTengjing1831c6505406
diff --git a/.agents/scripts/check/advisories.ts b/.agents/scripts/check/advisories.tsindex da250d67d92..12c822dc446 100644--- a/.agents/scripts/check/advisories.ts+++ b/.agents/scripts/check/advisories.ts@@ -1,7 +1,6 @@+import { createBaseLocator } from './base';import { run } from './exec';-import { getConfig, mountDir } from './paths';-import { resolveMount } from './routing';-import type { RepoMount } from './types';+import { mountDir } from './paths';interface BaseFileStatus {baseRef: string;@@ -15,33 +14,21 @@ const TESTING_SKILL_REFERENCE ='.agents/skills/testing/SKILL.md (Core Principles: "No new component tests")';const createBaseFileInspector = (): InspectBaseFile => {- const mergeBases = new Map<RepoMount, Promise<string | undefined>>();+ const locate = createBaseLocator();return async (file) => {- const { mount, subPath } = resolveMount(getConfig().repos, file);- if (!mount.baseRef) return;-- let mergeBase = mergeBases.get(mount);- if (!mergeBase) {- // This advisory is best-effort: an unavailable local base skips it instead of failing checks.- mergeBase = run('git', ['merge-base', 'HEAD', mount.baseRef], mountDir(mount)).then(- (result) => (result.code === 0 ? result.stdout.trim() || undefined : undefined),- );- mergeBases.set(mount, mergeBase);- }-- const baseCommit = await mergeBase;- // Unlike a missing file at a valid base, an unresolved base cannot prove the file is new.- if (!baseCommit) return;+ // An unresolved base cannot prove the file is new, unlike a missing file at a valid base.+ const base = await locate(file);+ if (!base) return;const result = await run('git',- ['cat-file', '-e', `${baseCommit}:${subPath}`],- mountDir(mount),+ ['cat-file', '-e', `${base.baseCommit}:${base.basePath}`],+ mountDir(base.mount),);return {- baseRef: mount.baseRef,+ baseRef: base.baseRef,exists: result.code === 0,};};diff --git a/.agents/scripts/check/base.ts b/.agents/scripts/check/base.tsnew file mode 100644index 00000000000..a1037a9c309--- /dev/null+++ b/.agents/scripts/check/base.ts@@ -0,0 +1,76 @@+import { run } from './exec';+import { getConfig, mountDir } from './paths';+import { resolveMount } from './routing';+import type { RepoMount } from './types';++/** A selected file resolved against its mount's merge base with the configured base ref. */+export interface BaseLocation {+ baseCommit: string;+ /** Mount-relative path of the file at the merge base; differs from `subPath` after a rename. */+ basePath: string;+ baseRef: string;+ mount: RepoMount;+ subPath: string;+}++/** Parse `git diff --name-status -z --diff-filter=R` output into a new-path → old-path map. */+export const parseRenames = (output: string): Map<string, string> => {+ const renames = new Map<string, string>();+ const fields = output.split('\0');+ for (let index = 0; index + 2 < fields.length; index += 3) {+ const [status, from, to] = fields.slice(index, index + 3);+ if (status.startsWith('R')) renames.set(to, from);+ }+ return renames;+};++/**+ * Resolve files to their mount's merge base, computing each merge base and+ * rename map once. Renames matter because a split starts with a move-only+ * commit (`Foo.tsx` → `Foo/index.tsx`); without them, a moved file looks new.+ * Returns undefined when the mount has no base ref or the base is unavailable+ * locally: base-dependent checks are best-effort and skip instead of failing.+ */+export const createBaseLocator = () => {+ const bases = new Map<+ RepoMount,+ Promise<{ baseCommit: string; renames: Map<string, string> } | undefined>+ >();++ const resolveBase = async (mount: RepoMount, baseRef: string) => {+ const cwd = mountDir(mount);+ const mergeBase = await run('git', ['merge-base', 'HEAD', baseRef], cwd);+ const baseCommit = mergeBase.code === 0 ? mergeBase.stdout.trim() : '';+ if (!baseCommit) return;++ // Diffing the base against the working tree covers committed and staged renames.+ const diff = await run(+ 'git',+ ['diff', '-M', '--name-status', '-z', '--diff-filter=R', baseCommit],+ cwd,+ );+ return { baseCommit, renames: diff.code === 0 ? parseRenames(diff.stdout) : new Map() };+ };++ return async (file: string): Promise<BaseLocation | undefined> => {+ const { mount, subPath } = resolveMount(getConfig().repos, file);+ if (!mount.baseRef) return;++ let base = bases.get(mount);+ if (!base) {+ base = resolveBase(mount, mount.baseRef);+ bases.set(mount, base);+ }++ const resolved = await base;+ if (!resolved) return;++ return {+ baseCommit: resolved.baseCommit,+ basePath: resolved.renames.get(subPath) ?? subPath,+ baseRef: mount.baseRef,+ mount,+ subPath,+ };+ };+};diff --git a/.agents/scripts/check/check.test.ts b/.agents/scripts/check/check.test.tsindex 64e0da93602..778ada865a8 100644--- a/.agents/scripts/check/check.test.ts+++ b/.agents/scripts/check/check.test.ts@@ -7,6 +7,8 @@ import { describe, expect, it } from 'vitest';import { findNewComponentTestAdvisories } from './advisories';import { alintScopeArgs, keepSelectedFiles, parseAlintJson } from './alint';import { diffStat, renderDiffsForStdout } from './autofix';+import { parseRenames } from './base';+import { checkFileSizes, countLines } from './fileSize';import { lobehubPipelines } from './pipelines';import {findVitestConfigDir,@@ -14,6 +16,7 @@ import {pipelineFor,relatedTestCandidates,resolveMount,+ scenarioTestLookup,stylelintApplies,} from './routing';import type { RepoMount } from './types';@@ -127,6 +130,21 @@ describe('relatedTestCandidates', () => {]);});+ it('matches scenario suites split from the source test', () => {+ const lookup = scenarioTestLookup('src/Foo/index.tsx');+ expect(lookup?.dirs).toEqual(['src/Foo', 'src/Foo/__tests__']);+ expect(+ [+ 'index.cta.test.ts',+ 'index.render.test.tsx',+ 'index.test.ts',+ 'indexer.cta.test.ts',+ 'index.a.b.test.ts',+ ].filter((name) => lookup?.matches(name)),+ ).toEqual(['index.cta.test.ts', 'index.render.test.tsx']);+ expect(scenarioTestLookup('src/Foo/index.test.ts')).toBeNull();+ });+it('returns nothing for non-source files', () => {expect(relatedTestCandidates('AGENTS.md')).toEqual([]);expect(relatedTestCandidates('image.png')).toEqual([]);@@ -158,6 +176,85 @@ describe('findNewComponentTestAdvisories', () => {});});+describe('parseRenames', () => {+ it('maps each renamed path to its source path', () => {+ expect(parseRenames('R098\0src/Foo.tsx\0src/Foo/index.tsx\0R100\0a.ts\0b/a.ts\0')).toEqual(+ new Map([+ ['src/Foo/index.tsx', 'src/Foo.tsx'],+ ['b/a.ts', 'a.ts'],+ ]),+ );+ expect(parseRenames('')).toEqual(new Map());+ });+});++describe('countLines', () => {+ it.each([+ ['', 0],+ ['a\n', 1],+ ['a\nb', 2],+ ['a\nb\n', 2],+ ])('counts %j as %i lines', (content, expected) => {+ expect(countLines(content)).toBe(expected);+ });+});++describe('checkFileSizes', () => {+ const current: Record<string, number> = {+ 'src/Big.ts': 801,+ 'src/Crossed.ts': 900,+ 'src/Grown.tsx': 1200,+ 'src/Shrunk.ts': 1000,+ 'src/Small.ts': 800,+ 'packages/locales/src/default/setting.ts': 5000,+ 'packages/locales/src/create.ts': 900,+ 'src/types.d.ts': 2000,+ 'packages/sdk/src/generated/types.gen.ts': 12000,+ 'packages/sdk/src/generated/core/client.ts': 900,+ 'README.md': 5000,+ };+ const base: Record<string, number | null> = {+ 'src/Big.ts': null,+ 'packages/locales/src/create.ts': null,+ 'packages/locales/src/default/setting.ts': 4000,+ 'src/types.d.ts': 1000,+ 'packages/sdk/src/generated/types.gen.ts': null,+ 'packages/sdk/src/generated/core/client.ts': null,+ 'src/Crossed.ts': 790,+ 'src/Grown.tsx': 1100,+ 'src/Shrunk.ts': 1100,+ };+ const run = (files: string[]) =>+ checkFileSizes(+ files,+ async (file) => current[file],+ async (file) => ({ baseRef: 'origin/canary', lines: base[file] }),+ );++ it('fails new and newly oversized files and only advises on grown legacy files', async () => {+ const findings = await run(Object.keys(current));++ expect(findings.errors).toEqual([+ expect.stringContaining('src/Big.ts: new file has 801 lines'),+ expect.stringContaining('src/Crossed.ts: grew from 790 to 900 lines'),+ expect.stringContaining('packages/locales/src/create.ts: new file has 900 lines'),+ ]);+ expect(findings.advisories).toEqual([+ expect.stringContaining('src/Grown.tsx: already over 800 lines and grew from 1100 to 1200'),+ ]);+ });++ it('skips oversized files when the base cannot be inspected', async () => {+ await expect(+ checkFileSizes(+ ['src/Big.ts'],+ async () => 801,+ async () => undefined,+ ),+ ).resolves.toEqual({ advisories: [], errors: [] });+ });+});+describe('findVitestConfigDir', () => {const configs = new Set(['vitest.config.mts',diff --git a/.agents/scripts/check/fileSize.ts b/.agents/scripts/check/fileSize.tsnew file mode 100644index 00000000000..2c91772f0a1--- /dev/null+++ b/.agents/scripts/check/fileSize.ts@@ -0,0 +1,108 @@+import { readFile } from 'node:fs/promises';+import path from 'node:path';++import { createBaseLocator } from './base';+import { run } from './exec';+import { mountDir, rootDir } from './paths';++export const MAX_FILE_LINES = 800;++const SOURCE_PATTERN = /\.[cm]?[jt]sx?$/;+/**+ * Declarations, default locale tables, and generated code are data or tool+ * output, not hand-written code that splits on a module boundary.+ */+const EXEMPT_PATTERN =+ /\.d\.[cm]?ts$|\.gen\.[cm]?[jt]sx?$|(?:^|\/)generated\/|(?:^|\/)locales\/(?:src\/)?default\//;+const RULE_REFERENCE = '.agents/skills/source-layout/SKILL.md §3';++/** Line count at the merge base; `null` when the file does not exist there. */+interface BaseLines {+ baseRef: string;+ lines: number | null;+}++type ReadBaseLines = (file: string) => Promise<BaseLines | undefined>;+type ReadLines = (file: string) => Promise<number>;++export interface FileSizeFindings {+ /** Advisories for legacy over-limit files that grew; reported without failing the run. */+ advisories: string[];+ /** New files over the limit, or files this change pushed over it; these fail the run. */+ errors: string[];+}++/** Same count as `wc -l`, plus a final line without a trailing newline. */+export const countLines = (content: string) => {+ if (content.length === 0) return 0;+ const newlines = content.split('\n').length - 1;+ return content.endsWith('\n') ? newlines : newlines + 1;+};++const readLines: ReadLines = async (file) =>+ countLines(await readFile(path.join(rootDir(), file), 'utf8'));++const createBaseLinesReader = (): ReadBaseLines => {+ const locate = createBaseLocator();++ return async (file) => {+ const base = await locate(file);+ if (!base) return;++ const result = await run(+ 'git',+ ['show', `${base.baseCommit}:${base.basePath}`],+ mountDir(base.mount),+ );++ return {+ baseRef: base.baseRef,+ lines: result.code === 0 ? countLines(result.stdout) : null,+ };+ };+};++/**+ * Enforce the 800-line limit on changed source and test files. Hundreds of+ * legacy files already exceed it, so blocking every touch would stall+ * unrelated fixes: only violations this change creates fail the run, and a+ * legacy file that keeps growing is reported as an advisory.+ */+export const checkFileSizes = async (+ files: string[],+ readCurrentLines: ReadLines = readLines,+ readBaseLines: ReadBaseLines = createBaseLinesReader(),+): Promise<FileSizeFindings> => {+ const findings: FileSizeFindings = { advisories: [], errors: [] };+ const candidates = [+ ...new Set(files.filter((file) => SOURCE_PATTERN.test(file) && !EXEMPT_PATTERN.test(file))),+ ];++ const sizes = await Promise.all(candidates.map((file) => readCurrentLines(file)));+ const oversized = candidates+ .map((file, index) => ({ file, lines: sizes[index] }))+ .filter(({ lines }) => lines > MAX_FILE_LINES);+ const bases = await Promise.all(oversized.map(({ file }) => readBaseLines(file)));++ oversized.forEach(({ file, lines }, index) => {+ const base = bases[index];+ // Without a base the change cannot be told apart from legacy debt.+ if (!base) return;++ if (base.lines === null) {+ findings.errors.push(+ `${file}: new file has ${lines} lines (limit ${MAX_FILE_LINES}, relative to ${base.baseRef}). Split it on a real boundary before committing (${RULE_REFERENCE}).`,+ );+ } else if (base.lines <= MAX_FILE_LINES) {+ findings.errors.push(+ `${file}: grew from ${base.lines} to ${lines} lines, crossing the ${MAX_FILE_LINES}-line limit (relative to ${base.baseRef}). Split it in this change (${RULE_REFERENCE}).`,+ );+ } else if (lines > base.lines) {+ findings.advisories.push(+ `${file}: already over ${MAX_FILE_LINES} lines and grew from ${base.lines} to ${lines} (relative to ${base.baseRef}). Over-limit files must not grow; extract the part this change touches (${RULE_REFERENCE}).`,+ );+ }+ });++ return findings;+};diff --git a/.agents/scripts/check/index.ts b/.agents/scripts/check/index.tsindex 48361c53b7a..f1f626422e6 100644--- a/.agents/scripts/check/index.ts+++ b/.agents/scripts/check/index.ts@@ -19,16 +19,20 @@* mounting this repo provides its own entry that adds its root pipelines and* mounts this repo's via `pipelines.ts`.*/+import { readdir } from 'node:fs/promises';+import path from 'node:path';+import { findNewComponentTestAdvisories } from './advisories';import { runAlint } from './alint';import { collectAutofixDiffs, snapshot, writeFullDiff } from './autofix';import { collectFromGit, normalizeArgs } from './collect';import { assertCheckRoot } from './delegate';import { run } from './exec';+import { checkFileSizes } from './fileSize';import { lintGroup } from './lint';-import { existsInRepo, setConfig } from './paths';+import { existsInRepo, rootDir, setConfig } from './paths';import { printReport } from './report';-import { pipelineFor, relatedTestCandidates, resolveMount } from './routing';+import { pipelineFor, relatedTestCandidates, resolveMount, scenarioTestLookup } from './routing';import type { CheckConfig, FileDiff, LintProblem, RepoMount, TestOutcome } from './types';import { runTestGroups } from './vitest';@@ -49,6 +53,20 @@ const filterExisting = async (candidates: string[]): Promise<string[]> => {return candidates.filter((_, index) => present[index]);};+/** Scenario suites (`<base>.<scenario>.test.*`) beside a source file or in its `__tests__/`. */+const findScenarioTests = async (file: string): Promise<string[]> => {+ const lookup = scenarioTestLookup(file);+ if (!lookup) return [];++ const listed = await Promise.all(+ lookup.dirs.map(async (dir) => {+ const names = await readdir(path.join(rootDir(), dir)).catch(() => [] as string[]);+ return names.filter((name) => lookup.matches(name)).map((name) => path.join(dir, name));+ }),+ );+ return listed.flat();+};+export const runCli = async (config: CheckConfig) => {setConfig(config);@@ -137,13 +155,21 @@ export const runCli = async (config: CheckConfig) => {let tests: TestOutcome | null = null;let testFiles: string[] = [];if (runTest) {+ const scenarioTests = await Promise.all(files.map((file) => findScenarioTests(file)));testFiles = await filterExisting([- ...new Set(files.flatMap((file) => relatedTestCandidates(file))),+ ...new Set([+ ...files.flatMap((file) => relatedTestCandidates(file)),+ ...scenarioTests.flat(),+ ]),]);tests = await runTestGroups(testFiles);}- const advisories = await findNewComponentTestAdvisories([...new Set([...files, ...testFiles])]);+ const sizeFindings = await checkFileSizes(files);+ const advisories = [+ ...(await findNewComponentTestAdvisories([...new Set([...files, ...testFiles])])),+ ...sizeFindings.advisories,+ ];/* ---- Type check ---- */let typeOutput: string | null = null;@@ -161,6 +187,7 @@ export const runCli = async (config: CheckConfig) => {fullDiffPath,lintRan: runLint || wantAlint,problems,+ sizeErrors: sizeFindings.errors,skipped,testFileCount: testFiles.length,tests,diff --git a/.agents/scripts/check/report.ts b/.agents/scripts/check/report.tsindex 923c76426a8..6aa82bf537f 100644--- a/.agents/scripts/check/report.ts+++ b/.agents/scripts/check/report.ts@@ -10,6 +10,8 @@ export interface ReportInput {fullDiffPath: string | null;lintRan: boolean;problems: LintProblem[];+ /** Files over the line limit that this change created; they fail the run. */+ sizeErrors: string[];/** Files with no matching lint pipeline (only counted when lint ran). */skipped: number;testFileCount: number;@@ -29,6 +31,7 @@ export const printReport = (input: ReportInput): { failed: boolean } => {fullDiffPath,lintRan,problems,+ sizeErrors,skipped,testFileCount,tests,@@ -40,6 +43,7 @@ export const printReport = (input: ReportInput): { failed: boolean } => {const failed =errors.length > 0 ||fatal.length > 0 ||+ sizeErrors.length > 0 ||(tests?.failedOutput.length ?? 0) > 0 ||Boolean(typeOutput);@@ -67,6 +71,7 @@ export const printReport = (input: ReportInput): { failed: boolean } => {);}if (typeOutput !== null) parts.push(typeOutput ? 'types failed' : 'types clean');+ if (sizeErrors.length > 0) parts.push(`${sizeErrors.length} oversized`);if (advisories.length > 0) parts.push(`${advisories.length} advisories`);if (skipped > 0) parts.push(`${skipped} skipped (no linter)`);@@ -81,6 +86,11 @@ export const printReport = (input: ReportInput): { failed: boolean } => {}for (const message of fatal) console.log(`\nlint fatal:\n${message}`);+ if (sizeErrors.length > 0) {+ console.log('\nfile size:');+ for (const message of sizeErrors) console.log(`✗ ${message}`);+ }+if (advisories.length > 0) {console.log('\nadvisories:');for (const advisory of advisories) console.log(`⚠ ${advisory}`);diff --git a/.agents/scripts/check/routing.ts b/.agents/scripts/check/routing.tsindex 91b3aa097f2..43df55931cc 100644--- a/.agents/scripts/check/routing.ts+++ b/.agents/scripts/check/routing.ts@@ -56,6 +56,25 @@ export const relatedTestCandidates = (relPath: string): string[] => {]);};+/**+ * Scenario suites split from a large test (`<base>.<scenario>.test.*`, see+ * `source-layout` §2): the directories to list and a matcher for their+ * entries. Pure — the caller lists the directories.+ */+export const scenarioTestLookup = (relPath: string) => {+ if (isTestFile(relPath) || !/\.[cm]?[jt]sx?$/.test(relPath)) return null;++ const dir = path.dirname(relPath);+ const base = path.basename(relPath).replace(/\.[^.]+$/, '');+ const pattern = new RegExp(+ `^${base.replaceAll(/[$()*+.?[\\\]^{|}]/g, '\\$&')}\\.[^.]+\\.test\\.(?:ts|tsx|mts)$`,+ );+ return {+ dirs: [dir, path.join(dir, '__tests__')],+ matches: (name: string) => pattern.test(name),+ };+};+/*** Nearest directory (walking up to the host root) containing a vitest config —* the "run vitest from the owning package" rule, automated.diff --git a/.agents/scripts/check/size-gate.ts b/.agents/scripts/check/size-gate.tsnew file mode 100644index 00000000000..d21fa0286b0--- /dev/null+++ b/.agents/scripts/check/size-gate.ts@@ -0,0 +1,17 @@+/**+ * Standalone entry of the file-size gate (see `sizeGate.ts`); a superproject+ * mounting this repo provides its own entry with its config.+ */+import path from 'node:path';+import { fileURLToPath } from 'node:url';++import { lobehubPipelines } from './pipelines';+import { runSizeGate } from './sizeGate';++runSizeGate({+ repos: [{ dir: '', pipelines: lobehubPipelines }],+ rootDir: path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../..'),+}).catch((error) => {+ console.error(`✗ size gate crashed: ${error?.stack ?? error}`);+ process.exit(2);+});diff --git a/.agents/scripts/check/sizeGate.ts b/.agents/scripts/check/sizeGate.tsnew file mode 100644index 00000000000..92d54b106cc--- /dev/null+++ b/.agents/scripts/check/sizeGate.ts@@ -0,0 +1,44 @@+/// <reference types="node" />++/**+ * File-size gate for hooks and CI: `size-gate.ts --staged` (pre-commit, base+ * `HEAD`) or `size-gate.ts --base <ref>` (CI, base = merge base with `<ref>`).+ *+ * Unlike `bun run check`, it only inspects the host repo's own files: a+ * mounted sub-repo commits through its own hook and runs its own CI. Rules+ * live in `fileSize.ts` and `.agents/skills/source-layout/SKILL.md` §3.+ */+import { git } from './exec';+import { checkFileSizes } from './fileSize';+import { setConfig } from './paths';+import type { CheckConfig } from './types';++const USAGE = 'Usage: size-gate.ts --staged | --base <ref>';++export const runSizeGate = async (config: CheckConfig) => {+ const args = process.argv.slice(2);+ const staged = args.includes('--staged');+ const baseArg = args.indexOf('--base');+ const baseRef = staged ? 'HEAD' : baseArg === -1 ? undefined : args[baseArg + 1];+ const host = config.repos.find((repo) => repo.dir === '');+ if (!baseRef || !host) {+ console.error(USAGE);+ process.exit(2);+ }++ setConfig({ ...config, repos: [{ ...host, baseRef }] });++ const files = staged+ ? await git(['diff', '--cached', '--name-only', '--diff-filter=d'])+ : await git(['diff', '--name-only', '--diff-filter=d', `${baseRef}...HEAD`]);+ const { advisories, errors } = await checkFileSizes(files);++ // GitHub Actions turns these lines into annotations on the PR diff.+ const annotate = process.env.GITHUB_ACTIONS === 'true';+ for (const message of advisories)+ console.log(annotate ? `::warning::${message}` : `⚠ ${message}`);+ for (const message of errors) console.log(annotate ? `::error::${message}` : `✗ ${message}`);++ if (errors.length > 0) process.exit(1);+ console.log(`✓ file size: ${files.length} changed files within limits`);+};diff --git a/.agents/skills/desktop/SKILL.md b/.agents/skills/desktop/SKILL.mdindex 38e602a4721..9222c320685 100644--- a/.agents/skills/desktop/SKILL.md+++ b/.agents/skills/desktop/SKILL.md@@ -70,7 +70,7 @@ Location: `src/store/`### 5. Add Tests-Location: `apps/desktop/src/main/controllers/__tests__/`+Location: beside the controller, `apps/desktop/src/main/controllers/<Name>Ctr.test.ts` (`source-layout` §2)## Detailed Guidesdiff --git a/.agents/skills/react/SKILL.md b/.agents/skills/react/SKILL.mdindex 33e379db215..040b2c3c39a 100644--- a/.agents/skills/react/SKILL.md+++ b/.agents/skills/react/SKILL.md@@ -58,7 +58,7 @@ For Modal specifically, see the dedicated **modal** skill — use the imperativeKeep transient state in its smallest useful owner. Extract a custom hook when state transitions and handlers obscure rendering or form a reusable unit; do not extract solely because a component has a particular number of hooks.-Split a component only to establish a real state, reuse, render-update, or mountable-capability boundary. Do not split solely to make files smaller. Decomposing a heavy domain feature into host-assembled atoms is owned by **`compose-atoms`**.+Split a component only to establish a real state, reuse, render-update, or mountable-capability boundary. Do not split solely to make files smaller; when a file reaches the 800-line limit in **`source-layout`**, find one of these boundaries rather than cutting at a line count. Decomposing a heavy domain feature into host-assembled atoms is owned by **`compose-atoms`**.## Render Performance and Memoizationdiff --git a/.agents/skills/source-layout/SKILL.md b/.agents/skills/source-layout/SKILL.mdnew file mode 100644index 00000000000..f12e022515c--- /dev/null+++ b/.agents/skills/source-layout/SKILL.md@@ -0,0 +1,65 @@+---+name: source-layout+description: 'Use for where a file lives, how it is named, where its tests go, and how to split a source or test file over 800 lines (拆分大文件, 目录结构, 文件命名).'+user-invocable: false+---++# Source Layout++Top-level ownership (`src/features`, `src/routes`, `apps/server/src`, `packages`, …) is in `AGENTS.md` and `project-overview`. This skill owns placement and naming inside those roots, test placement, and how a large file becomes a directory. The rules record the conventions the codebase already follows; where it was split between two forms, the rule names the one to use for new files. Do not rename existing files only to match.++## 1. Names++| What | Form | Example |+| ---------------------------------------------------- | --------------------- | ---------------------------------------------- |+| React component file / component directory | PascalCase | `PlanCard.tsx`, `ChatInput/ControlBar/` |+| Hook | `useXxx.ts(x)` | `ChatInputNotice/useChatInputNotice.ts` |+| Other module | camelCase or one word | `originLink.ts`, `recentDirs.ts` |+| Server class module | the class name | `services/agentRuntime/CompletionLifecycle.ts` |+| Service, router, store, and other non-component dirs | camelCase | `services/aiAgent/`, `store/chat/slices/` |+| Package directory | kebab-case | `packages/agent-runtime/` |+| Files inside a package | camelCase | `packages/database/src/models/` |++A package whose files are already kebab-case (`alint`, `openapi`, `builtin-skills`) keeps kebab-case internally. Shared per-directory modules are `constants.ts`, `types.ts`, `style.ts`, and `utils.ts`, not `const.ts`, `type.ts`, `styles.ts`, or `helpers.ts`. Create one only when two or more modules in that directory use it; a constant or type used by one module stays in that module.++New files use named exports (`export const PlanCard = …`), even when the neighboring files default-export; do not copy the older default-export habit. The exceptions are modules a framework, tool, or loader imports by their default export: route segments under `src/routes` (see `spa-routes`), Next.js special files (`page.tsx`, `layout.tsx`, `not-found.tsx`), `*.config.ts` files, desktop controllers and services (`*Ctr.ts`, `*Srv.ts`, globbed by `apps/desktop/src/main/core/App.ts`), and locale resource files. Lint does not enforce this: this repository's `eslint.config.mjs` overrides `no-restricted-syntax`, which drops the shared `@lobehub/lint` warning on `export default`. When moving an existing file, keep its exports unchanged so its callers do not change.++## 2. Tests++One rule for every app and package:++- A test of one module sits beside it: `Foo.ts` → `Foo.test.ts`; a directory entry's test is `index.test.ts`.+- `__tests__/` holds only tests that do not belong to one module: integration tests that run several modules together or real infrastructure (database, Redis, the tRPC or Hono request stack), such as `routers/lambda/__tests__/integration/` and the database model and repository tests in `testing`, plus their shared setup, fixtures, and fakes.+- New tests follow this rule even in a directory whose existing unit tests sit in `__tests__/`. Move an existing unit test beside its module when you split or rewrite that test file; do not migrate tests as a side task.+- Split a large test file by scenario: `Foo.<scenario>.test.ts(x)`, keeping the original extension (`index.<scenario>.test.ts(x)` for a directory entry). Put shared mock factories and fixtures in a `testUtils.ts` beside them; each test file keeps its own `vi.mock` calls, because Vitest hoists them per file.+- Do not add React component tests, including to guard a split. Extract the logic into a hook or pure function and test that in `.test.ts` (`testing`).++## 3. File size++Source and test files stay at or below 800 lines. Generated code (`*.gen.ts`, `generated/` directories) and the `locales/default/` tables are exempt:++- A new file over 800 lines, or an existing file that crosses 800 lines in this change, is split in the same change. `bun run check`, the pre-commit hook, and the PR's File Size Gate job fail on both.+- A file already over 800 lines must not grow, including for a bug fix: the change may only keep or reduce its line count. Before adding code, extract the cohesive part the change touches. Put a new test in a scenario test file under the limit (§2), splitting the old test file first when the test belongs to one of its scenarios. Because hundreds of legacy files are over the limit, these checks report their growth as an advisory (a warning annotation in CI) instead of failing; it is still a required fix.++The limit says when to split, not where. Split on a real boundary (state, reuse, render update, sub-domain, pipeline stage), as `react` requires; never cut a file at an arbitrary line count. When a heavy feature is mounted by several hosts, use `compose-atoms` instead.++## 4. Turning a file into a directory++A split keeps the public import path: `Foo.tsx` becomes `Foo/index.tsx`, so `import Foo from './Foo'` keeps working and callers do not change. Commit the move (`mkdir -p Foo && git mv Foo.tsx Foo/index.tsx`) alone before extracting, so reviewers can read the extraction diff separately and Git keeps the rename while those commits stay intact (a squash merge folds them together). `split-large-file` has the full procedure.++| Kind | `index` keeps | Siblings | Precedent |+| --------------- | ----------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------- |+| React component | Public API, shared top-level state, composition | Child components (PascalCase), `useXxx.ts` for state transitions and side effects, pure logic modules with their own tests | `Conversation/Messages/GoalTaskCard/` |+| Server service | The class and its orchestration methods | Stage functions taking an explicit `deps` object (`pipeline/<stage>.ts`), sub-domain folders | `services/aiAgent/`, `services/comfyui/` |+| tRPC router | The merged router | One sub-router per sub-domain (`market/agent.ts` exports `agentRouter`) | `routers/lambda/market/` |+| Zustand store | — | Follow `zustand` | `src/store/page` |++- Prefer flat siblings. Add a sub-folder for a sub-area with several files of its own (`ChatInput/ControlBar/`).+- Kind folders (`components/`, `hooks/`, `utils/`) follow who uses the code:+ - One user: keep it in that file or beside it (`PlanGrid/usePlanActions.ts`).+ - A few modules in the directory share it: flat siblings for hooks and components, one `utils.ts` for pure functions.+ - Three or more files of one kind shared by sibling modules: collect them in a kind folder (`Dashboard/utils/`, `ChatInput/hooks/`, `ResourceManager/components/`).+ - Shared across features: `src/utils`, `src/hooks`, `src/components`, or a `packages/*` package.+ - Do not create `helpers/`; name the module by its content or use `utils`.+- A split moves code without changing behavior. Collapsing duplicated branches that become one component is in scope when existing tests cover each branch; any other behavior change belongs in a separate commit.+- Move the matching tests with the code they cover, then run `bun run check` with the test files passed explicitly: related-test discovery finds only `<name>.test.*` and `<name>.<scenario>.test.*` of each changed file, so the entry's tests do not run for an extracted sibling such as `usePlanActions.ts`.diff --git a/.agents/skills/split-large-file/SKILL.md b/.agents/skills/split-large-file/SKILL.mdnew file mode 100644index 00000000000..bbe8de0ad6d--- /dev/null+++ b/.agents/skills/split-large-file/SKILL.md@@ -0,0 +1,88 @@+---+name: split-large-file+description: 'Refactor a source file over 800 lines into a directory of cohesive modules without changing behavior, test-first. Use when asked to split, decompose, or shrink a large file (拆分大文件, 拆文件, 重构大文件); with no file given, pick one.'+---++# Split a Large File++Split one file into a directory of modules without changing behavior. Where the pieces go, what they are named, and where tests live are owned by `source-layout`; read it first. This skill owns the procedure: lock behavior with tests, move, extract, then split the tests.++The split changes no behavior. If you find a bug on the way, note it and fix it in a separate commit or PR after the split.++## 1. Pick the file++Given a file, use it. Otherwise build a shortlist:++```bash+git ls-files -z -- 'src/*.ts' 'src/*.tsx' 'apps/*.ts' 'apps/*.tsx' 'packages/*.ts' 'packages/*.tsx' \+ | rg --null-data -v '(^|/)(__tests__|__mocks__|fixtures|locales)/|\.(test|spec)\.|\.d\.ts$' \+ | xargs -0 wc -l | awk '$1 > 800 && $NF != "total"' | sort -rn | head -30+```++The shortlist still contains data tables and generated code; filter it by reading. Prefer a file with:++- **A real extraction boundary**: hand-written logic with separable state, sub-domains, or stages, not a lookup table.+- **A repeatable verification surface**: behavior that unit or integration tests can observe (including the real-database tests `testing` requires for models), not one that needs a browser session or live third-party calls.+- **A reviewable scope**: one PR can hold the split. When this repository is mounted as a submodule, split a file of the submodule only through a PR to the submodule.++Use recent churn (`git log --since=3.months --oneline -- <file> | wc -l`) only to break ties. State the choice and the reason before starting.++## 2. Read and plan++Read the whole file and its tests. Find every reference with `rg` on the module path and basename across source roots: imports, re-exports, dynamic `import()`, `vi.mock('…/Foo')`, explicit extensions, and package entry mappings.++Write a short plan before editing:++- the real boundaries (state, reuse, render update, sub-domain, pipeline stage — see `react` and `source-layout` §3) and the module each becomes;+- the directory layout from `source-layout` §4, with expected line counts;+- duplicated branches that will collapse into one module, if any;+- each behavior the split moves or merges, mapped to the test that will guard it.++When a boundary or layout decision is unclear, ask an independent reviewer (a different-vendor harness when available) to critique the plan.++## 3. Lock the behavior with characterization tests++Existing tests usually cover the happy path and miss the branches a split is most likely to break. Before editing, record the baseline commit and the original path, then:++1. Run the existing tests by explicit path; record the pass count.+2. Pin every branch whose code or branch selection the split changes or merges (each CTA state, early return, error path). For a service, router, or store, test through the public entry: return values and calls. For a component, do not add render tests (`source-layout` §2): first extract the branch selection into a pure function or hook as a mechanical step that keeps every rendered output, then pin that function in `.test.ts`; existing component tests must pass before and after the extraction. Name the state or mock that reaches each branch. Prefer one table test (`it.each`) with expected values written out; inline snapshots do not work inside `it.each`.+3. For a service, router, or store, run the new tests against the original code and record the result. If extraction already started, restore the original **in its original directory** so its relative imports resolve (`git show <baseline>:<path> > <dir>/<Name>Original.ts`), point the test import at it, run, then point it back and delete only that copy.+4. Mutation smoke check: break one guarded branch (for example make an `if` condition `false`), confirm a named test fails, undo exactly that edit, and confirm the test passes again. One mutation shows the tests are sensitive, not that coverage is complete.++Behavior the split moves unchanged and that had no test before stays "uncovered before and after"; say so in the PR instead of claiming it is guarded.++## 4. Move first, in its own commit++Skip this step when the file is already a directory entry (`foo/index.ts`); extract siblings beside it instead. Otherwise move the file and its tests together: `mkdir -p Foo && git mv Foo.tsx Foo/index.tsx` (`git mv` does not create the directory, and `Foo/` may already exist), then move each matching test keeping its extension (`Foo.test.tsx` → `Foo/index.test.tsx`, `Foo.<scenario>.test.ts` → `Foo/index.<scenario>.test.ts`). Rewrite only relative module specifiers in imports, `vi.mock`, and dynamic imports; run the tests by explicit path, and commit. Large extraction in the same commit lowers content similarity until Git stops detecting the rename. A separate move commit keeps the extraction diff reviewable on its own; a squash merge folds both commits together.++## 5. Extract along the plan++Extract one boundary at a time and rerun the guard tests by explicit path after each:++- Pure functions to `utils.ts` (or a named module) with explicit parameters instead of closures over component state.+- For React components, a cohesive `useXxx.ts` when transitions, side effects, or handlers obscure rendering or form a reusable unit; otherwise keep state in its smallest owner (`react`). For services, routers, and stores, use the matching row of `source-layout` §4.+- Child components to PascalCase siblings with named exports.+- A constant stays in the module that uses it; one shared by several extracted modules goes to the nearest common directory's `constants.ts`.++Keep the public import path and exported names unchanged so callers do not change. Every resulting file must be at most 800 lines, and the entry should read as composition, not logic.++## 6. Split and trim the tests++When the test file is large or covers distinct scenarios, split it by scenario (`index.render.test.ts`, `index.actions.test.ts`, …; keep `.tsx` when the tests contain JSX) with shared mocks in `testUtils.ts`, as `source-layout` §2 describes.++Preserve every observable behavior the old suite asserted. Remove a test or assertion only when it duplicates a named retained test, is coupled to implementation details (`testing` lists these), or checks an expectation that is demonstrably obsolete; record each removal and its replacement or evidence in the PR. Merge near-identical tests into `it.each`, and drop mock branches and translation keys nothing renders.++## 7. Verify and deliver++```bash+find <dir> -type f -exec wc -l {} + | sort -rn # every file ≤ 800, nested folders included+bun run check <every changed source file> <every guard test file> --lint --test --type+```++Pass the test files explicitly: related-test discovery finds only `<name>.test.*` and `<name>.<scenario>.test.*` of each changed file, so tests that guard an extracted sibling through the entry (`index.*.test.ts` for `usePlanActions.ts`) run only when passed. Confirm the reported test count matches the suites you expect.++Then follow the normal task lifecycle: a light `deep-review` (suggest Deep when the file is on a high-risk surface such as billing or auth), `commit`, and `pr`. A pure split needs no product acceptance; state that reason in the PR body together with:++- the commits (move, extraction) so reviewers can read the extraction alone;+- the baseline run of the characterization tests and the mutation result;+- removed tests with their replacement, and behavior left uncovered before and after.diff --git a/.agents/skills/testing/references/desktop-controller-test.md b/.agents/skills/testing/references/desktop-controller-test.mdindex 0b2631e35a4..5a0c7b35464 100644--- a/.agents/skills/testing/references/desktop-controller-test.md+++ b/.agents/skills/testing/references/desktop-controller-test.md@@ -2,16 +2,14 @@## Testing Framework & Directory Structure-LobeHub Desktop uses Vitest as the test framework. Controller unit tests should be placed in the `__tests__` directory adjacent to the controller file, named with the original controller filename plus `.test.ts`.+LobeHub Desktop uses Vitest as the test framework. A new controller unit test sits beside the controller, named with the controller filename plus `.test.ts` (`source-layout` §2). Existing tests in `controllers/__tests__/` move beside their controller when that test file is split or rewritten.```plaintextapps/desktop/src/main/controllers/-├── __tests__/-│ ├── index.test.ts-│ ├── MenuCtr.test.ts-│ └── ...├── McpCtr.ts+├── McpCtr.test.ts├── MenuCtr.ts+├── MenuCtr.test.ts└── ...```@@ -22,7 +20,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import type { App } from '@/core/App';-import YourController from '../YourControllerName';+import YourController from './YourControllerName';// Mock dependenciesvi.mock('dependency-module', () => ({diff --git a/.githooks/pre-commit b/.githooks/pre-commitindex f929d3039a3..1400f75dd0b 100755--- a/.githooks/pre-commit+++ b/.githooks/pre-commit@@ -11,3 +11,6 @@ if [ "$BRANCH" = "dev" ] || [ "$BRANCH" = "main" ]; thenfilint-staged++# Runs after lint-staged autofix so it measures the final staged content.+bun run .agents/scripts/check/size-gate.ts --stageddiff --git a/AGENTS.md b/AGENTS.mdindex d066a2c2b59..caa209e55e8 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -105,7 +105,7 @@ When acceptance is required, put its published `https://app.lobehub.com/acceptan### Code Style-- When a single file grows beyond \~800 lines, consider splitting it into multiple files (extract sub-components, hooks, helpers, or types). Smaller, focused files are friendly to humans and agents.+- Source and test files stay at or below 800 lines; a file already over the limit must not grow. Before adding, moving, or splitting files, read the `source-layout` skill for placement, naming, test location, and how a large file becomes a directory.### Code Review