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: simplify agent guidance and guard check execution (#19230)

YuTengjing25bf2310f845
diff --git a/.agents/scripts/check/check.test.ts b/.agents/scripts/check/check.test.ts
index 6016de96482..5391b351f51 100644
--- a/.agents/scripts/check/check.test.ts
+++ b/.agents/scripts/check/check.test.ts
@@ -6,7 +6,6 @@ import { describe, expect, it } from 'vitest';
import { findNewComponentTestAdvisories } from './advisories';
import { diffStat, renderDiffsForStdout } from './autofix';
-import { hostRootFromGitdir } from './delegate';
import { lobehubPipelines } from './pipelines';
import {
findVitestConfigDir,
@@ -183,17 +182,6 @@ describe('findVitestConfigDir', () => {
});
});
-describe('hostRootFromGitdir', () => {
- it('extracts the superproject root from a submodule gitdir', () => {
- expect(hostRootFromGitdir('/work/host/.git/modules/vendor/sub')).toBe('/work/host');
- });
-
- it('returns null for standalone clones and linked worktrees', () => {
- expect(hostRootFromGitdir('/work/repo/.git')).toBeNull();
- expect(hostRootFromGitdir('/work/repo/.git/worktrees/feature')).toBeNull();
- });
-});
-
describe('diffStat', () => {
it('counts added/removed lines, ignoring file headers', () => {
const diff = ['--- a/f', '+++ b/f', '@@ -1,2 +1,2 @@', '-old', '+new', '+extra'].join('\n');
diff --git a/.agents/scripts/check/cli.ts b/.agents/scripts/check/cli.ts
index ed4647293f4..aabf0941dad 100644
--- a/.agents/scripts/check/cli.ts
+++ b/.agents/scripts/check/cli.ts
@@ -3,13 +3,14 @@
* this repo's own pipelines. When this repo is checked out as a submodule of
* a superproject that ships its own `check` script, the run is delegated to
* that entry instead (see `delegate.ts`), so the unified host behavior
- * applies no matter which directory the command is invoked from.
+ * applies when using the selected checkout's own entrypoint from within
+ * that checkout. Foreign entrypoints are rejected before delegation.
*/
import { spawn } from 'node:child_process';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
-import { detectHostCheckRoot } from './delegate';
+import { assertCheckRoot, detectHostCheckRoot } from './delegate';
import { runCli } from './index';
import { lobehubPipelines } from './pipelines';
@@ -18,6 +19,7 @@ const rootDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../.
const main = async () => {
const hostRoot = await detectHostCheckRoot(rootDir);
if (hostRoot) {
+ await assertCheckRoot(rootDir);
console.log(`โ†’ submodule checkout: delegating to the superproject check (${hostRoot})`);
// Absolute file args survive the cwd change; flags pass through untouched.
const args = process.argv
diff --git a/.agents/scripts/check/delegate.test.ts b/.agents/scripts/check/delegate.test.ts
new file mode 100644
index 00000000000..7c61dd2ae0d
--- /dev/null
+++ b/.agents/scripts/check/delegate.test.ts
@@ -0,0 +1,181 @@
+import { chmod, cp, mkdir, mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { afterEach, describe, expect, it } from 'vitest';
+
+import { detectHostCheckRoot } from './delegate';
+import { run } from './exec';
+
+const enginePath = fileURLToPath(new URL('./index.ts', import.meta.url));
+const cliPath = fileURLToPath(new URL('./cli.ts', import.meta.url));
+let fixtureRoot: string | undefined;
+
+const git = async (cwd: string, ...args: string[]) => {
+ const result = await run(
+ 'git',
+ ['-c', 'user.name=Fixture', '-c', '[email protected]', ...args],
+ cwd,
+ );
+ expect(result.code, result.stderr).toBe(0);
+ return result.stdout.trim();
+};
+
+const createFixture = async () => {
+ fixtureRoot = await mkdtemp(path.join(os.tmpdir(), 'check-worktree-'));
+ const host = path.join(fixtureRoot, 'host');
+ const library = path.join(fixtureRoot, 'library');
+ await git(fixtureRoot, 'init', '-b', 'main', library);
+ await writeFile(path.join(library, 'README.md'), 'library\n');
+ await git(library, 'add', 'README.md');
+ await git(library, 'commit', '-m', 'initialize library');
+ await git(fixtureRoot, 'init', '-b', 'main', host);
+ await writeFile(
+ path.join(host, 'package.json'),
+ JSON.stringify({
+ scripts: { 'check': 'bun run ./host-check.ts', 'type-check': 'bun run ./host-check.ts' },
+ }),
+ );
+ await writeFile(path.join(host, 'host-check.ts'), 'console.log("HOST_CHECK");\n');
+ await git(
+ host,
+ '-c',
+ 'protocol.file.allow=always',
+ 'submodule',
+ 'add',
+ library,
+ 'vendor/library',
+ );
+ await git(host, 'add', 'package.json', 'host-check.ts', '.gitmodules', 'vendor/library');
+ await git(host, 'commit', '-m', 'initialize host');
+ return { host, library };
+};
+
+afterEach(async () => {
+ if (fixtureRoot) await rm(fixtureRoot, { force: true, recursive: true });
+ fixtureRoot = undefined;
+});
+
+describe('check entry worktree selection', () => {
+ it('delegates a normal submodule to its containing host', async () => {
+ const { host } = await createFixture();
+ const detected = await detectHostCheckRoot(path.join(host, 'vendor/library'));
+ expect(detected && (await realpath(detected))).toBe(await realpath(host));
+ });
+
+ it('delegates a submodule in a linked host worktree to that worktree', async () => {
+ const { host } = await createFixture();
+ const selected = path.join(fixtureRoot!, 'selected');
+ await git(host, 'worktree', 'add', '-b', 'feature/selected', selected);
+ await git(selected, '-c', 'protocol.file.allow=always', 'submodule', 'update', '--init');
+
+ const detected = await detectHostCheckRoot(path.join(selected, 'vendor/library'));
+ expect(detected && (await realpath(detected))).toBe(await realpath(selected));
+ });
+
+ it('does not delegate a standalone worktree of a submodule to its old host', async () => {
+ const { host } = await createFixture();
+ const standalone = path.join(fixtureRoot!, 'standalone');
+ await git(
+ path.join(host, 'vendor/library'),
+ 'worktree',
+ 'add',
+ '-b',
+ 'feature/library',
+ standalone,
+ );
+
+ expect(await detectHostCheckRoot(standalone)).toBeNull();
+ });
+
+ it('does not delegate a nested repository that is not a submodule', async () => {
+ const { host } = await createFixture();
+ const nested = path.join(host, 'scratch');
+ await git(host, 'init', '-b', 'main', nested);
+
+ expect(await detectHostCheckRoot(nested)).toBeNull();
+ });
+
+ it('delegates an independent clone mounted at a tracked submodule path', async () => {
+ const { host, library } = await createFixture();
+ const mounted = path.join(host, 'vendor/library');
+ await rm(mounted, { force: true, recursive: true });
+ await git(host, 'clone', library, mounted);
+
+ const detected = await detectHostCheckRoot(mounted);
+ expect(detected && (await realpath(detected))).toBe(await realpath(host));
+ });
+
+ it.each(['--lint', '--type'])(
+ 'rejects a foreign host entry before running %s',
+ async (selector) => {
+ const { host } = await createFixture();
+ const selected = path.join(fixtureRoot!, 'selected');
+ await git(host, 'worktree', 'add', '-b', 'feature/selected', selected);
+ await writeFile(path.join(host, 'anchor.txt'), 'anchor draft\n');
+ await writeFile(path.join(selected, 'selected.txt'), 'selected draft\n');
+ const formatter = path.join(host, 'node_modules/.bin/fixture-format');
+ await mkdir(path.dirname(formatter), { recursive: true });
+ await writeFile(
+ formatter,
+ '#!/usr/bin/env bun\nawait Bun.write(process.argv.at(-1), "formatted wrong checkout\\n");\n',
+ );
+ await chmod(formatter, 0o755);
+ const entry = path.join(fixtureRoot!, 'entry.ts');
+ await writeFile(
+ entry,
+ `import { runCli } from ${JSON.stringify(enginePath)};\n` +
+ `await runCli(${JSON.stringify({
+ repos: [{ dir: '', pipelines: [{ exts: ['.txt'], tools: [['fixture-format']] }] }],
+ rootDir: host,
+ })});\n`,
+ );
+
+ const result = await run('bun', ['run', entry, selector], selected);
+
+ expect(result.code).not.toBe(0);
+ expect(result.stderr).toContain('checkout');
+ expect(result.stderr).not.toContain('Error:');
+ expect(result.stdout).not.toContain('HOST_CHECK');
+ expect(await readFile(path.join(host, 'anchor.txt'), 'utf8')).toBe('anchor draft\n');
+ expect(await readFile(path.join(selected, 'selected.txt'), 'utf8')).toBe('selected draft\n');
+ },
+ );
+
+ it('accepts a host entry invoked from one of its mounted repositories', async () => {
+ const { host } = await createFixture();
+ const entry = path.join(fixtureRoot!, 'entry.ts');
+ await writeFile(
+ entry,
+ `import { runCli } from ${JSON.stringify(enginePath)};\n` +
+ `await runCli(${JSON.stringify({
+ repos: [
+ { dir: '', pipelines: [] },
+ { dir: 'vendor/library', pipelines: [] },
+ ],
+ rootDir: host,
+ })});\n`,
+ );
+
+ const result = await run('bun', ['run', entry, '--test'], path.join(host, 'vendor/library'));
+
+ expect(result.code, result.stderr).toBe(0);
+ expect(result.stdout).toContain('nothing to check');
+ });
+
+ it('rejects a foreign standalone entry before delegating or collecting files', async () => {
+ const { host, library } = await createFixture();
+ const copiedScripts = path.join(host, 'vendor/library/.agents/scripts/check');
+ await cp(path.dirname(cliPath), copiedScripts, {
+ filter: (source) => !source.endsWith('.test.ts'),
+ recursive: true,
+ });
+ const result = await run('bun', ['run', path.join(copiedScripts, 'cli.ts'), '--test'], library);
+
+ expect(result.code).not.toBe(0);
+ expect(result.stderr).toContain('checkout');
+ expect(result.stderr).not.toContain('crashed');
+ expect(result.stdout).not.toContain('delegating');
+ });
+});
diff --git a/.agents/scripts/check/delegate.ts b/.agents/scripts/check/delegate.ts
index f3ec443357b..861c77da374 100644
--- a/.agents/scripts/check/delegate.ts
+++ b/.agents/scripts/check/delegate.ts
@@ -1,40 +1,21 @@
-import { readFile, stat } from 'node:fs/promises';
+import { readFile, realpath } from 'node:fs/promises';
import path from 'node:path';
-/**
- * Derive the superproject root from a submodule's resolved gitdir: a
- * submodule checkout stores its git data under the host's
- * `<hostRoot>/.git/modules/<name>`. Returns null for anything else (a
- * standalone clone has a `.git` directory, a linked worktree points into
- * `.git/worktrees`).
- */
-export const hostRootFromGitdir = (gitdir: string): string | null => {
- const marker = `${path.sep}.git${path.sep}modules${path.sep}`;
- const index = gitdir.lastIndexOf(marker);
- return index === -1 ? null : gitdir.slice(0, index);
-};
+import { run } from './exec';
+import { exists } from './paths';
/**
* When this repo is mounted as a git submodule of a superproject that ships
* its own `check` script, return that superproject's root so the standalone
* entry can delegate โ€” the host entry routes this repo's files through the
* same engine with the host's full config, so both entries behave
- * identically no matter where they are invoked from.
+ * identically no matter where they are invoked from. Ask Git about the
+ * containing checkout: shared git metadata may belong to another worktree.
*/
export const detectHostCheckRoot = async (repoRoot: string): Promise<string | null> => {
- const gitPath = path.join(repoRoot, '.git');
- let content: string;
- try {
- if ((await stat(gitPath)).isDirectory()) return null;
- content = await readFile(gitPath, 'utf8');
- } catch {
- return null;
- }
-
- // The gitfile format is exactly `gitdir: <path>` (git's repository-layout docs)
- const match = content.match(/^gitdir: ?(.+)$/m);
- if (!match) return null;
- const hostRoot = hostRootFromGitdir(path.resolve(repoRoot, match[1].trim()));
+ const result = await run('git', ['rev-parse', '--show-superproject-working-tree'], repoRoot);
+ if (result.code !== 0) return null;
+ const hostRoot = result.stdout.trim();
if (!hostRoot) return null;
try {
@@ -46,3 +27,29 @@ export const detectHostCheckRoot = async (repoRoot: string): Promise<string | nu
return null;
}
};
+
+/**
+ * A check entry owns its checkout's configuration and tool versions. Refuse
+ * a foreign entry before autofix or type-check can target another worktree;
+ * an explicitly mounted repository within the same host remains valid.
+ * A wrong checkout is a CLI usage error, so exit without a crash stack.
+ */
+export const assertCheckRoot = async (rootDir: string, mountedDirs: string[] = []) => {
+ const result = await run('git', ['rev-parse', '--show-toplevel'], process.cwd());
+ if (result.code !== 0) {
+ console.error('โœ— Run `bun run check` from the target Git checkout.');
+ process.exit(2);
+ }
+
+ const currentRoot = await realpath(result.stdout.trim());
+ for (const dir of ['', ...mountedDirs]) {
+ const allowedRoot = path.resolve(rootDir, dir);
+ if ((await exists(allowedRoot)) && (await realpath(allowedRoot)) === currentRoot) return;
+ }
+
+ console.error(
+ `โœ— This check entry belongs to ${rootDir}, but the current checkout is ${currentRoot}. ` +
+ "Run `bun run check` using the target checkout's own entrypoint.",
+ );
+ process.exit(2);
+};
diff --git a/.agents/scripts/check/index.ts b/.agents/scripts/check/index.ts
index c7b7401a588..39195535b8b 100644
--- a/.agents/scripts/check/index.ts
+++ b/.agents/scripts/check/index.ts
@@ -22,6 +22,7 @@
import { findNewComponentTestAdvisories } from './advisories';
import { collectAutofixDiffs, snapshot, writeFullDiff } from './autofix';
import { collectFromGit, normalizeArgs } from './collect';
+import { assertCheckRoot } from './delegate';
import { run } from './exec';
import { lintGroup } from './lint';
import { existsInRepo, setConfig } from './paths';
@@ -60,6 +61,11 @@ export const runCli = async (config: CheckConfig) => {
process.exit(2);
}
+ await assertCheckRoot(
+ config.rootDir,
+ config.repos.map((repo) => repo.dir),
+ );
+
const wantLint = rawArgs.includes('--lint');
const wantTest = rawArgs.includes('--test');
const runType = rawArgs.includes('--type');
diff --git a/.agents/skills/agent-runtime-hooks/SKILL.md b/.agents/skills/agent-runtime-hooks/SKILL.md
index 59dcc25d3fb..20f6070727b 100644
--- a/.agents/skills/agent-runtime-hooks/SKILL.md
+++ b/.agents/skills/agent-runtime-hooks/SKILL.md
@@ -1,6 +1,6 @@
---
name: agent-runtime-hooks
-description: 'Agent runtime lifecycle hooks. Use for before/after tool or step hooks, tool mocks, human intervention, sub-agent calls, context compression, evals, callAgent, or lifecycle events.'
+description: 'Use for agent lifecycle hooks, tool mocks, intervention, sub-agent calls and context compression.'
user-invocable: false
---
diff --git a/.agents/skills/agent-signal/SKILL.md b/.agents/skills/agent-signal/SKILL.md
index f09c8347e63..2c18d2262cc 100644
--- a/.agents/skills/agent-signal/SKILL.md
+++ b/.agents/skills/agent-signal/SKILL.md
@@ -1,6 +1,6 @@
---
name: agent-signal
-description: 'Build or extend LobeHub Agent Signal pipelines. Use for signal sources, signal/action types, policies, middleware, workflow handoff, dedupe, scope behavior, or observability.'
+description: 'Use for Agent Signal sources, actions, policies, middleware, workflow handoff and deduplication.'
---
# Agent Signal
diff --git a/.agents/skills/agent-testing-bot/SKILL.md b/.agents/skills/agent-testing-bot/SKILL.md
index 0bac71cc05d..2f681116188 100644
--- a/.agents/skills/agent-testing-bot/SKILL.md
+++ b/.agents/skills/agent-testing-bot/SKILL.md
@@ -1,12 +1,6 @@
---
name: agent-testing-bot
-description: >
- Bot-channel end-to-end verification for LobeHub โ€” drives the real native chat
- apps (Discord / Slack / Telegram / WeChat / Lark / QQ / iMessage) via osascript
- or the iMessage bridge, on macOS. Extends the generic acceptance skill for
- bot surfaces. Triggers on 'test bot', 'bot test', 'test in discord',
- 'test in telegram', 'test in slack', 'test in wechat', 'test in weixin',
- 'test in lark', 'test in feishu', 'test in qq'.
+description: 'Use for real bot-channel acceptance in Discord, Slack, Telegram, WeChat/Weixin, Lark/Feishu, QQ or iMessage on macOS. Extends acceptance with native chat apps.'
---
# Agent Testing โ€” Bot Channels (LobeHub project skill)
diff --git a/.agents/skills/agent-tracing/SKILL.md b/.agents/skills/agent-tracing/SKILL.md
index 01764d6e275..41bbe421af3 100644
--- a/.agents/skills/agent-tracing/SKILL.md
+++ b/.agents/skills/agent-tracing/SKILL.md
@@ -1,6 +1,6 @@
---
name: agent-tracing
-description: 'Agent tracing CLI for execution snapshots. Use for agent-tracing, traces, snapshots, LLM call inspection, context engine data, agent step analysis, execution debugging, or pulling remote/production traces ("ๆ‹‰็บฟไธŠ tracing") by operation id. Also the first stop for debugging agent tool calls โ€” wrong or missing tool_calls, unexpected tool arguments or results, which tools were available at a step, or why a tool ran where it did.'
+description: 'Use for agent traces by operation ID (ๆ‹‰็บฟไธŠ tracing): failed tools, arguments/results, available tools, execution location, LLM calls and context.'
user-invocable: false
---
diff --git a/.agents/skills/agent-work/SKILL.md b/.agents/skills/agent-work/SKILL.md
index e240a6194b5..bc45de6485c 100644
--- a/.agents/skills/agent-work/SKILL.md
+++ b/.agents/skills/agent-work/SKILL.md
@@ -1,6 +1,6 @@
---
name: agent-work
-description: 'Agent Work registry (works / work_versions): how agent outputs โ€” github/linear entities, files, documents, tasks โ€” get registered, deduped, and rendered as cards, and how to extend it with a new skill provider, a new shell CLI scanner, or a new Work type.'
+description: 'Use for the Agent Work output registry: registration, deduplication, cards, skill providers, CLI scanners and Work types.'
user-invocable: false
---
diff --git a/.agents/skills/builtin-tool/SKILL.md b/.agents/skills/builtin-tool/SKILL.md
index 8978f0409bc..73f95247d4f 100644
--- a/.agents/skills/builtin-tool/SKILL.md
+++ b/.agents/skills/builtin-tool/SKILL.md
@@ -1,6 +1,6 @@
---
name: builtin-tool
-description: 'Build LobeHub builtin tool packages. Use when adding agent-callable tools, manifests, executors, runtimes, inspectors, renders, placeholders, streaming, interventions, portals, or tool registries.'
+description: 'Use for LobeHub builtin agent tools: manifests, executors, runtimes, inspectors, renders, streaming and intervention.'
---
# Builtin Tool Authoring Guide
diff --git a/.agents/skills/chat-sdk/SKILL.md b/.agents/skills/chat-sdk/SKILL.md
index 889b693bf02..55092526567 100644
--- a/.agents/skills/chat-sdk/SKILL.md
+++ b/.agents/skills/chat-sdk/SKILL.md
@@ -1,6 +1,6 @@
---
name: chat-sdk
-description: 'Build multi-platform chat bots with the chat SDK. Use for Slack, Teams, Google Chat, Discord, GitHub, Linear bots, webhooks, mentions, slash commands, cards, modals, or streaming responses.'
+description: 'Use for multi-platform bots built with chat SDK: webhooks, mentions, slash commands, cards, modals and streaming.'
user-invocable: false
---
diff --git a/.agents/skills/cleanup-git-worktrees/SKILL.md b/.agents/skills/cleanup-git-worktrees/SKILL.md
index 6d086bddb68..851032ac4fb 100644
--- a/.agents/skills/cleanup-git-worktrees/SKILL.md
+++ b/.agents/skills/cleanup-git-worktrees/SKILL.md
@@ -1,6 +1,6 @@
---
name: cleanup-git-worktrees
-description: Audit and safely clean Git worktrees and stale local branches. Use when asked to list worktrees, identify completed or merged branches, remove worktrees whose remote branches are gone, prune stale worktree registrations, or clean local branches without losing uncommitted work.
+description: 'Use for stale-worktree, Git registration and branch audits. Managed removal uses the repo lifecycle.'
---
# Cleanup Git Worktrees
@@ -29,7 +29,10 @@ Use the bundled script to make classification deterministic. Treat cleanup as a
3. Present a compact table containing path, branch, dirty count, upstream state, base containment, and classification. Keep `candidate-merged` separate from `candidate-gone`; do not describe `[gone]` as proof of merge.
-4. After approval, pass exact branch names to cleanup:
+4. After approval, use the repository's worktree lifecycle workflow when it manages
+ services or other resources alongside a checkout. The Git-only cleanup script
+ does not tear those resources down. For plain Git worktrees, pass exact branch
+ names to cleanup:
```bash
bash .agents/skills/cleanup-git-worktrees/scripts/cleanup.sh clean \
diff --git a/.agents/skills/compose-atoms/SKILL.md b/.agents/skills/compose-atoms/SKILL.md
index 762de0abae5..d17d9e323c1 100644
--- a/.agents/skills/compose-atoms/SKILL.md
+++ b/.agents/skills/compose-atoms/SKILL.md
@@ -1,6 +1,6 @@
---
name: compose-atoms
-description: 'Decompose a heavy domain feature into mountable capability atoms. Use when a Viewer/Page/index.tsx owns fetch, filters, mutations, modals, and host integrations together; a visual split still leaves store calls and actions on the page; a portal, embed, share, mobile, or micro-app needs a subset of the same domain; or a new capability is landing as another `readOnly`/`mode`/`variant` flag. Triggers on `compose-atoms`, sink state, ็Šถๆ€ไธ‹ๆฒ‰, ้‡ไธšๅŠกๆ‹†ๅˆ†, ๆ‹†ๆˆๅŽŸๅญ, ๅŽŸๅญ็ป„ไปถ, ็ป„่ฃ…, god component, fat viewer, module graph, slot composition, host seam.'
+description: 'Use for splitting heavy domains into capabilities (ๅŽŸๅญ็ป„ไปถ) across page, portal, share or micro-app hosts, sinking state (็Šถๆ€ไธ‹ๆฒ‰) and replacing mode/readOnly flags. Simple component splits: react.'
user-invocable: false
---
diff --git a/.agents/skills/data-fetching-architecture/SKILL.md b/.agents/skills/data-fetching-architecture/SKILL.md
index 81a16821456..3fd57977eb8 100644
--- a/.agents/skills/data-fetching-architecture/SKILL.md
+++ b/.agents/skills/data-fetching-architecture/SKILL.md
@@ -1,58 +1,29 @@
---
name: data-fetching-architecture
-description: 'LobeHub data-fetching pipeline guide. Use for service layer, Zustand store, SWR, lambdaClient, useClientDataSWR, useFetchXxx hooks, home first-paint flicker, persistent display caches, or migrating useEffect fetches.'
+description: 'Use for client APIs, SWR hooks, cache invalidation, async errors, useEffect migration, home first paint and persistent caches.'
user-invocable: false
---
# LobeHub Data Fetching Architecture
-> **Related:** `store-data-structures` covers List vs Detail data shape rationale (Map vs Array).
-
-## Architecture Overview
-
```text
-โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
-โ”‚ Component โ”‚
-โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”˜
- โ”‚ 1. Call useFetchXxx hook from store
- โ†“
-โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
-โ”‚ Zustand Store โ”‚
-โ”‚ (State + Hook) โ”‚
-โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
- โ”‚ 2. useClientDataSWR calls service
- โ†“
-โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
-โ”‚ Service Layer โ”‚
-โ”‚ (xxxService) โ”‚
-โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
- โ”‚ 3. Call lambdaClient
- โ†“
-โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
-โ”‚ lambdaClient โ”‚
-โ”‚ (TRPC Client) โ”‚
-โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
+Component โ†’ Store useFetchXxx hook โ†’ Service โ†’ lambdaClient
+ โ† SWR request state + store data โ† response
```
-## Core Principles
-
-### โœ… DO
+## Layer boundaries
-1. **Use Service Layer** for all API calls
-2. **Use Store SWR Hooks** for data fetching (not useEffect)
-3. **Use proper data structures** โ€” see `store-data-structures` skill for List vs Detail patterns
-4. **Use lambdaClient.mutate** for write operations (create/update/delete)
-5. **Use lambdaClient.query** only inside service methods
-6. **Naming convention** โ€” read hooks are `useFetchXxx`, cache invalidation helpers are `refreshXxx` (e.g. `useFetchBenchmarks` / `refreshBenchmarks`). Mutations then chain `refreshXxx()` after the service call.
-
-### โŒ DON'T
-
-1. **Never use useEffect** for data fetching
-2. **Never call lambdaClient** directly in components or stores
-3. **Never use useState** for server data
-4. **Never mix data structure patterns** โ€” follow `store-data-structures` skill
-
----
+- Services in `src/services/` own API calls: `.query()` for reads, `.mutate()` for writes.
+ Export a service instance per domain; components and stores do not call `lambdaClient` directly.
+- Store read hooks use `useClientDataSWR` and return its SWR response, including `error`
+ and `mutate`. Sync successful results into the store through the wrapper's supported
+ callback (`onSuccess`, or `onData` for the sync wrapper).
+- Components call these hooks and read store data through selectors. Do not fetch in
+ `useEffect` or duplicate server data in component `useState`.
+- Use `useFetchXxx` for read hooks and `refreshXxx` for cache invalidation.
+- For list/detail types, maps, reducers, and shared type sources, use
+ [Zustand data structures](../zustand/references/data-structures.md). For action classes,
+ internal actions, and `flattenActions`, use [zustand](../zustand/SKILL.md).
## Home First Paint and Persistent Caches
@@ -60,611 +31,112 @@ When changing home/sidebar first paint or persisted display data, read
[`references/home-first-paint.md`](./references/home-first-paint.md). It covers
avoiding flicker, reusing persistence, and the user `displaySnapshot.ts` boundary.
-## Layer 1: Service Layer
-
-### Purpose
-
-- Encapsulate all API calls to lambdaClient
-- Provide clean, typed interfaces
-- Single source of truth for API operations
-
-### Service Structure
-
-```typescript
-// src/services/agentEval.ts
-class AgentEvalService {
- // Query methods - READ operations
- async listBenchmarks() {
- return lambdaClient.agentEval.listBenchmarks.query();
- }
-
- async getBenchmark(id: string) {
- return lambdaClient.agentEval.getBenchmark.query({ id });
- }
-
- // Mutation methods - WRITE operations
- async createBenchmark(params: CreateBenchmarkParams) {
- return lambdaClient.agentEval.createBenchmark.mutate(params);
- }
-
- async updateBenchmark(params: UpdateBenchmarkParams) {
- return lambdaClient.agentEval.updateBenchmark.mutate(params);
- }
-
- async deleteBenchmark(id: string) {
- return lambdaClient.agentEval.deleteBenchmark.mutate({ id });
- }
-}
-
-export const agentEvalService = new AgentEvalService();
-```
-
-### Service Guidelines
-
-1. **One service per domain** (e.g., agentEval, ragEval, aiAgent)
-2. **Export singleton instance** (`export const xxxService = new XxxService()`)
-3. **Method names match operations** (list, get, create, update, delete)
-4. **Clear parameter types** (use interfaces for complex params)
-
----
-
-## Layer 2: Store with SWR Hooks
+## Cache keys and refresh
-### Purpose
+Reuse the domain key factory in `src/libs/swr/keys.ts`; define a shared key if the
+domain has none. Include every parameter that changes the response: entity or parent
+id, filters, sort, and pagination. Read and refresh must construct the same key.
-- Manage client-side state
-- Provide SWR hooks for data fetching
-- Handle cache invalidation
+Import `useClientDataSWR` and `mutate` from `@/libs/swr`, keeping the application's
+workspace/cache handling. Return a `null` key when a required id is absent; passing
+`undefined` to a store hook only disables fetching if that hook maps it to `null`.
-### State Structure
+For example, inside an action class:
```typescript
-// src/store/eval/slices/benchmark/initialState.ts
-export interface BenchmarkSliceState {
- // List data - simple array
- benchmarkList: AgentEvalBenchmarkListItem[];
- benchmarkListInit: boolean;
-
- // Detail data - map for caching
- benchmarkDetailMap: Record<string, AgentEvalBenchmark>;
- loadingBenchmarkDetailIds: string[];
-
- // Mutation states
- isCreatingBenchmark: boolean;
- isUpdatingBenchmark: boolean;
- isDeletingBenchmark: boolean;
-}
-```
-
-> For complete initialState, reducer, and internal dispatch patterns, see the `store-data-structures` skill.
-
-### Actions
-
-```typescript
-// src/store/eval/slices/benchmark/action.ts
-const FETCH_BENCHMARKS_KEY = 'FETCH_BENCHMARKS';
-const FETCH_BENCHMARK_DETAIL_KEY = 'FETCH_BENCHMARK_DETAIL';
-
-export interface BenchmarkAction {
- // SWR Hooks - for data fetching
- useFetchBenchmarks: () => SWRResponse;
- useFetchBenchmarkDetail: (id?: string) => SWRResponse;
-
- // Refresh methods - for cache invalidation
- refreshBenchmarks: () => Promise<void>;
- refreshBenchmarkDetail: (id: string) => Promise<void>;
-
- // Mutation actions
- createBenchmark: (params: CreateParams) => Promise<any>;
- updateBenchmark: (params: UpdateParams) => Promise<void>;
- deleteBenchmark: (id: string) => Promise<void>;
-
- // Internal methods - not for direct UI use
- internal_dispatchBenchmarkDetail: (payload: BenchmarkDetailDispatch) => void;
- internal_updateBenchmarkDetailLoading: (id: string, loading: boolean) => void;
-}
-
-export const createBenchmarkSlice: StateCreator<EvalStore, any, [], BenchmarkAction> = (
- set,
- get,
-) => ({
- // Fetch list โ€” simple array stored in benchmarkList
- useFetchBenchmarks: () =>
- useClientDataSWR(FETCH_BENCHMARKS_KEY, () => agentEvalService.listBenchmarks(), {
- onSuccess: (data) => {
- set({ benchmarkList: data, benchmarkListInit: true }, false, 'useFetchBenchmarks/success');
- },
- }),
-
- // Fetch detail โ€” null key disables the request when id is missing
- useFetchBenchmarkDetail: (id) =>
- useClientDataSWR(
- id ? [FETCH_BENCHMARK_DETAIL_KEY, id] : null,
- () => agentEvalService.getBenchmark(id!),
- {
- onSuccess: (data) => {
- get().internal_dispatchBenchmarkDetail({
- type: 'setBenchmarkDetail',
- id: id!,
- value: data,
- });
- get().internal_updateBenchmarkDetailLoading(id!, false);
- },
- },
- ),
-
- // Refresh methods
- refreshBenchmarks: () => mutate(FETCH_BENCHMARKS_KEY),
- refreshBenchmarkDetail: (id) => mutate([FETCH_BENCHMARK_DETAIL_KEY, id]),
-
- // CREATE โ€” refresh list after creation
- createBenchmark: async (params) => {
- set({ isCreatingBenchmark: true }, false, 'createBenchmark/start');
- try {
- const result = await agentEvalService.createBenchmark(params);
- await get().refreshBenchmarks();
- return result;
- } finally {
- set({ isCreatingBenchmark: false }, false, 'createBenchmark/end');
- }
- },
-
- // UPDATE โ€” optimistic update + refresh
- updateBenchmark: async (params) => {
- const { id } = params;
-
- // 1. Optimistic update
- get().internal_dispatchBenchmarkDetail({
- type: 'updateBenchmarkDetail',
- id,
- value: params,
- });
- // 2. Set loading
- get().internal_updateBenchmarkDetailLoading(id, true);
-
- try {
- // 3. Call service
- await agentEvalService.updateBenchmark(params);
- // 4. Refresh from server
- await get().refreshBenchmarks();
- await get().refreshBenchmarkDetail(id);
- } finally {
- get().internal_updateBenchmarkDetailLoading(id, false);
- }
- },
-
- // DELETE โ€” optimistic update + refresh
- deleteBenchmark: async (id) => {
- get().internal_dispatchBenchmarkDetail({ type: 'deleteBenchmarkDetail', id });
- get().internal_updateBenchmarkDetailLoading(id, true);
-
- try {
- await agentEvalService.deleteBenchmark(id);
- await get().refreshBenchmarks();
- } finally {
- get().internal_updateBenchmarkDetailLoading(id, false);
- }
- },
-
- // Internal โ€” dispatch to reducer (for detail map)
- internal_dispatchBenchmarkDetail: (payload) => {
- const currentMap = get().benchmarkDetailMap;
- const nextMap = benchmarkDetailReducer(currentMap, payload);
-
- // Skip set when nothing changed โ€” avoids unnecessary re-renders
- if (isEqual(nextMap, currentMap)) return;
- set({ benchmarkDetailMap: nextMap }, false, `dispatchBenchmarkDetail/${payload.type}`);
- },
+useFetchBenchmarks = () =>
+ useClientDataSWR(evalKeys.benchmarks(), () => agentEvalService.listBenchmarks(), {
+ onSuccess: (data) => {
+ this.#set({ benchmarkList: data, benchmarkListInit: true });
+ },
+ });
- // Internal โ€” update loading state for specific detail
- internal_updateBenchmarkDetailLoading: (id, loading) => {
- set(
- (state) => ({
- loadingBenchmarkDetailIds: loading
- ? [...state.loadingBenchmarkDetailIds, id]
- : state.loadingBenchmarkDetailIds.filter((i) => i !== id),
- }),
- false,
- 'updateBenchmarkDetailLoading',
- );
- },
-});
+refreshBenchmarks = async () => {
+ await mutate(evalKeys.benchmarks());
+};
```
-### Store Guidelines
-
-1. **SWR keys as constants** at top of file
-2. **useClientDataSWR** for all data fetching (never useEffect)
-3. **onSuccess/onData callback** updates store state
-4. **Refresh methods** use `mutate()` to invalidate cache
-5. **Loading states** in initialState, updated in onSuccess/onData
-6. **Mutations** call service, then refresh relevant cache
-
----
+Read the current [benchmark action](../../../src/store/eval/slices/benchmark/action.ts)
+for store wiring and the [SWR wrappers](../../../src/libs/swr/index.ts) for their
+actual options. These links locate implementation; they do not make every existing
+call site a template to copy unchanged.
-## Async Failure Boundary Contract
+Hooks that share a known parent id can run together. If one request needs a value
+returned by another, keep its key `null` until that value exists. Do not assume the
+application wrapper uses upstream SWR's default deduplication interval.
-Every read hook returns an SWR response that includes `error` and `mutate`; the surface must
-consume them. A success-only init flag (`!isInit`, `!map[id]`, `data ?? []`) is not enough:
-when the request fails, that flag often never flips, so the UI paints a permanent skeleton,
-a fake empty state, a false `NotFound`, or a confident zero-value metric.
-
-Use the shared UI primitives:
-
-- `AsyncBoundary` for normal loading / error / empty / data surfaces.
-- `AsyncError` for custom layouts, detail pages, inline load-more failures, or metrics.
-
-Core precedence for first-load failures:
-
-```tsx
-const { data, error, isLoading, mutate } = useFetchXxx();
+For lists cached separately under multiple parents, see
+[parent-keyed lists](references/walkthrough.md). Ordinary flat lists need no extra layer.
-return (
- <AsyncBoundary
- data={data}
- empty={<EmptyState />}
- error={error}
- isEmpty={!error && data?.length === 0}
- isLoading={isLoading}
- onRetry={() => {
- void mutate();
- }}
- >
- <List items={data ?? []} />
- </AsyncBoundary>
-);
-```
+## Mutations
-Rules:
+- Call the service, then refresh affected list/detail keys and any related domain
+ whose response changed. Await refresh when subsequent UI behavior depends on it.
+- Keep pending flags in store state and clear them in `finally`. Use per-id state for
+ row updates/deletes so unrelated rows remain usable; create can use a separate flag
+ because no persistent id exists yet.
+- For optimistic create/update, use the store's reducer/dispatch convention and
+ restore or revalidate affected state if the service fails. Do not leave a temporary
+ row or a successful-looking edit after rejection.
+- Delete after server success, following the `zustand` convention. Do not remove the
+ row optimistically or apply create/update's optimistic recipe to deletion.
+- Let failures reach the caller's error UI; a `finally` block clears pending state
+ but does not by itself recover an optimistic write.
-- Check `error` before empty / `NotFound` / zero defaults. Error is not a kind of empty.
-- Keep already-loaded content on background revalidation failures; only replace the surface
- when there is no settled data to preserve.
-- For detail maps, don't put the error branch after `if (!map[id]) return <Skeleton/>`.
- First-load failures never populate the map, making that error branch unreachable.
-- For infinite scroll / load-more, persist a per-bucket `loadMoreError` and render an
- inline Retry row. Do not let an `IntersectionObserver` silently retry while the error is
- still unresolved.
-- For merged fetched + static lists, branch on the fetched slice's `error` before merging.
- Static fallback rows can make a failed fetch look like a plausible partial catalog.
+## Render loading, errors, and settled data
-## Layer 3: Component Usage
+Consume the read hook's SWR response. Success-only flags such as `isInit`, missing
+map entries, and `data ?? []` cannot distinguish an initial request failure from
+loading or empty results.
-### Fetching List Data
+Use `AsyncBoundary` for standard loading/error/empty/data surfaces; use `AsyncError`
+for custom layouts and inline failures. Pass the original SWR `data` to the boundary:
+`undefined` means no successful result, whereas `[]` is a settled empty result.
```tsx
-// โœ… CORRECT
const BenchmarkList = () => {
- // 1. Get the hook from store
const useFetchBenchmarks = useEvalStore((s) => s.useFetchBenchmarks);
-
- // 2. Get list data
const benchmarks = useEvalStore((s) => s.benchmarkList);
- const isInit = useEvalStore((s) => s.benchmarkListInit);
-
- // 3. Call the hook (SWR handles the data fetching)
- useFetchBenchmarks();
-
- // 4. Use the data
- if (!isInit) return <Loading />;
- return (
- <div>
- <h2>Total: {benchmarks.length}</h2>
- {benchmarks.map((b) => (
- <BenchmarkCard key={b.id} {...b} />
- ))}
- </div>
- );
-};
-```
-
-### Fetching Detail Data
-
-```tsx
-// โœ… CORRECT
-const BenchmarkDetail = () => {
- const { benchmarkId } = useParams<{ benchmarkId: string }>();
-
- const useFetchBenchmarkDetail = useEvalStore((s) => s.useFetchBenchmarkDetail);
-
- // Detail from map
- const benchmark = useEvalStore((s) =>
- benchmarkId ? s.benchmarkDetailMap[benchmarkId] : undefined,
- );
-
- // Per-item loading
- const isLoading = useEvalStore((s) =>
- benchmarkId ? s.loadingBenchmarkDetailIds.includes(benchmarkId) : false,
- );
-
- useFetchBenchmarkDetail(benchmarkId);
-
- if (!benchmark) return <Loading />;
- return (
- <div>
- <h1>{benchmark.name}</h1>
- <p>{benchmark.description}</p>
- {isLoading && <Spinner />}
- </div>
- );
-};
-```
-
-### Using Selectors (Recommended)
-
-```typescript
-// src/store/eval/slices/benchmark/selectors.ts
-export const benchmarkSelectors = {
- getBenchmarkDetail: (id: string) => (s: EvalStore) => s.benchmarkDetailMap[id],
- isLoadingBenchmarkDetail: (id: string) => (s: EvalStore) =>
- s.loadingBenchmarkDetailIds.includes(id),
-};
-
-// Component with selectors
-const BenchmarkDetail = () => {
- const { benchmarkId } = useParams();
- const useFetchBenchmarkDetail = useEvalStore((s) => s.useFetchBenchmarkDetail);
- const benchmark = useEvalStore(benchmarkSelectors.getBenchmarkDetail(benchmarkId!));
-
- useFetchBenchmarkDetail(benchmarkId);
-
- return <div>{benchmark && <h1>{benchmark.name}</h1>}</div>;
-};
-```
-
-### Anti-pattern
-
-```tsx
-// โŒ WRONG โ€” Don't use useEffect for data fetching
-const BenchmarkList = () => {
- const [data, setData] = useState([]);
- const [loading, setLoading] = useState(false);
-
- useEffect(() => {
- setLoading(true);
- lambdaClient.agentEval.listBenchmarks
- .query()
- .then(setData)
- .finally(() => setLoading(false));
- }, []);
-
- return <div>...</div>;
-};
-```
-
-### Mutations in Components
-
-```tsx
-// Create โ€” global mutation flag drives form loading
-const CreateBenchmarkModal = () => {
- const createBenchmark = useEvalStore((s) => s.createBenchmark);
- const isCreating = useEvalStore((s) => s.isCreatingBenchmark);
-
- const handleSubmit = async (values) => {
- try {
- // Optimistic update + refresh happen inside createBenchmark
- await createBenchmark(values);
- message.success('Created successfully');
- onClose();
- } catch (error) {
- message.error('Failed to create');
- }
- };
+ const { data, error, isLoading, mutate } = useFetchBenchmarks();
return (
- <Form onSubmit={handleSubmit} loading={isCreating}>
- ...
- </Form>
- );
-};
-
-// Update / delete โ€” per-item loading so only the row being mutated spins
-const BenchmarkItem = ({ id }: { id: string }) => {
- const updateBenchmark = useEvalStore((s) => s.updateBenchmark);
- const deleteBenchmark = useEvalStore((s) => s.deleteBenchmark);
- const isLoading = useEvalStore(benchmarkSelectors.isLoadingBenchmarkDetail(id));
-
- const handleUpdate = async (data) => {
- await updateBenchmark({ id, ...data });
- };
-
- const handleDelete = async () => {
- await deleteBenchmark(id);
- };
-
- return (
- <div>
- {isLoading && <Spinner />}
- <button onClick={handleUpdate}>Update</button>
- <button onClick={handleDelete}>Delete</button>
- </div>
- );
-};
-```
-
-**Why two patterns:** create has no id yet, so a single `isCreatingXxx` flag is enough. Update/delete target a specific row, so global flags would freeze unrelated rows โ€” keep per-item state in `loadingXxxIds`.
-
----
-
-## Need a fuller worked example?
-
-The canonical `Benchmark` example above is the one to copy for a flat list + detail map. If you need to maintain a list **keyed by a parent id** (e.g. `datasetMap[benchmarkId]` because the same shape appears under multiple parents), read [`references/walkthrough.md`](./references/walkthrough.md) โ€” it walks through the full 6 steps (service โ†’ reducer โ†’ slice โ†’ store wiring โ†’ selectors โ†’ component) for that variant.
-
----
-
-## Common Patterns
-
-### Pattern 1: Pagination
-
-Cache key array must include every parameter that should trigger a refetch.
-
-```typescript
-useFetchTestCases: (params: { datasetId: string; limit: number; offset: number }) =>
- useClientDataSWR(
- params.datasetId ? [FETCH_TEST_CASES_KEY, params.datasetId, params.limit, params.offset] : null,
- () => agentEvalService.listTestCases(params),
- {
- onSuccess: (data) =>
- set({
- testCaseList: data.data,
- testCaseTotal: data.total,
- isLoadingTestCases: false,
- }),
- },
+ <AsyncBoundary
+ data={data}
+ empty={<EmptyState />}
+ error={error}
+ isEmpty={data?.length === 0}
+ isLoading={isLoading}
+ onRetry={() => {
+ void mutate();
+ }}
+ >
+ <BenchmarkCards items={benchmarks} />
+ </AsyncBoundary>
);
-```
-
-### Pattern 2: Dependent Fetching
-
-Both hooks run in parallel โ€” SWR dedupes, no manual sequencing needed.
-
-```tsx
-const BenchmarkDetail = () => {
- const { benchmarkId } = useParams();
- const useFetchBenchmarkDetail = useEvalStore((s) => s.useFetchBenchmarkDetail);
- const useFetchDatasets = useEvalStore((s) => s.useFetchDatasets);
-
- useFetchBenchmarkDetail(benchmarkId);
- useFetchDatasets(benchmarkId);
-
- return <div>...</div>;
};
```
-### Pattern 3: Conditional Fetching
-
-Pass `undefined` to disable the hook entirely.
+The example's `EmptyState` and `BenchmarkCards` stand for the surface's existing
+renderers. Follow these distinctions when adapting it:
-```tsx
-// only fetch when modal is open AND id present
-useFetchDatasetDetail(open && datasetId ? datasetId : undefined);
-```
+- Show first-load errors before empty / `NotFound` / zero-value defaults. Do not put
+ an error branch after `if (!map[id]) return <Skeleton />`; failure may never fill the map.
+- Preserve settled content during background revalidation failures, including a
+ successfully loaded empty list. A retry in flight should show pending feedback.
+- In a fetched + static list, use the fetched slice's request state before combining
+ rows. Static rows must not hide a failed request.
+- For infinite scroll, keep a per-bucket `loadMoreError` and show an inline Retry row.
+ Suspend observer-triggered retries while that error is unresolved.
+- A closed modal or absent id disables a request; it is not evidence of a missing record.
-### Pattern 4: Cross-domain Refresh
-
-```typescript
-deleteBenchmark: async (id) => {
- await agentEvalService.deleteBenchmark(id);
- await get().refreshBenchmarks();
- await get().refreshDatasets(id); // related cache invalidated too
-};
-```
-
----
-
-## Migration Guide: useEffect โ†’ Store SWR
-
-### Before (โŒ Wrong)
-
-```tsx
-const TestCaseList = ({ datasetId }: Props) => {
- const [data, setData] = useState<any[]>([]);
- const [loading, setLoading] = useState(false);
-
- useEffect(() => {
- setLoading(true);
- lambdaClient.agentEval.listTestCases
- .query({ datasetId })
- .then((r) => setData(r.data))
- .finally(() => setLoading(false));
- }, [datasetId]);
-
- return <Table data={data} loading={loading} />;
-};
-```
-
-### After (โœ… Correct)
-
-```typescript
-// 1. Add service method
-class AgentEvalService {
- async listTestCases(params: { datasetId: string }) {
- return lambdaClient.agentEval.listTestCases.query(params);
- }
-}
-
-// 2. Add store slice hook
-export const createTestCaseSlice: StateCreator<...> = (set) => ({
- useFetchTestCases: (params) =>
- useClientDataSWR(
- params.datasetId ? [FETCH_TEST_CASES_KEY, params.datasetId] : null,
- () => agentEvalService.listTestCases(params),
- {
- onSuccess: (data) =>
- set({ testCaseList: data.data, isLoadingTestCases: false }),
- },
- ),
-});
-
-// 3. Component reads from store
-const TestCaseList = ({ datasetId }: Props) => {
- const useFetchTestCases = useEvalStore((s) => s.useFetchTestCases);
- const data = useEvalStore((s) => s.testCaseList);
- const loading = useEvalStore((s) => s.isLoadingTestCases);
-
- useFetchTestCases({ datasetId });
-
- return <Table data={data} loading={loading} />;
-};
-```
-
----
-
-## Troubleshooting
-
-| Symptom | Check |
-| --------------------------- | ------------------------------------------------------------------- |
-| Data never loads | Hook called? Key not `null`/`undefined`? Network tab shows request? |
-| Stale data after mutation | Did `refreshXxx` run? Cache key matches what the hook uses? |
-| Loading state stuck `true` | `onSuccess` writes loading=false? Promise rejected silently? |
-| Detail map missing an entry | Reducer dispatch ran? `isEqual` short-circuited on stale data? |
-
----
-
-## Summary Checklist
-
-When adding new data fetching:
-
-### Step 1: Types & State
-
-See `store-data-structures` for details.
-
-- [ ] Define types in `@lobechat/types`: Detail type + List item type
-- [ ] State structure: `xxxList: XxxListItem[]`, `xxxDetailMap: Record<string, Xxx>`, `loadingXxxDetailIds: string[]`
-- [ ] Reducer if optimistic updates are needed
-
-### Step 2: Service Layer
-
-- [ ] Create service in `src/services/xxxService.ts`
-- [ ] Methods: `listXxx()`, `getXxx(id)`, `createXxx()`, `updateXxx()`, `deleteXxx()`
-
-### Step 3: Store Actions
-
-- [ ] `initialState.ts` with state structure
-- [ ] `action.ts` with:
- - [ ] `useFetchXxxList()`, `useFetchXxxDetail(id)` โ€” SWR hooks
- - [ ] `refreshXxxList()`, `refreshXxxDetail(id)` โ€” cache invalidation
- - [ ] CRUD methods calling service
- - [ ] `internal_dispatch`, `internal_updateLoading` if using reducer
-- [ ] `selectors.ts` (optional but recommended)
-- [ ] Integrate slice into main store + initialState
-
-### Step 4: Component Usage
-
-- [ ] Use store hooks (NOT useEffect)
-- [ ] Destructure and consume `error` / `mutate`; wrap first-load surfaces in `AsyncBoundary`
- or render `AsyncError` before empty / `NotFound` / zero defaults
-- [ ] List pages: access `xxxList` array
-- [ ] Detail pages: access `xxxDetailMap[id]`
-- [ ] Use loading states for UI feedback
-- [ ] Infinite-scroll failures persist as a visible tail Retry row, not a silent `catch`
-- [ ] Changes affecting home first paint or persisted display data follow the guidance above
-
-**Mental model:** Types โ†’ Service โ†’ Reducer โ†’ Slice โ†’ Component ๐ŸŽฏ
-
----
+## Migrating an existing fetch
-## Related Skills
+Move the API call into its service and the request into a store SWR hook. Reuse the
+existing state shape and action organization unless they need to change for the task.
+Replace the component's effect/local fetch state with that hook and selectors, then
+connect `error`, retry, and pending feedback. Refresh the same cache key after writes.
-- **`store-data-structures`** โ€” How to structure List and Detail data in stores
-- **`zustand`** โ€” General Zustand patterns and best practices
+Check initial failure, retry, settled-empty results, background failure, and switching
+ids against the surface being changed. For stale data, compare read/refresh keys and
+the store bucket they update; for stuck loading, inspect rejected requests as well as
+success callbacks. Do not add a second fetch or another loading flag to mask the cause.
diff --git a/.agents/skills/data-fetching-architecture/references/walkthrough.md b/.agents/skills/data-fetching-architecture/references/walkthrough.md
index 893e9ed69e4..56941841f6b 100644
--- a/.agents/skills/data-fetching-architecture/references/walkthrough.md
+++ b/.agents/skills/data-fetching-architecture/references/walkthrough.md
@@ -1,244 +1,93 @@
-# Walkthrough: Adding a New Feature End-to-End
+# Parent-Keyed Lists
-This is a worked example of the canonical 6-step recipe applied to a new entity (`Dataset`), showing a variant of the main skill's pattern: **a list keyed by a parent id** (`datasetMap[benchmarkId]`), useful when the same shape appears under different parents.
+Use this variant when the store needs to retain separate lists for multiple parents,
+such as datasets under different benchmarks. A single visible list does not need a
+parent-keyed map merely because its request has a parent parameter.
-If you only need the canonical (single-array) pattern, the main `SKILL.md` already shows it for `Benchmark`. Read this file when you need the parent-keyed Map variant, or when you want a checklist-style walkthrough.
+The request key and store bucket must identify the same parent. If filters or pages
+also need independent retained state, include them in the bucket identity as well as
+the SWR key; otherwise a response can overwrite another view's data.
-## Step 1: Add Service methods
+## Store pattern
-```typescript
-class AgentEvalService {
- async listDatasets(benchmarkId: string) {
- return lambdaClient.agentEval.listDatasets.query({ benchmarkId });
- }
- async getDataset(id: string) {
- return lambdaClient.agentEval.getDataset.query({ id });
- }
- async createDataset(params: CreateDatasetParams) {
- return lambdaClient.agentEval.createDataset.mutate(params);
- }
- // updateDataset / deleteDataset follow the same shape
-}
-```
-
-## Step 2: Reducer (optimistic updates)
-
-```typescript
-// src/store/eval/slices/dataset/reducer.ts
-export type DatasetDispatch =
- | { type: 'addDataset'; value: Dataset }
- | { type: 'updateDataset'; id: string; value: Partial<Dataset> }
- | { type: 'deleteDataset'; id: string };
-
-export const datasetReducer = (state: Dataset[] = [], payload: DatasetDispatch): Dataset[] =>
- produce(state, (draft) => {
- switch (payload.type) {
- case 'addDataset':
- draft.unshift(payload.value);
- break;
- case 'updateDataset': {
- const i = draft.findIndex((item) => item.id === payload.id);
- if (i !== -1) draft[i] = { ...draft[i], ...payload.value };
- break;
- }
- case 'deleteDataset': {
- const i = draft.findIndex((item) => item.id === payload.id);
- if (i !== -1) draft.splice(i, 1);
- break;
- }
- }
- });
-```
-
-## Step 3: Store slice
+The following is an illustrative action-class method. `DatasetListItem` denotes the
+domain's shared list-item type; use the real service return shape when implementing it.
+The domain key factory and service call are shared with ordinary list fetching.
```typescript
-// src/store/eval/slices/dataset/initialState.ts
-export interface DatasetData {
- currentPage: number;
- hasMore: boolean;
- isLoading: boolean;
- items: Dataset[];
- pageSize: number;
- total: number;
+interface DatasetSliceState {
+ datasetListMap: Record<string, DatasetListItem[]>;
}
-export interface DatasetSliceState {
- // Map keyed by benchmarkId โ€” multiple parent contexts share the slice
- datasetMap: Record<string, DatasetData>;
- // Single item for modal display
- datasetDetail: Dataset | null;
- isLoadingDatasetDetail: boolean;
- loadingDatasetIds: string[];
-}
-
-export const datasetInitialState: DatasetSliceState = {
- datasetMap: {},
- datasetDetail: null,
- isLoadingDatasetDetail: false,
- loadingDatasetIds: [],
-};
-```
-
-```typescript
-// src/store/eval/slices/dataset/action.ts
-const FETCH_DATASETS_KEY = 'FETCH_DATASETS';
-const FETCH_DATASET_DETAIL_KEY = 'FETCH_DATASET_DETAIL';
-
-export const createDatasetSlice: StateCreator<EvalStore, any, [], DatasetAction> = (set, get) => ({
- // Cache key includes benchmarkId so each parent has its own SWR entry
- useFetchDatasets: (benchmarkId) =>
- useClientDataSWR(
- benchmarkId ? [FETCH_DATASETS_KEY, benchmarkId] : null,
- () => agentEvalService.listDatasets(benchmarkId!),
- {
- onSuccess: (data) => {
- set({
- datasetMap: {
- ...get().datasetMap,
- [benchmarkId!]: {
- currentPage: 1,
- hasMore: false,
- isLoading: false,
- items: data,
- pageSize: data.length,
- total: data.length,
- },
- },
- });
- },
- },
- ),
-
- useFetchDatasetDetail: (id) =>
- useClientDataSWR(
- id ? [FETCH_DATASET_DETAIL_KEY, id] : null,
- () => agentEvalService.getDataset(id!),
- {
- onSuccess: (data) => set({ datasetDetail: data, isLoadingDatasetDetail: false }),
+useFetchDatasets = (benchmarkId?: string) =>
+ useClientDataSWR(
+ benchmarkId ? evalKeys.datasets(benchmarkId) : null,
+ () => agentEvalService.listDatasets(benchmarkId!),
+ {
+ onSuccess: (items) => {
+ this.#set((state) => ({
+ datasetListMap: {
+ ...state.datasetListMap,
+ [benchmarkId!]: items,
+ },
+ }));
},
- ),
-
- refreshDatasets: (benchmarkId) => mutate([FETCH_DATASETS_KEY, benchmarkId]),
- refreshDatasetDetail: (id) => mutate([FETCH_DATASET_DETAIL_KEY, id]),
-
- // CREATE with optimistic update โ€” note the temp id pattern
- createDataset: async (params) => {
- const tmpId = Date.now().toString();
- const { benchmarkId } = params;
-
- get().internal_dispatchDataset(
- { type: 'addDataset', value: { ...params, id: tmpId, createdAt: Date.now() } as any },
- benchmarkId,
- );
- get().internal_updateDatasetLoading(tmpId, true);
-
- try {
- const result = await agentEvalService.createDataset(params);
- await get().refreshDatasets(benchmarkId);
- return result;
- } finally {
- get().internal_updateDatasetLoading(tmpId, false);
- }
- },
-
- // UPDATE / DELETE follow the same optimistic + refresh pattern as BenchmarkSlice
- // (see the main SKILL.md)
-
- // Internal โ€” dispatch reducer scoped to a parent
- internal_dispatchDataset: (payload, benchmarkId) => {
- const currentData = get().datasetMap[benchmarkId];
- const nextItems = datasetReducer(currentData?.items, payload);
-
- // Skip set when nothing changed โ€” avoids unnecessary re-renders
- if (isEqual(nextItems, currentData?.items)) return;
-
- set({
- datasetMap: {
- ...get().datasetMap,
- [benchmarkId]: {
- ...currentData,
- currentPage: currentData?.currentPage ?? 1,
- hasMore: currentData?.hasMore ?? false,
- isLoading: false,
- items: nextItems,
- pageSize: currentData?.pageSize ?? nextItems.length,
- total: currentData?.total ?? nextItems.length,
- },
- },
- });
- },
-
- internal_updateDatasetLoading: (id, loading) => {
- set((state) => ({
- loadingDatasetIds: loading
- ? [...state.loadingDatasetIds, id]
- : state.loadingDatasetIds.filter((i) => i !== id),
- }));
- },
-});
-```
-
-## Step 4: Wire into the store
+ },
+ );
-```typescript
-// src/store/eval/store.ts
-export type EvalStore = EvalStoreState & BenchmarkAction & DatasetAction & RunAction;
-
-const createStore: StateCreator<EvalStore, [['zustand/devtools', never]]> = (set, get, store) => ({
- ...initialState,
- ...createBenchmarkSlice(set, get, store),
- ...createDatasetSlice(set, get, store),
- ...createRunSlice(set, get, store),
-});
-
-// src/store/eval/initialState.ts
-export const initialState: EvalStoreState = {
- ...benchmarkInitialState,
- ...datasetInitialState,
- ...runInitialState,
+refreshDatasets = async (benchmarkId: string) => {
+ await mutate(evalKeys.datasets(benchmarkId));
};
```
-## Step 5: Selectors (optional but recommended)
+Capture the request's parent id in the callback rather than reading the currently
+selected parent when the response arrives. Preserve other buckets during updates.
+Add pagination metadata only if the endpoint and surface use it; derive totals and
+`hasMore` from the response rather than guessing from the loaded array length.
-```typescript
-export const datasetSelectors = {
- getDatasetData: (benchmarkId: string) => (s: EvalStore) => s.datasetMap[benchmarkId],
- getDatasets: (benchmarkId: string) => (s: EvalStore) => s.datasetMap[benchmarkId]?.items ?? [],
- isLoadingDataset: (id: string) => (s: EvalStore) => s.loadingDatasetIds.includes(id),
-};
-```
+## Component request state
-## Step 6: Use in component
+Read the matching bucket, but use the hook response to distinguish loading, failure,
+and a settled result. The example assumes `benchmarkId` is present for the mounted list.
```tsx
-// List scoped to a parent
const DatasetList = ({ benchmarkId }: { benchmarkId: string }) => {
const useFetchDatasets = useEvalStore((s) => s.useFetchDatasets);
- const datasets = useEvalStore(datasetSelectors.getDatasets(benchmarkId));
- const datasetData = useEvalStore(datasetSelectors.getDatasetData(benchmarkId));
-
- useFetchDatasets(benchmarkId);
+ const items = useEvalStore((s) => s.datasetListMap[benchmarkId]);
+ const { data, error, isLoading, mutate } = useFetchDatasets(benchmarkId);
- if (datasetData?.isLoading) return <Loading />;
return (
- <div>
- <h2>Total: {datasetData?.total ?? 0}</h2>
- <List data={datasets} />
- </div>
+ <AsyncBoundary
+ data={data}
+ empty={<EmptyState />}
+ error={error}
+ isEmpty={data?.length === 0}
+ isLoading={isLoading}
+ onRetry={() => {
+ void mutate();
+ }}
+ >
+ <DatasetCards items={items ?? []} />
+ </AsyncBoundary>
);
};
+```
-// Single item for modal โ€” conditional fetching pattern
-const DatasetImportModal = ({ open, datasetId }: Props) => {
- const useFetchDatasetDetail = useEvalStore((s) => s.useFetchDatasetDetail);
- const dataset = useEvalStore((s) => s.datasetDetail);
- const isLoading = useEvalStore((s) => s.isLoadingDatasetDetail);
+`EmptyState` and `DatasetCards` stand for the surface's existing renderers. Do not
+replace the boundary's `data` with `items ?? []`: an uninitialized bucket would look
+like a successful empty result and hide the first-load error.
- // Only fetch when modal is open AND id present
- useFetchDatasetDetail(open && datasetId ? datasetId : undefined);
+## Mutation and detail boundaries
- return <Modal open={open}>{isLoading ? <Loading /> : <div>{dataset?.name}</div>}</Modal>;
-};
-```
+Refresh the affected parent after a write, and both parents if an item moves between
+them. If a reducer updates the list, dispatch into that same parent bucket. Delete
+only after server success; optimistic create/update must recover on failure as
+described in the [main skill](../SKILL.md#mutations).
+
+Keep item details keyed by item id, following [Zustand data structures](../../zustand/references/data-structures.md), rather than
+introducing one shared `datasetDetail` slot that can display the previous item's data.
+For a conditional detail request, pass `undefined` while the surface is inactive and
+map it to a `null` SWR key. When active, consume its error/retry state just as for a list.
+
+Use the `zustand` skill for class composition and `flattenActions`; this cache variant
+does not require a separate store-wiring or reducer recipe.
diff --git a/.agents/skills/db-migrations/SKILL.md b/.agents/skills/db-migrations/SKILL.md
index a4e18c955e6..9038f3007c1 100644
--- a/.agents/skills/db-migrations/SKILL.md
+++ b/.agents/skills/db-migrations/SKILL.md
@@ -1,6 +1,6 @@
---
name: db-migrations
-description: 'Use for database rollout strategy, Drizzle migrations, online index creation, data backfills, migration regeneration, sequence conflicts after rebase, idempotent SQL review, or migration renames.'
+description: 'Use for Drizzle migration rollout, online indexes, backfills, idempotent SQL and migration regeneration or rebase conflicts.'
user-invocable: false
---
diff --git a/.agents/skills/debug-frontend-with-browser/SKILL.md b/.agents/skills/debug-frontend-with-browser/SKILL.md
index 3fae1d98d31..e933fee3907 100644
--- a/.agents/skills/debug-frontend-with-browser/SKILL.md
+++ b/.agents/skills/debug-frontend-with-browser/SKILL.md
@@ -1,6 +1,6 @@
---
name: debug-frontend-with-browser
-description: Frontend diagnosis extension for the acceptance skill. Use for intermittent rendering, ordering, stale-state, navigation, virtual-list, React/Zustand, optimistic-update, refresh-dependent, or browser-only failures where the first broken boundary may be DOM, component input, derived state, client cache, network data, or a pure transformation. Before any browser, Electron, or live-app interaction, this skill must load and follow the acceptance skill and the repository's `.agents/acceptance/` project layer; it adds only boundary tracing, minimal fixture replay, and regression attribution.
+description: 'Use for intermittent UI, stale state, ordering, navigation or browser-only bugs. Extends acceptance with boundary tracing and regression diagnosis.'
---
# Debug Frontend with Browser
diff --git a/.agents/skills/debug-frontend-with-browser/agents/openai.yaml b/.agents/skills/debug-frontend-with-browser/agents/openai.yaml
index 45122327f61..c9f5b1248ff 100644
--- a/.agents/skills/debug-frontend-with-browser/agents/openai.yaml
+++ b/.agents/skills/debug-frontend-with-browser/agents/openai.yaml
@@ -1,4 +1,4 @@
interface:
display_name: 'Debug Frontend with Browser'
short_description: 'Diagnose frontend state after isolated test setup'
- default_prompt: 'Use $debug-frontend-with-browser after $agent-testing to isolate the first broken frontend state boundary.'
+ default_prompt: 'Use $debug-frontend-with-browser after $acceptance to isolate the first broken frontend state boundary.'
diff --git a/.agents/skills/debug-package/SKILL.md b/.agents/skills/debug-package/SKILL.md
index a3b410c13e9..bb444f8e561 100644
--- a/.agents/skills/debug-package/SKILL.md
+++ b/.agents/skills/debug-package/SKILL.md
@@ -1,6 +1,6 @@
---
name: debug-package
-description: 'LobeHub debug package and log namespace guide. Use when adding debug() logging, choosing lobe-* namespaces, troubleshooting DEBUG output, localStorage.debug, or log format specifiers.'
+description: 'Use for debug() logging, lobe-* namespaces, DEBUG/localStorage.debug configuration and log formatting.'
user-invocable: false
---
diff --git a/.agents/skills/deep-review/SKILL.md b/.agents/skills/deep-review/SKILL.md
index 6b8cc18e65b..272b3b0f82c 100644
--- a/.agents/skills/deep-review/SKILL.md
+++ b/.agents/skills/deep-review/SKILL.md
@@ -1,6 +1,6 @@
---
name: deep-review
-description: 'Multi-dimensional code review. Use when the user asks to review, evaluate, or audit a PR, diff, branch, or pasted change โ€” including informal review asks like "look at this change for problems" โ€” via light mode: one independent reviewer against the dimension quick checklists. Not for explain-only questions about what a change does or why. Deep mode runs only on explicit invocation (/deep-review), and normally at most once per logical requirement.'
+description: 'Use for independent PR, diff or branch review; not explanations. Full multi-agent review requires an explicit deep-review request.'
---
# Deep Review
@@ -13,7 +13,7 @@ consolidation before findings reach the report.
Every design choice below serves one of these. When unsure how to execute a step, come back here.
-1. **Anti-hallucination** โ€” reviewers that only see diff fragments invent bugs. Candidate findings are therefore falsified one by one by an **independent verify subagent** that reads full context and returns a three-way verdict (`confirmed` / `false_positive` / `need_more_context`). Three-way verdicts beat confidence percentages: calibrated-sounding scores are unreliable as hard filters.
+1. **Anti-hallucination** โ€” reviewers need surrounding context, not only diff fragments. Deep mode verifies candidate findings through independent agents returning `confirmed` / `false_positive` / `need_more_context`. Light mode uses the bounded follow-up procedure below; it does not add a separate per-finding verification pipeline.
2. **Anti self-approval** โ€” an agent that just wrote the code is grading its own homework and will pass it. Both modes use an **independent reviewer** with a third-party stance. Light: one reviewer that is not the main agent. Deep: independent subagents per the environment manual. Never silently degrade either mode to "the main agent reviews the diff itself".
3. **Rules over model** โ€” review quality comes from fine-grained, executable dimension rules, not from a smarter model. Subagents run on balanced/fast model tiers; each dimension file tells them exactly how to check, what counts, and what does not.
4. **Calibrate to codebase and lifespan** โ€” hold the diff to the standard the codebase already meets, not an idealized one. If a pattern is widespread in the existing code and this diff does not make it worse, it is not a finding. Declared-temporary code (time-boxed campaign, experiment, one-off script) is judged against its lifespan: hardcoding and low-extensibility shortcuts are the intended trade-off for shipping fast, and "delete the code at expiry" is a valid plan โ€” do not demand configurability from code built to be deleted. (Security is exempt from all calibration โ€” see the dimension file.)
@@ -21,10 +21,10 @@ Every design choice below serves one of these. When unsure how to execute a step
## Two entry modes
-| Mode | Trigger | What runs |
-| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| **Light** (default) | Any ordinary review ask: "review this PR", an informal "look at this change for problems", a diff pasted for review โ€” but not explain-only questions about a change | One independent reviewer against the **Quick checklist** of each applicable dimension. Prefer a different-vendor harness when the session can dispatch to one; otherwise one same-harness subagent. No verify pass. The main agent does not review. |
-| **Deep** | Explicit only: `/deep-review`, "run deep review", "full multi-agent review" | Full orchestration: dimension review agents โ†’ pipelined verification โ†’ global consolidation โ†’ structured report โ†’ interactive fix flow. |
+| Mode | Trigger | What runs |
+| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| **Light** (default) | Any ordinary review ask: "review this PR", an informal "look at this change for problems", a diff pasted for review โ€” but not explain-only questions about a change | One independent reviewer against the **Quick checklist** of each applicable dimension. Prefer a different-vendor harness when available; otherwise one same-harness subagent. At most one follow-up verification round as described below. |
+| **Deep** | Explicit only: `/deep-review`, "run deep review", "full multi-agent review" | Full orchestration: dimension review agents โ†’ pipelined verification โ†’ global consolidation โ†’ structured report โ†’ interactive fix flow. |
Do not auto-escalate light to deep. Do not run deep mode for a casual "็œ‹็œ‹่ฟ™ไธชๆ”นๅŠจ" โ€” that is light mode.
@@ -106,8 +106,9 @@ that prompt and do not re-enter this procedure.
1. If this session can dispatch a self-contained task to a different vendor's coding-agent harness (not a same-harness subagent), use that. Prefer a preset whose job is independent code review when the dispatcher exposes one.
2. Otherwise spawn one same-harness subagent. Disable context inheritance when the spawn API allows it.
3. If the chosen path fails, try the next. If none work, stop and tell the user why. Do not review the diff yourself.
-4. Relay the reviewer's findings in your environment's normal review format (light mode does NOT use the deep report template). Do not drop, downgrade, or re-verify findings. When the reviewer listed pre-deploy confirmation items, keep them as a short checklist separate from defects. Mention that deep mode exists if findings suggest the diff deserves a full pass.
- - On a follow-up round (verifying that earlier findings were fixed), dispatch again on the newly changed code as a fresh diff โ€” never just confirm the requested edits landed. Fix commits introduce new logic (guards, parsers, refactors) whose bugs a checkbox pass will miss.
+4. Assess the findings against their evidence. In an authorized implementation task, fix accepted, safe, in-scope issues and run appropriate checks. To reject or downgrade a finding, send the counterevidence to the independent verification round below rather than overruling the reviewer yourself. A standalone review request does not authorize edits.
+5. Allow **at most one follow-up verification round** per review request, covering disputed findings and fixes together, regardless of dimension. Append the original findings and counterevidence to the light-review prompt and supply the current diff; ask the independent reviewer to check changed behavior and possible regressions. Correct or withdraw findings only with concrete evidence and state the reason. Fixes, new commits, and context compaction do not reset this budget. If verification still fails or leaves a finding unresolved, report that status honestly without further automatic review rounds. Necessary authorized repairs can continue, but do not claim a subsequent independent pass. A new explicit user request for review takes precedence over this automatic limit.
+6. Report the resulting findings and verification status in the environment's normal review format (not the deep report template). Keep pre-deploy confirmation items separate from defects.
## Deep mode procedure
diff --git a/.agents/skills/deep-review/references/dimensions/reuse-architecture.md b/.agents/skills/deep-review/references/dimensions/reuse-architecture.md
index 1ce6f51458e..4dbf13f8173 100644
--- a/.agents/skills/deep-review/references/dimensions/reuse-architecture.md
+++ b/.agents/skills/deep-review/references/dimensions/reuse-architecture.md
@@ -33,7 +33,7 @@ Reuse operates at three levels, and AI-authored diffs most often fail at the upp
- `.agents/skills/project-overview/SKILL.md` โ€” layer map: what belongs in apps/packages/src
- `.agents/skills/spa-routes/SKILL.md` โ€” roots vs features split
- `.agents/skills/data-fetching-architecture/SKILL.md` โ€” the canonical cross-layer route for server data (component โ†’ store SWR hook โ†’ service โ†’ `lambdaClient`)
-- `.agents/skills/store-data-structures/SKILL.md`, `.agents/skills/zustand/SKILL.md` โ€” store shape and action patterns when the diff touches stores
+- `.agents/skills/zustand/SKILL.md` and its `references/data-structures.md` โ€” store shape and action patterns when the diff touches stores
- Category pattern skills when the diff's category has one (`modal`, `trpc-router`, `builtin-tool`, `drizzle`, ...) โ€” check `.agents/skills/` for a skill matching the touched domain; when one exists it is the yardstick, cite it in `rule_source`
## How to check
diff --git a/.agents/skills/deep-review/references/dimensions/workflow.md b/.agents/skills/deep-review/references/dimensions/workflow.md
index 17f56facafc..cd45f85d5ba 100644
--- a/.agents/skills/deep-review/references/dimensions/workflow.md
+++ b/.agents/skills/deep-review/references/dimensions/workflow.md
@@ -15,7 +15,7 @@ Is the process around this change healthy? These are objective state checks โ€”
- Key decisions made during implementation (trade-offs, rejected alternatives, scope cuts) recorded in the issue/PR, not only in a chat transcript
- Decision records still match the implementation: when the implementation legitimately diverged from a decision written earlier in the issue/PR/conversation, the record is updated in the same PR โ€” a stale decision record misleads every later reader, and reviewers without the session context can only trust what is written
- CI green; preview/deployment build succeeded โ€” a red or pending-forever check is a finding with the failing job named
-- PR targets the right branch (this repo: feature PRs โ†’ `canary`; DB schema changes ride a separate branch PR'd to `main` first)
+- PR targets the right branch (`canary` in this repo); follow the repository's migration workflow for schema changes
- Commit messages follow repo convention (gitmoji prefix)
- Locale files: new keys shipped with en-US + zh-CN per the i18n workflow; other locales left to the auto-i18n CI
diff --git a/.agents/skills/deep-review/references/light-review-prompt.md b/.agents/skills/deep-review/references/light-review-prompt.md
index 346f610bcb1..79473339c17 100644
--- a/.agents/skills/deep-review/references/light-review-prompt.md
+++ b/.agents/skills/deep-review/references/light-review-prompt.md
@@ -55,7 +55,7 @@ Calibrate to lifespan as well: when the scope summary, PR/issue, or code comment
Focus over completeness: findings must serve THIS change and its requirement. Do not audit unrelated legacy code, and do not propose rewrites beyond the change's scope.
-If this is a follow-up that earlier findings were fixed, review the new diff as a fresh review under the same checklists โ€” never only confirm the requested edits landed.
+For a follow-up, assess every supplied original finding and its counterevidence against the current code, and check the fixes for regressions under the same checklists. Report each original finding as resolved, still present, or unresolved with the reason. Do not drop an original finding merely because its line is absent from the fix diff, and do not stop at confirming that the requested edits landed.
## Review scope (hard rules)
diff --git a/.agents/skills/design-prototype/SKILL.md b/.agents/skills/design-prototype/SKILL.md
index 6b12a272588..9b3991f6ab2 100644
--- a/.agents/skills/design-prototype/SKILL.md
+++ b/.agents/skills/design-prototype/SKILL.md
@@ -1,6 +1,6 @@
---
name: design-prototype
-description: Produce an interactive single-file HTML design prototype using the REAL LobeHub design system (@lobehub/ui + antd + antd-style tokens) with production-style React โ€” no build step, opens directly in a browser. Use when asked for a design prototype / interactive mockup / ไบคไบ’ๅŽŸๅž‹ / ๅ‡บไธชๅŽŸๅž‹ / ่ฎพ่ฎก็จฟ HTML for a page or flow, or to explore a redesign before committing to implementation.
+description: 'Use for interactive HTML prototypes (ไบคไบ’ๅŽŸๅž‹) with the real LobeHub UI stack. Excludes production UI implementation.'
---
# Design Prototype
diff --git a/.agents/skills/docs-changelog/SKILL.md b/.agents/skills/docs-changelog/SKILL.md
index 5364b4871af..d69aa11f728 100644
--- a/.agents/skills/docs-changelog/SKILL.md
+++ b/.agents/skills/docs-changelog/SKILL.md
@@ -1,6 +1,6 @@
---
name: docs-changelog
-description: 'Write website changelog pages under docs/changelog/*.mdx. Use for EN/ZH product update posts, changelog posts, update-log copy, or docs changelog edits; not GitHub Release notes.'
+description: 'Use for EN/ZH website product changelogs in docs/changelog/*.mdx. Excludes GitHub Release notes.'
---
# Docs Changelog Writing Guide
diff --git a/.agents/skills/drizzle/SKILL.md b/.agents/skills/drizzle/SKILL.md
index 601cb88ae89..022d9b9e730 100644
--- a/.agents/skills/drizzle/SKILL.md
+++ b/.agents/skills/drizzle/SKILL.md
@@ -1,6 +1,6 @@
---
name: drizzle
-description: 'LobeHub Drizzle ORM schema and query style. Use for pgTable schemas, indexes, joins, inferred types, db.select/db.query, schema fields, foreign keys, junction tables, or postgres query patterns.'
+description: 'Use for Drizzle schemas and queries: tables, indexes, relations, joins and inferred types. Rollout belongs to db-migrations.'
user-invocable: false
---
diff --git a/.agents/skills/full-text-search/SKILL.md b/.agents/skills/full-text-search/SKILL.md
index 79762cc30f6..e4fedbfd6c2 100644
--- a/.agents/skills/full-text-search/SKILL.md
+++ b/.agents/skills/full-text-search/SKILL.md
@@ -1,6 +1,6 @@
---
name: full-text-search
-description: 'LobeHub product full-text search architecture and operations. Use for FtsSearchRepo, pg_search or Elasticsearch providers, search projections and mappings, reindexing, Outbox capture/sync, provider switching, search analytics, or search performance. Not for agent web-browsing tools.'
+description: 'Use for product search: FtsSearchRepo, pg_search/Elasticsearch, projections, Outbox sync, reindexing and performance. Excludes agent web search.'
---
# Product Full-Text Search
diff --git a/.agents/skills/heterogeneous-agent/SKILL.md b/.agents/skills/heterogeneous-agent/SKILL.md
index c192e29a14b..389cd2a5f5b 100644
--- a/.agents/skills/heterogeneous-agent/SKILL.md
+++ b/.agents/skills/heterogeneous-agent/SKILL.md
@@ -1,6 +1,6 @@
---
name: heterogeneous-agent
-description: 'Implement or debug LobeHub heterogeneous agents. Use for Claude Code/Codex adapters, external CLI agents, event mapping, IPC, persistence, tool-call chains, sessions, traces, or adapter bugs.'
+description: 'Use for Claude Code/Codex external-agent adapters, IPC, event mapping, sessions, persistence and tool-call chains.'
---
# Heterogeneous Agent Development
diff --git a/.agents/skills/hotkey/SKILL.md b/.agents/skills/hotkey/SKILL.md
index 0a7f862e837..2b8b4978003 100644
--- a/.agents/skills/hotkey/SKILL.md
+++ b/.agents/skills/hotkey/SKILL.md
@@ -1,6 +1,6 @@
---
name: hotkey
-description: 'Add or edit LobeHub keyboard shortcuts. Use for HotkeyEnum, HOTKEYS_REGISTRATION, combineKeys, useHotkeyById, tooltip hotkeys, shortcut scope, conflicts, or Cmd/Ctrl key combos.'
+description: 'Use for keyboard shortcuts, registration, key combinations, scope, conflicts and shortcut tooltips.'
user-invocable: false
---
diff --git a/.agents/skills/i18n/SKILL.md b/.agents/skills/i18n/SKILL.md
index 1fea01d6ea4..10e29445055 100644
--- a/.agents/skills/i18n/SKILL.md
+++ b/.agents/skills/i18n/SKILL.md
@@ -1,6 +1,6 @@
---
name: i18n
-description: 'LobeHub i18n with react-i18next. Use for user-facing strings, locale keys, namespaces, useTranslation, t(), interpolation, zh-CN/en-US previews, hardcoded UI copy, or bun run i18n.'
+description: 'Use for user-facing strings and react-i18next locale keys, namespaces, interpolation, translations or bun run i18n.'
user-invocable: false
---
diff --git a/.agents/skills/linear/SKILL.md b/.agents/skills/linear/SKILL.md
index 01e2057b2ac..56fab53fbfb 100644
--- a/.agents/skills/linear/SKILL.md
+++ b/.agents/skills/linear/SKILL.md
@@ -1,34 +1,24 @@
---
name: linear
-description: 'Linear issue management. Use for LOBE-xxx issues, Linear links, PRs referencing Linear, retrieving issues, updating status, completion comments, or sub-issue trees.'
+description: 'Use for Linear issues, LOBE-xxx links, status updates, completion comments and sub-issue trees.'
user-invocable: false
---
# Linear Issue Management
-Before using Linear workflows, search for `linear` MCP tools. If not found, treat as not installed.
-
-## PR Creation with Linear Issues
-
-A PR that fixes a Linear issue has **two separate jobs to do**, and both matter:
-
-1. **`Fixes LOBE-xxx` in the PR body** โ€” Linear watches GitHub for these magic keywords and auto-links the PR and auto-closes the issue on merge. This is the machine-readable side.
-2. **A completion comment on the Linear issue** โ€” gives the reviewer/PM/teammate landing in Linear a human-readable summary of what changed and why, without forcing them to click through to GitHub and read a diff.
-
-If you only do step 1, Linear watchers (often non-engineers) hit the issue and see no context. So pair PR creation with the Linear comment as part of the same task โ€” finish both before considering the work done.
+Before using Linear workflows, discover the available Linear tools, including deferred tools, and inspect their current schemas. Select tools by capability (issue lookup, images, sub-issues, create/update, comments), not a fixed MCP prefix or historical tool name. Report a missing capability only after discovery.
## Workflow
-1. **Retrieve issue details** before starting: `mcp__linear-server__get_issue`
-2. **Read images** โ€” issue descriptions often contain screenshots with critical context (mockups, error states, before/after). Use `mcp__linear-server__extract_images` so you actually see them; reading raw markdown alone misses what the reporter was looking at.
-3. **Check for sub-issues**: `mcp__linear-server__list_issues` with `parentId` filter
+1. **Retrieve issue details** before starting using the issue lookup capability.
+2. **Read images** โ€” issue descriptions often contain screenshots with critical context (mockups, error states, before/after). Use the available image extraction or viewing capability; reading raw markdown alone misses what the reporter was looking at.
+3. **Check for sub-issues** using the available parent filter or issue relation fields.
4. **Mark as In Progress** at the moment you start planning or implementing โ€” this signals to teammates the issue is owned, so they don't double-pick it up.
-5. **Update issue status** when completing: `mcp__linear-server__update_issue`
-6. **Add completion comment** (see [format below](#completion-comment-format))
+5. Follow [Per-Issue Completion](#per-issue-completion) before moving to the next issue.
## Creating Issues
-When creating issues with `mcp__linear-server__create_issue`, add the `claude code` label. Reason: the label is how the team filters/audits AI-generated issues; without it those issues vanish into the general backlog and the team loses visibility into AI contribution patterns.
+When creating issues, add the `claude code` label. Reason: the label is how the team filters/audits AI-generated issues; without it those issues vanish into the general backlog and the team loses visibility into AI contribution patterns.
Unless the user explicitly specifies another assignee or asks for the issue to remain unassigned, pass `assignee: "me"` so the issue is assigned to the authenticated Linear user. Always honor explicit assignment instructions over this default.
@@ -45,11 +35,11 @@ Specifics:
## Creating Sub-issue Trees
-When breaking a parent issue into a tree of sub-issues (e.g., task decomposition for LOBE-xxx), follow these rules โ€” they work around real limitations of the Linear MCP tools.
+When breaking a parent issue into a tree of sub-issues (e.g., task decomposition for LOBE-xxx), follow these conventions and check the available tool capabilities.
### 1. Prefix titles with an ordering index
-Linear itself supports sub-issue ordering: its public API exposes `subIssueSortOrder` on both `IssueCreateInput` and `IssueUpdateInput`, and the app offers per-user sub-issue sorting. The limitation is the current Linear MCP `save_issue` tool, which exposes neither `subIssueSortOrder` nor `sortOrder`; therefore, an agent cannot set sub-issue order through this MCP at create or update time.
+Linear supports sub-issue ordering, but tool support varies. Check the discovered create/update schema for ordering fields rather than assuming a particular MCP tool exposes them.
Workaround: encode execution order in the title itself:
@@ -73,7 +63,7 @@ Linear supports **unlimited sub-issue depth**. A flat list of 8+ siblings under
- Core service โ†’ its SDK โ†’ SDK consumers
- Don't create a sibling when a child is more accurate
-Use `parentId: "LOBE-xxxx"` at creation (or `save_issue` to move). Moving an issue's parent does not disturb its `blockedBy` relations.
+Set the parent relation when creating or moving an issue using the discovered schema (for example, `parentId: "LOBE-xxxx"` when supported). Moving the parent does not require rewriting `blockedBy` relations.
### 3. Sub-issue creation order is dictated by `blockedBy`
@@ -84,9 +74,9 @@ Use `parentId: "LOBE-xxxx"` at creation (or `save_issue` to move). Moving an iss
3. Create dependent issues only after collecting the blocker IDs from prior responses
4. `blockedBy` is **append-only**; passing it again does not overwrite โ€” safe to re-run
-### 4. Don't waste rounds trying to parallelize
+### 4. Respect dependency order
-MCP tool calls in a single message look parallel but execute sequentially on the server, and you still need blocker IDs from earlier responses. Just issue calls in dependency order; optimizing for parallelism gains nothing here.
+Collect blocker IDs before creating dependent issues. Do not assume parallel execution from how tool calls appear in a message; use the active tool's supported execution behavior.
### 5. Keep each sub-issue description self-contained
@@ -100,46 +90,11 @@ Each sub-issue should state:
The implementer may open only the sub-issue, not the parent โ€” don't rely on context that lives only in the parent description.
-## Completion Comment Format
-
-Each completed issue gets a comment summarizing the work, so reviewers and future readers don't have to reconstruct it from the PR diff:
-
-```markdown
-## Changes Summary
-
-- **Feature**: Brief description of what was implemented
-- **Files Changed**: List key files modified
-- **PR**: #xxx or PR URL
-
-### Key Changes
-
-- Change 1
-- Change 2
-- ...
-```
-
-This gives team visibility, code-review context, and a paper trail for future reference.
-
-## PR Association
-
-When creating PRs for Linear issues, include magic keywords in the PR body:
-
-- `Fixes LOBE-123`
-- `Closes LOBE-123`
-- `Resolves LOBE-123`
-
-These trigger Linear's auto-link + auto-close on merge.
-
-## Per-Issue Completion Rule
-
-When working on multiple issues, close out **each one before starting the next** โ€” don't batch all the Linear updates to the end. Batching is where comments get forgotten and issues stay stuck in "In Progress" days after the PR shipped.
+## Per-Issue Completion
-For each issue:
+Close out each issue before starting the next; do not defer all Linear updates to the end. Reuse existing authorization for that issue's status updates and comments without asking again.
-1. Complete implementation
-2. Run `bun run type-check`
-3. Run related tests
-4. Create PR if needed
-5. Update status to **"In Review"** (not "Done" โ€” "Done" is for after the PR merges)
-6. Add the completion comment
-7. Move to the next issue
+1. Complete implementation and the repository-required checks, including related tests; follow the Quality Check section of the repository's `AGENTS.md` (`bun run check` in LobeHub).
+2. Create a PR when needed using the **pr** skill. Include `Fixes LOBE-123` (or `Closes` / `Resolves`) in the PR body so Linear can link it and close the issue on merge.
+3. Update the issue to **In Review** while its PR awaits merge, then **Done** after merge. For work that needs no PR, mark **Done** when its outcome and verification are complete.
+4. Proactively add or update a concise completion comment with the resulting behavior, important changes, validation, and PR link. PR linkage does not replace this human-readable summary. If an existing comment already covers the same result, do not post a duplicate.
diff --git a/.agents/skills/llm-generation/SKILL.md b/.agents/skills/llm-generation/SKILL.md
index 178ee100f99..e1dcd16effe 100644
--- a/.agents/skills/llm-generation/SKILL.md
+++ b/.agents/skills/llm-generation/SKILL.md
@@ -1,6 +1,6 @@
---
name: llm-generation
-description: 'LobeHub application-level LLM generation conventions. Use when adding or changing prompts, generateObject/generateText calls, structured output schemas, generation model selection, prompt versions, llm_generation_tracing scenarios, or tests for AI-generated business content. Do not use for provider adapter internals or agent execution snapshots.'
+description: 'Use for application prompts, generateObject/generateText, model selection and generation tracing. Excludes provider adapters and agent snapshots.'
---
# LLM Generation
diff --git a/.agents/skills/modal/SKILL.md b/.agents/skills/modal/SKILL.md
index 994ed7aa34f..2c150bbfc15 100644
--- a/.agents/skills/modal/SKILL.md
+++ b/.agents/skills/modal/SKILL.md
@@ -1,6 +1,6 @@
---
name: modal
-description: 'LobeHub imperative modal conventions. Use when creating or migrating modals, dialogs, popups, confirm flows, ModalHost wiring, createModal, confirmModal, useModalContext, or base-ui modal APIs.'
+description: 'Use for modals, dialogs and confirmations with createModal, confirmModal, ModalHost or base-ui modal APIs.'
user-invocable: false
---
diff --git a/.agents/skills/model-bank-metadata/SKILL.md b/.agents/skills/model-bank-metadata/SKILL.md
index d99bd686831..0b936e6332f 100644
--- a/.agents/skills/model-bank-metadata/SKILL.md
+++ b/.agents/skills/model-bank-metadata/SKILL.md
@@ -1,6 +1,6 @@
---
name: model-bank-metadata
-description: 'Backfill and maintain model-bank metadata (knowledgeCutoff, family, generation). Use when adding models, fixing cutoff/family data, running a metadata sweep across aiModels providers, or researching official knowledge cutoffs.'
+description: 'Use for model knowledgeCutoff, family and generation metadata: onboarding, corrections, research and bulk backfills.'
user-invocable: false
---
diff --git a/.agents/skills/product-design/SKILL.md b/.agents/skills/product-design/SKILL.md
index 18958a2b5c9..f292d86762e 100644
--- a/.agents/skills/product-design/SKILL.md
+++ b/.agents/skills/product-design/SKILL.md
@@ -1,6 +1,6 @@
---
name: product-design
-description: 'Turn a vague product ask ("this page feels wrong", "we need a team view") into a grounded, shippable design by establishing business semantics and the user task before proposing a surface. Use when scoping a new surface, redesigning an existing one, or deciding what a feature should be. Not for auditing a built screen (ux-audit) or choosing visual details (ux).'
+description: 'Use for new surfaces, redesigns and vague product asks: establish user tasks and business meaning. Built-screen audits and visual polish have separate skills.'
---
# Product Design
diff --git a/.agents/skills/project-overview/SKILL.md b/.agents/skills/project-overview/SKILL.md
index b8b8848cdf3..c1a9941fd60 100644
--- a/.agents/skills/project-overview/SKILL.md
+++ b/.agents/skills/project-overview/SKILL.md
@@ -1,6 +1,6 @@
---
name: project-overview
-description: 'LobeHub open-source monorepo architecture map. Use when locating code layers, understanding apps/packages/src layout, business stubs, project structure, or onboarding to the repository.'
+description: 'Use for the OSS repository map, code-layer lookup, apps/packages/src ownership and business stubs.'
user-invocable: false
---
diff --git a/.agents/skills/react/SKILL.md b/.agents/skills/react/SKILL.md
index c0df7572001..fee7334d8ef 100644
--- a/.agents/skills/react/SKILL.md
+++ b/.agents/skills/react/SKILL.md
@@ -1,6 +1,6 @@
---
name: react
-description: 'LobeHub React component conventions. Use when editing TSX UI, choosing base-ui vs @lobehub/ui vs antd, styling with antd-style, component boundaries, local state, layouts, render performance, or memoization.'
+description: 'Use for TSX components, UI libraries, styling, state locality, layout, render performance and memoization.'
user-invocable: false
---
diff --git a/.agents/skills/response-compliance/SKILL.md b/.agents/skills/response-compliance/SKILL.md
index a41cb5bdb17..bd40278e9dd 100644
--- a/.agents/skills/response-compliance/SKILL.md
+++ b/.agents/skills/response-compliance/SKILL.md
@@ -1,6 +1,6 @@
---
name: response-compliance
-description: 'OpenResponses API compliance testing. Use for Response API endpoint tests, compliance runs, schema debugging, response api test, or openresponses test tasks.'
+description: 'Use for OpenResponses/Response API compliance tests, endpoint schema failures and test runs.'
---
# OpenResponses Compliance Test
diff --git a/.agents/skills/skills-audit/SKILL.md b/.agents/skills/skills-audit/SKILL.md
index 12536476b68..b0df1a427cc 100644
--- a/.agents/skills/skills-audit/SKILL.md
+++ b/.agents/skills/skills-audit/SKILL.md
@@ -14,7 +14,7 @@ Periodic review of the project-local skill set under `.agents/skills/`. The goal
### 1 โ€” Inventory
-Build a fresh census of all SKILL.md files. Do NOT trust any prior cached list.
+Build a current inventory, including symlinked skills. Look for inventory/check helpers in `package.json` scripts and `.agents/scripts/`; reuse them when available and inspect their supported options rather than duplicating their checks. Read each description and inspect bodies where routing, overlap, or stale references need investigation. Without an inventory helper:
```bash
find -L .agents/skills -name SKILL.md | wc -l # total count, including symlinked skills
@@ -23,24 +23,12 @@ find -L .agents/skills -name SKILL.md -exec wc -l {} \; | sort -rn # by body len
Group by domain in a mental table (DB / state / UI / agent / testing / workflow / docs / etc.). Note new arrivals since last audit (`git log --since="1 week ago" -- .agents/skills/`).
-### 2 โ€” Pull frontmatter for all skills
-
-```bash
-# Extract name + description for each SKILL.md
-for f in .agents/skills/*/SKILL.md; do
- echo "=== $(basename $(dirname $f)) ==="
- awk '/^---$/{c++; next} c==1' "$f" | head -20
-done
-```
-
-Read the description block of every skill. The body can stay unread unless step 4 flags it.
-
-### 3 โ€” Detect overlap / redundancy
+### 2 โ€” Detect overlap / redundancy
For each pair within the same domain, ask:
- **Same description**? โ†’ likely duplicate (one is probably a stale rename leftover, or a global-vs-local collision).
-- **Trigger keywords substantially overlap**? โ†’ either merge, OR tighten one description so the model can choose unambiguously.
+- **The same task fits multiple descriptions**? โ†’ check whether the skills are complementary or actually compete; clarify the boundary only when selection is ambiguous.
- **One skill's body says "see also: foo"**? โ†’ confirm `foo` still exists, AND confirm the cross-reference is still meaningful (the referenced skill may have absorbed the referrer's concerns).
- **Skill duplicates content from `AGENTS.md`**? โ†’ fold into AGENTS.md or slim the skill to just the delta.
@@ -50,37 +38,27 @@ Common false positives (do NOT merge):
- `agent-runtime-hooks` vs `agent-tracing` vs `agent-signal` โ€” different surfaces of the agent system.
- `testing` vs `acceptance` โ€” different test types.
-### 4 โ€” Description format consistency
+### 3 โ€” Description and invocation boundaries
-Apply the **standard template**:
+Check whether the description makes the skill's purpose and selection boundary clear and matches its body. Flag broad triggers that attract unrelated tasks, missing distinctions between overlapping skills, and stale names or references.
-```
-{Topic + key conventions or scope}. Use when {scenarios โ€” verbs + nouns}. Triggers on {`code-symbols`, 'natural phrases', 'ไธญๆ–‡'}.
-```
+Do not require literal phrases such as `Use when` or `Triggers on`, a fixed sentence structure, or a description length proportional to the body. These are writing choices, not runtime routing controls. Treat script wording heuristics as review hints, not proof of a defect.
-Skills with `disable-model-invocation: true` (user-invoked only, slash commands) don't need `Triggers on` โ€” they're never auto-routed.
+Verify explicit-only invocation settings against the active harness's supported metadata, such as frontmatter `disable-model-invocation` or `policy.allow_implicit_invocation` in `agents/openai.yaml`. Do not assume different harnesses recognize the same fields. Preserve the intended policy; do not infer runtime behavior from description wording alone.
-Flag descriptions that:
-
-- โŒ Have NO `Use when` clause (model can't decide when to load it).
-- โŒ Have NO `Triggers on` clause (and aren't `disable-model-invocation`).
-- โŒ Use weird formats (numbered lists `(1)(2)(3)`, `Triggers:` colon instead of `Triggers on`, `MUST use when ...` as opening word).
-- โŒ Are dramatically terse for a 200+ line body, or dramatically verbose for a 60-line body.
-- โŒ Reference deleted/renamed skills.
-
-### 5 โ€” Stale-skill check
+### 4 โ€” Stale-skill check
For narrow domain skills (e.g. `response-compliance`, one-off CLI workflows):
```bash
# Confirm the referenced code surface still exists
-rg -l "response-compliance|openresponses" packages/ src/ # adjust per skill
-git log --since="3 months ago" -- .agents/skills/ < skill > /SKILL.md # is it being maintained?
+rg -l "response-compliance|openresponses" packages/ src/ # adjust per skill
+git log --since="3 months ago" -- '.agents/skills/<skill>/SKILL.md' # replace <skill>
```
If the underlying surface is gone and the skill hasn't been edited in 3+ months โ†’ flag for archival.
-### 5b โ€” Living-log freshness (`common-mistakes.md`, `probe-mock-patterns.md`)
+### 4b โ€” Living-log freshness (`common-mistakes.md`, `probe-mock-patterns.md`)
Both layers (`.agents/skills/acceptance/references/` generic, `.agents/acceptance/`
project) are injected into every acceptance round, so a stale entry is a stale
@@ -96,46 +74,15 @@ rg -n 'holds-while: (?!always)' -P .agents/acceptance/common-mistakes.md # the m
- An entry that names a project script from the generic layer, or a product noun, is in the wrong layer.
- Duplicate ids (`rg -o '^### [ML]-?[A-Z]?\d+' | sort | uniq -d`).
-### 6 โ€” Cross-reference integrity
-
-Any skill body mentioning another skill by name:
-
-```bash
-# Scan all skill bodies for skill-name references
-rg -o '`[a-z][a-z0-9-]+`' .agents/skills/*/SKILL.md | grep -v ':\s*$' | sort -u
-```
+### 5 โ€” Cross-reference integrity
-For each name extracted, confirm `.agents/skills/<name>/SKILL.md` exists. Broken references happen after renames โ€” fix them in the same audit pass.
+Check actual skill links, named handoffs, and referenced files against their owning root, including symlink targets. A code symbol or CLI command in backticks is not automatically a skill reference. Resolve renamed or moved targets before reporting a broken link, and fix confirmed references when edits are authorized.
-### 7 โ€” Output report
+### 6 โ€” Output report
-Produce a markdown summary back to the user with the same structure as the original audit (this skill was created during one):
-
-```markdown
-## ๐Ÿ“Š Inventory
-
-{count, domain breakdown}
-
-## ๐ŸŽฏ Recommendations
-
-### ๐Ÿ”ด High confidence
-
-- {action} โ€” {reason}
-
-### ๐ŸŸก Medium confidence
-
-- {action} โ€” {reason needs verification}
-
-### ๐ŸŸข Low confidence / no-op
-
-- {item considered but skipping because ...}
-
-## ๐Ÿ“‹ Suggested order
-
-{table of actions with risk + LOC estimate}
-```
+Report actionable findings with file references, evidence, and the proposed change. Distinguish confirmed defects from uncertain candidates. Include inventory totals or an execution order only when they help the user decide; no fixed headings, template, or line-count estimates are required.
-End by asking the user which actions to apply โ€” do NOT auto-apply unless the user passed `--apply` and even then confirm destructive deletes individually.
+An audit-only request produces recommendations. When the user authorizes fixes, through `--apply` or ordinary language, apply safe changes within that scope without asking again. Deletions require authorization covering the target; do not request it again when already provided.
## Output rules
@@ -147,7 +94,7 @@ End by asking the user which actions to apply โ€” do NOT auto-apply unless the u
## What NOT to do
- โŒ Don't rename skill directories without checking for cross-references AND user memory entries that name the old slug.
-- โŒ Don't normalize a description by removing trigger keywords just to fit the template โ€” the keywords are the routing signal.
+- โŒ Don't remove meaningful selection boundaries merely to shorten a description or fit a template.
- โŒ Don't fold a heavy 200+ line skill into another just because they share a domain โ€” large skills get loaded selectively and merging makes everything load.
- โŒ Don't propose `.agents/skills/INDEX.md` or `<domain>-<skill>` prefix renames unless the user explicitly asks โ€” costs > benefits for cosmetic reorgs.
diff --git a/.agents/skills/spa-routes/SKILL.md b/.agents/skills/spa-routes/SKILL.md
index 62d2369bccf..06c488a8db4 100644
--- a/.agents/skills/spa-routes/SKILL.md
+++ b/.agents/skills/spa-routes/SKILL.md
@@ -1,6 +1,6 @@
---
name: spa-routes
-description: 'LobeHub SPA route architecture. Use when editing src/routes, src/features delegation, desktop/mobile/popup router configs, .desktop variants, route segments, redirects, or new pages.'
+description: 'Use for SPA routes and page segments: Web/desktop/mobile/popup routers, redirects and src/routes-to-features boundaries.'
user-invocable: false
---
diff --git a/.agents/skills/split-micro-app/SKILL.md b/.agents/skills/split-micro-app/SKILL.md
index 8092a0a67f6..a1b929e06bc 100644
--- a/.agents/skills/split-micro-app/SKILL.md
+++ b/.agents/skills/split-micro-app/SKILL.md
@@ -1,6 +1,6 @@
---
name: split-micro-app
-description: 'Use when splitting a monorepo surface into a standalone micro app (React Router SSR on Cloudflare Workers), splitting a surface whose rendering code lives in the lobehub-cloud business overlay, fighting SSR bundle bloat from main-src imports, deploying its assets to CDN/R2, adding SEO/OG meta to an SSR page, adding a target and route rules for it in the lobehub gateway (torii), setting up PR preview uploads on a sibling -preview Worker so the production script keeps its Cloudflare rollback window, wiring it into the OSS Docker image, or deciding whether Cloud Next should still build or rewrite it.'
+description: 'Use for standalone micro apps: React Router SSR/SSG, Cloud overlays, Workers, CDN/R2, SEO/OG, gateway routes, previews, Docker integration and SSR bundle isolation.'
user-invocable: false
---
diff --git a/.agents/skills/store-data-structures/SKILL.md b/.agents/skills/store-data-structures/SKILL.md
index aa8f6d37a0a..b5a57d22edd 100644
--- a/.agents/skills/store-data-structures/SKILL.md
+++ b/.agents/skills/store-data-structures/SKILL.md
@@ -1,314 +1,12 @@
---
name: store-data-structures
-description: 'LobeHub Zustand store data-shape patterns. Use when designing store state, list/detail splits, normalized maps, reducers, messagesMap, topicsMap, or choosing shared type sources.'
-user-invocable: false
+description: 'Explicit compatibility entry for Zustand data-shape guidance.'
+disable-model-invocation: true
+user-invocable: true
---
-# LobeHub Store Data Structures
+# Store Data Structures
-How to structure data in Zustand stores for fast list rendering, multi-detail caching, and ergonomic optimistic updates.
-
-## Core Principles
-
-### โœ… DO
-
-1. **Separate List and Detail** โ€” different structures for list pages and detail pages
-2. **Use Map for Details** โ€” cache multiple detail pages with `Record<string, Detail>`
-3. **Use Array for Lists** โ€” simple arrays for list display
-4. **Types from `@lobechat/types`** โ€” never use `@lobechat/database` types in stores
-5. **Distinguish List and Detail types** โ€” List types may have computed UI fields
-
-### โŒ DON'T
-
-1. **Don't use a single detail object** โ€” can't cache multiple pages
-2. **Don't mix List and Detail types** โ€” they have different purposes
-3. **Don't use database types** โ€” use types from `@lobechat/types`
-4. **Don't use Map for lists** โ€” simple arrays are sufficient
-
----
-
-## Type Definitions
-
-Each entity gets its own file under `@lobechat/types/`. Each file exports two types:
-
-- **Detail type** โ€” full entity, including heavy fields (rubrics, content, editor state, โ€ฆ)
-- **List item type** โ€” a **subset** that excludes heavy fields, may add computed UI fields (counts, timestamps formatted for display)
-
-**Important:** the List type is a **subset**, not an `extends` of Detail. Extending pulls the heavy fields right back in.
-
-> See [`references/types.md`](./references/types.md) for full worked examples (Benchmark, Document) and the heavy-field exclusion checklist.
-
----
-
-## When to Use Map vs Array
-
-### Use Map + Reducer โ€” for Detail Data
-
-โœ… Detail page data caching โ€” multiple detail pages cached simultaneously
-โœ… Optimistic updates โ€” update UI before API responds
-โœ… Per-item loading states โ€” track which items are being updated
-โœ… Multi-page navigation โ€” user can switch between details without refetching
-
-```typescript
-benchmarkDetailMap: Record<string, AgentEvalBenchmark>;
-```
-
-Examples: benchmark detail pages, dataset detail pages, user profiles.
-
-### Use Simple Array โ€” for List Data
-
-โœ… List display โ€” lists, tables, cards
-โœ… Refresh as a whole โ€” entire list refreshes together
-โœ… No per-item updates โ€” no need to mutate individual rows in place
-โœ… Simple data flow โ€” fewer moving parts
-
-```typescript
-benchmarkList: AgentEvalBenchmarkListItem[];
-```
-
-Examples: benchmark list, dataset list, user list.
-
----
-
-## State Structure Pattern
-
-```typescript
-// src/store/eval/slices/benchmark/initialState.ts
-import type { AgentEvalBenchmark, AgentEvalBenchmarkListItem } from '@lobechat/types';
-
-export interface BenchmarkSliceState {
- // List โ€” simple array
- benchmarkList: AgentEvalBenchmarkListItem[];
- benchmarkListInit: boolean;
-
- // Detail โ€” map for multi-entity caching
- benchmarkDetailMap: Record<string, AgentEvalBenchmark>;
- loadingBenchmarkDetailIds: string[]; // per-item loading
-
- // Mutation states (drive form-level UI)
- isCreatingBenchmark: boolean;
- isUpdatingBenchmark: boolean;
- isDeletingBenchmark: boolean;
-}
-
-export const benchmarkInitialState: BenchmarkSliceState = {
- benchmarkList: [],
- benchmarkListInit: false,
- benchmarkDetailMap: {},
- loadingBenchmarkDetailIds: [],
- isCreatingBenchmark: false,
- isUpdatingBenchmark: false,
- isDeletingBenchmark: false,
-};
-```
-
----
-
-## Reducer Pattern (for Detail Map)
-
-When the Detail Map needs optimistic updates (i.e. the user edits a row and the UI should reflect it before the server confirms), wire a typed reducer instead of inlining `set` calls. This keeps mutations testable and the dispatch surface small.
-
-> See [`references/reducer.md`](./references/reducer.md) for the full discriminated-union action types, the `produce`-based reducer, and the `internal_dispatch*` slice methods that connect them to Zustand.
-
----
-
-## Data Structure Comparison
-
-### โŒ WRONG โ€” Single Detail Object
-
-```typescript
-interface BenchmarkSliceState {
- benchmarkDetail: AgentEvalBenchmark | null;
- isLoadingBenchmarkDetail: boolean;
-}
-```
-
-Problems:
-
-- Can only cache one detail page at a time
-- Switching between details forces refetch
-- No optimistic updates
-- No per-item loading states
-
-### โœ… CORRECT โ€” Separate List and Detail
-
-```typescript
-interface BenchmarkSliceState {
- benchmarkList: AgentEvalBenchmarkListItem[];
- benchmarkListInit: boolean;
-
- benchmarkDetailMap: Record<string, AgentEvalBenchmark>;
- loadingBenchmarkDetailIds: string[];
-
- isCreatingBenchmark: boolean;
- isUpdatingBenchmark: boolean;
- isDeletingBenchmark: boolean;
-}
-```
-
-Benefits:
-
-- Cache multiple detail pages
-- Fast navigation between cached details
-- Optimistic updates via reducer
-- Per-item loading states
-- Clear separation of concerns
-
----
-
-## Component Usage
-
-### Accessing List Data
-
-```tsx
-const BenchmarkList = () => {
- const benchmarks = useEvalStore((s) => s.benchmarkList);
- const isInit = useEvalStore((s) => s.benchmarkListInit);
-
- if (!isInit) return <Loading />;
- return (
- <div>
- {benchmarks.map((b) => (
- <BenchmarkCard key={b.id} name={b.name} testCaseCount={b.testCaseCount} />
- ))}
- </div>
- );
-};
-```
-
-### Accessing Detail Data
-
-```tsx
-const BenchmarkDetail = () => {
- const { benchmarkId } = useParams<{ benchmarkId: string }>();
-
- const benchmark = useEvalStore((s) =>
- benchmarkId ? s.benchmarkDetailMap[benchmarkId] : undefined,
- );
- const isLoading = useEvalStore((s) =>
- benchmarkId ? s.loadingBenchmarkDetailIds.includes(benchmarkId) : false,
- );
-
- if (!benchmark) return <Loading />;
- return (
- <div>
- <h1>{benchmark.name}</h1>
- {isLoading && <Spinner />}
- </div>
- );
-};
-```
-
-### Using Selectors (Recommended)
-
-```typescript
-// src/store/eval/slices/benchmark/selectors.ts
-export const benchmarkSelectors = {
- getBenchmarkDetail: (id: string) => (s: EvalStore) => s.benchmarkDetailMap[id],
- isLoadingBenchmarkDetail: (id: string) => (s: EvalStore) =>
- s.loadingBenchmarkDetailIds.includes(id),
-};
-
-// In component
-const benchmark = useEvalStore(benchmarkSelectors.getBenchmarkDetail(benchmarkId!));
-const isLoading = useEvalStore(benchmarkSelectors.isLoadingBenchmarkDetail(benchmarkId!));
-```
-
----
-
-## Decision Tree
-
-```text
-Need to store data?
-โ”‚
-โ”œโ”€ Is it a LIST for display?
-โ”‚ โ””โ”€ โœ… Use simple array: `xxxList: XxxListItem[]`
-โ”‚ - May include computed fields
-โ”‚ - Refreshed as a whole
-โ”‚ - No optimistic updates needed
-โ”‚
-โ””โ”€ Is it DETAIL page data?
- โ””โ”€ โœ… Use Map: `xxxDetailMap: Record<string, Xxx>`
- - Cache multiple details
- - Support optimistic updates
- - Per-item loading states
- - Requires reducer for mutations
-```
-
----
-
-## Checklist
-
-When designing store state structure:
-
-- [ ] **Organize types by entity** in separate files (e.g. `benchmark.ts`, `agentEvalDataset.ts`)
-- [ ] Create **Detail** type (full entity with all fields including heavy ones)
-- [ ] Create **ListItem** type:
- - [ ] Subset of Detail (exclude heavy fields)
- - [ ] May include computed statistics for UI
- - [ ] **NOT** `extends` Detail
-- [ ] Use **array** for list data: `xxxList: XxxListItem[]`
-- [ ] Use **Map** for detail data: `xxxDetailMap: Record<string, Xxx>`
-- [ ] Per-item loading: `loadingXxxDetailIds: string[]`
-- [ ] **Reducer** for detail map if optimistic updates needed (see [`references/reducer.md`](./references/reducer.md))
-- [ ] **Internal dispatch** and **loading** methods
-- [ ] **Selectors** for clean access (optional but recommended)
-- [ ] Document in comments which fields are excluded from List and why
-
----
-
-## Best Practices
-
-1. **File organization** โ€” one entity per file, not mixed
-2. **List is a subset** โ€” ListItem excludes heavy fields, does not `extends` Detail
-3. **Clear naming** โ€” `xxxList` for arrays, `xxxDetailMap` for maps
-4. **Consistent patterns** โ€” all detail maps follow the same shape
-5. **Type safety** โ€” never use `any`, always use proper types
-6. **Document exclusions** โ€” comment which fields are excluded and why
-7. **Selectors** โ€” encapsulate access patterns
-8. **Loading states** โ€” per-item for details, global for mutations
-9. **Immutability** โ€” use Immer in reducers
-
-### Common Mistakes to Avoid
-
-โŒ **DON'T extend Detail in List:**
-
-```typescript
-// Wrong โ€” pulls heavy fields back in
-export interface BenchmarkListItem extends Benchmark {
- testCaseCount?: number;
-}
-```
-
-โœ… **DO create separate subset:**
-
-```typescript
-export interface BenchmarkListItem {
- id: string;
- name: string;
- // ... only necessary fields
- testCaseCount?: number; // Computed
-}
-```
-
-โŒ **DON'T mix entities in one file:**
-
-```text
-// Wrong โ€” all entities in agentEvalEntities.ts
-```
-
-โœ… **DO separate by entity:**
-
-```text
-// Correct โ€” separate files
-// benchmark.ts
-// agentEvalDataset.ts
-// agentEvalRun.ts
-```
-
----
-
-## Related Skills
-
-- `data-fetching-architecture` โ€” how to fetch and update this data
-- `zustand` โ€” general Zustand patterns
+Read [Zustand data structures](../zustand/references/data-structures.md) for
+list/detail types, maps, reducers and shared type sources. The `zustand` skill
+is the automatic entry for store work.
diff --git a/.agents/skills/store-data-structures/agents/openai.yaml b/.agents/skills/store-data-structures/agents/openai.yaml
new file mode 100644
index 00000000000..5b1f887a913
--- /dev/null
+++ b/.agents/skills/store-data-structures/agents/openai.yaml
@@ -0,0 +1,2 @@
+policy:
+ allow_implicit_invocation: false
diff --git a/.agents/skills/testing/SKILL.md b/.agents/skills/testing/SKILL.md
index 307cd8796f0..cfe27784776 100644
--- a/.agents/skills/testing/SKILL.md
+++ b/.agents/skills/testing/SKILL.md
@@ -1,6 +1,6 @@
---
name: testing
-description: 'Vitest testing guide. Use when writing or updating tests, fixing failing tests, improving coverage, debugging test issues, or setting up mocks.'
+description: 'Use for Vitest tests, mocks, coverage and failing-test diagnosis.'
user-invocable: false
---
@@ -39,49 +39,10 @@ cd packages/database && TEST_SERVER_DB=1 bunx vitest run --silent='passed-only'
## Core Principles
-1. **Prefer `vi.spyOn` over `vi.mock`** - More targeted, easier to maintain
-2. **Tests must pass type check** - Run `bun run type-check` after writing tests
-3. **After 1-2 failed fix attempts, stop and ask for help**
-4. **Test behavior, not implementation details**
-5. **Regression tests for bug fixes** - After fixing a bug, add a regression test that fails before the fix and passes after, to prevent recurrence. **Skip** pure style/CSS fixes (selector, hover, mask, spacing, color) when the only practical assertion would be source-string matching on the stylesheet โ€” that is not a regression test worth shipping.
-6. **No new component tests** - Only update existing React component tests. Complex logic should be extracted into hooks and tested there instead
-7. **All source changes before any test changes** - Complete all source file edits first, then update tests in a separate pass. Interleaving disrupts reasoning about the source changes, especially across many files
-
-## Basic Test Structure
-
-```typescript
-import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
-
-beforeEach(() => {
- vi.clearAllMocks();
-});
-
-afterEach(() => {
- vi.restoreAllMocks();
-});
-
-describe('ModuleName', () => {
- describe('functionName', () => {
- it('should handle normal case', () => {
- // Arrange โ†’ Act โ†’ Assert
- });
- });
-});
-```
-
-## Mock Patterns
-
-```typescript
-// โœ… Spy on direct dependencies
-vi.spyOn(messageService, 'createMessage').mockResolvedValue('id');
-
-// โœ… Use vi.stubGlobal for browser APIs
-vi.stubGlobal('Image', mockImage);
-vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:mock');
-
-// โŒ Avoid mocking entire modules globally
-vi.mock('@/services/chat'); // Too broad
-```
+1. **Prefer `vi.spyOn` over `vi.mock`** - More targeted, easier to maintain. The root Vitest configs do not restore mocks automatically; restore spies in test cleanup with `vi.restoreAllMocks()`.
+2. **Test behavior, not implementation details**
+3. **Regression tests for bug fixes** - Include a regression test that fails without the fix and passes with it; write the failing test first when the failure is easy to reproduce. **Skip** pure style/CSS fixes (selector, hover, mask, spacing, color) when the only practical assertion would be source-string matching on the stylesheet โ€” that is not a regression test worth shipping.
+4. **No new component tests** - Only update existing React component tests. Complex logic should be extracted into hooks and tested there instead
## UI Library Mocks (@lobehub/ui/base-ui)
@@ -146,10 +107,3 @@ When tests fail due to implementation changes (not bugs), evaluate before blindl
- Prefer **integration-level assertions** (verify final output) over **white-box assertions** (verify internal calls)
- Use `expect.objectContaining` only for stable, public-facing contracts โ€” not for internal param shapes that change with refactors
- Mock at boundaries (DB, network, external services), not between internal modules
-
-## Common Issues
-
-1. **Module pollution**: Use `vi.resetModules()` when tests fail mysteriously
-2. **Mock not working**: Check setup position and use `vi.clearAllMocks()` in beforeEach
-3. **Test data pollution**: Clean database state in beforeEach/afterEach
-4. **Async issues**: Wrap state changes in `act()` for React hooks
diff --git a/.agents/skills/trpc-router/SKILL.md b/.agents/skills/trpc-router/SKILL.md
index 6a5465fc6e8..61fb0a6a858 100644
--- a/.agents/skills/trpc-router/SKILL.md
+++ b/.agents/skills/trpc-router/SKILL.md
@@ -1,6 +1,6 @@
---
name: trpc-router
-description: 'TRPC router development guide. Use when creating or modifying apps/server/src/routers, adding procedures, or implementing server-side API endpoints.'
+description: 'Use for server TRPC routers, procedures and API endpoints in apps/server/src/routers.'
user-invocable: false
---
diff --git a/.agents/skills/typescript/SKILL.md b/.agents/skills/typescript/SKILL.md
index 0de21e8366e..fa19a8d05a9 100644
--- a/.agents/skills/typescript/SKILL.md
+++ b/.agents/skills/typescript/SKILL.md
@@ -1,6 +1,6 @@
---
name: typescript
-description: 'LobeHub TypeScript style and type-safety guide. Use when editing TS/TSX/MTS, fixing types, choosing interface vs type, avoiding any/object, import type, async flow, or ts-expect-error.'
+description: 'Use for TypeScript style and type safety when editing TS/TSX/MTS, including imports, async code and error suppression.'
user-invocable: false
---
@@ -28,41 +28,15 @@ user-invocable: false
## Imports
-- This project uses `simple-import-sort/imports` and `consistent-type-imports` (`fixStyle: 'separate-type-imports'`)
-
-- **Separate type imports**: always use `import type { ... }` for type-only imports, NOT `import { type ... }` inline syntax
-
-- When a file already has `import type { ... }` from a package and you need to add a value import, keep them as **two separate statements**:
-
- ```ts
- import type { ChatTopicBotContext } from '@lobechat/types';
- import { RequestTrigger } from '@lobechat/types';
- ```
-
-- Within each import statement, specifiers are sorted **alphabetically by name**
+- Let lint enforce `simple-import-sort/imports` and `consistent-type-imports` with separate `import type` statements (`fixStyle: 'separate-type-imports'`).
## Code Structure
-- Prefer object destructuring
-- Use consistent, descriptive naming; avoid obscure abbreviations
-- Replace magic numbers/strings with well-named constants
-- Defer formatting to tooling
- Prefer **named exports** over `export default` โ€” keeps refactor renames and IDE auto-import in sync, and avoids the `default` re-naming drift you get with `import Foo from './foo'`. Reserve `export default` for files where the framework requires it (Next.js page/route/layout, React.lazy targets, config files like `vitest.config.ts`). The codebase still has many `export default` occurrences โ€” that's historical debt, not a pattern to copy; do not model new code on existing `export default` usage outside the framework-required cases above
-- Before adding local helpers for common guards/parsing/normalization (record checks, string extraction, empty-string handling, timing helpers, JSON-safe utilities, etc.), search `packages/utils` first. If the helper already exists or clearly belongs there, import it from `@lobechat/utils` (or the relevant `@lobechat/utils/*` subpath) instead of duplicating tiny helpers across feature files.
-
-## UI and Theming
-
-- Use `@lobehub/ui`, Ant Design components instead of raw HTML tags
-- Design for dark mode and mobile responsiveness
-- Use `antd-style` token system instead of hard-coded colors
-
-## Performance
-
-- Query only required columns from database
## Reusability
-- Reuse existing utils in `packages/utils` or installed npm packages
+- Before adding guards, parsing, normalization, timing, or JSON-safe helpers, search `packages/utils` and installed packages. Reuse `@lobechat/utils` or its relevant subpath instead of duplicating helpers across features.
- Do not hand-roll reusable record/object-map guards such as `typeof value === 'object' && value !== null`; import helpers like `isRecord`, `isPlainRecord`, `isObjectLike`, `toRecord`, `pickString`, `UnknownRecord`, etc. from `@lobechat/utils/object`.
- Assign `Date.now()` to a constant once and reuse for consistency
diff --git a/.agents/skills/upstash-workflow/SKILL.md b/.agents/skills/upstash-workflow/SKILL.md
index 11948e9bc6d..a8dc01f10ab 100644
--- a/.agents/skills/upstash-workflow/SKILL.md
+++ b/.agents/skills/upstash-workflow/SKILL.md
@@ -1,6 +1,6 @@
---
name: upstash-workflow
-description: 'LobeHub Upstash Workflow and QStash guide. Use for async workflows, process/paginate/execute fan-out, serve handlers, context.run/call/sleep, or workflow triggers.'
+description: 'Use for Upstash Workflow/QStash handlers, triggers, durable steps and async fan-out.'
user-invocable: false
---
diff --git a/.agents/skills/ux-audit/SKILL.md b/.agents/skills/ux-audit/SKILL.md
index 5aab0539614..e99778df0c8 100644
--- a/.agents/skills/ux-audit/SKILL.md
+++ b/.agents/skills/ux-audit/SKILL.md
@@ -232,8 +232,10 @@ An audit is not finished when the findings are written โ€” it is finished when t
parent (per-page container issue โ†’ one sub-issue per finding).
- **Generalizable gaps โ†’ ๅ›ž็Œ `ux` (mandatory).** Every run **must** close the loop back into
the `ux` skill: for each finding that generalizes beyond this surface, add / strengthen a
- `ux` checklist item (rule + โœ…/โŒ example in the right module, **and** mirror a line into the
- ux Quick review), citing the audited surface as the โŒ example. This is what makes the audit
+ `ux` checklist item (rule + โœ…/โŒ example in the right module), citing the audited surface
+ as the โŒ example. Add or update a short cue in the ux Quick review only when its existing
+ cues do not cover the requirement; keep examples and implementation details in the module.
+ This is what makes the audit
_continuous_ โ€” each run leaves the checklists sharper than it found them. If a run genuinely
surfaces **no** generalizable gap, say so explicitly in the report's Skill-feedback section
(only validated-existing-rule instances) โ€” silence is not an acceptable close.
diff --git a/.agents/skills/ux/SKILL.md b/.agents/skills/ux/SKILL.md
index 66c74ffc608..b373b0274cb 100644
--- a/.agents/skills/ux/SKILL.md
+++ b/.agents/skills/ux/SKILL.md
@@ -1,6 +1,6 @@
---
name: ux
-description: 'LobeHub product design values / principles / checklists. Use whenever the work touches user-interface features or implementation โ€” designing or building any user-facing flow โ€” to get better UX results.'
+description: 'Use for product design principles and UX checks when designing or implementing user-facing flows.'
user-invocable: false
---
@@ -95,68 +95,65 @@ Read + Edit + Act) โ€” walk each that applies.
## Quick review checklist
-The one-screen scan. Each line links back to a module above for the full rule + examples.
+Use this scan to identify applicable checks, then read the linked module for its full requirements and examples. Keep implementation details and case histories in those modules, not duplicated here.
**Read โ€” viewing data & lists** ([read.md](references/read.md))
-- [ ] Empty / loading / error states are all designed; empty is a real page with a CTA. Always-rendered chrome (toolbar/header) still gets a body empty state. If the `Empty` component ships a `search`/no-match variant, **wire it** โ€” don't render `<Empty/>` bare so a zero-result search shows the first-run onboarding.
-- [ ] Error is checked before the empty branch โ€” a failed fetch never renders as empty (read `error`, don't coerce `data ?? [] โ†’ Empty`); a detail page reads `error` before falling to `NotFound` (failed-to-load โ‰  deleted/404). On a **metrics/dashboard** surface the failure default is a zero-valued object (`?? {โ€ฆ:0}`) that renders as a confident `$0` โ€” read `error` before any aggregate, don't fall through to zeros. A list **merged from a fetched set + a static/frontend set** (`[...fetched, ...placeholders]`) branches `error` before merging โ€” the static half keeps `length > 0`, so a failed fetch renders a plausible partial catalog neither the empty guard nor an error-unread call site catches (channel).
-- [ ] List designed across 1 โ†’ 10k rows (virtual scroll / pagination / batch as needed).
-- [ ] Search / filter over a paginated list queries the full set server-side, not just the loaded page (no false "no results" for unfetched rows). Server-side coverage isn't just the search box โ€” **sort, facet filters, the count badges, and any "act on the filtered set" bulk op** run over the full set too; server-side search + client-side sort/filter/counts still false-empties, mis-orders across pages, and under-counts (topics).
-- [ ] Capped/scrollable/virtualized list scrolls the restored active item into view on mount (`block: 'nearest'`, re-run after async rows mount).
-- [ ] Pickers show all valid targets (default/inbox included); empty = truly none.
-- [ ] Large numbers roll the unit at each 1000ร— (Kโ†’Mโ†’Bโ†’T), never a coefficient โ‰ฅ 1000; use the shared `formatUsageValue` / `formatShortenNumber`.
-- [ ] Multi-tab/view surface lands on the tab the entry intent implies (and falls back to a populated view, decided from resolved state); a manual pick sticks.
-- [ ] A data-aware shortcut never makes the collection hub or its collection-level actions unreachable.
-- [ ] Live/polling feed signals new items + offers manual refresh, doesn't reorder under the user, and shows a failed refresh distinctly (not as empty). A bulk/destructive control derived from the live-status map (close-idle / clear-inactive) gates on the query's loaded/error state โ€” "unknown/errored" is ineligible, never treated as the inactive value. Conditional polling starts from **reactive state** (`shouldPoll` โ†’ `refreshInterval`), not a function-form `refreshInterval` that never schedules a first timer when its initial value is `0`.
-- [ ] A surface with many navigable entries (a big settings area, a long list) offers search / filter / jump, not browse-only โ€” named as a class norm so an absent box is caught.
-- [ ] Marketplace / registry browse cards carry owned/installed state on the tile (not only on the detail) and trust/verified badges via one card contract, consistent across sibling registries; contribute leads to an in-app submit, not an external repo.
-- [ ] A sidebar / nav / master-detail **list row** composes the canonical `NavItem` (+ `Accordion` / `GroupedAccordion` for groups, `Block variant='filled'` for active), not a hand-rolled `<div>`/`<button>`/`<input>` + bespoke CSS โ€” else the hover/active highlight misaligns from the content box, content bleeds to the panel edge, the search/rename/action-reveal drift from every sibling panel, and the list stays a flat ungrouped dump. Grep `NavItem` before building.
-- [ ] A persistent create/compose affordance above a list is the hero only while the list is **empty**; once populated it doesn't bury the records โ€” cap the editor height (max-height + internal scroll) and/or default it to collapsed when the list has data, so the records keep Center Stage.
-- [ ] A status group/label is true for **every** member โ€” don't fold a distinct lifecycle state (scheduled/queued/snoozed) under a label that asserts another (running/in-progress); give it its own group or a neutral label.
-- [ ] An embedded/quoted document (evidence, log, attached report) folds to a **titled row** (first meaningful line as the label) expanding to full text โ€” not a first-N-px cropped preview with a fade; expanded, it stays in a quiet container with a capped heading scale so it never masquerades as page structure.
+- [ ] Distinguish first-use empty, no search matches, loading, and failure; include a useful body state beneath persistent chrome.
+- [ ] Handle fetch errors before empty, not-found, zero-valued aggregates, or static fallback entries can mask them.
+- [ ] Support lists from 1 to 10k rows with pagination, virtualization, and batch operations as needed.
+- [ ] Search, filters, sort, counts, and bulk scope cover the full dataset, not only loaded pages.
+- [ ] Scroll restored selections into view after their rows exist, without moving already-visible selections.
+- [ ] Pickers include every valid target, including default/inbox options.
+- [ ] Use shared number formatters with K/M/B/T rollover; never display a coefficient โ‰ฅ 1000.
+- [ ] Choose the initial view from entry intent and resolved data; preserve manual choices and access to collection-level actions.
+- [ ] Live feeds signal updates, allow manual refresh, preserve reading position, and distinguish refresh failure.
+- [ ] Conditional polling starts reliably; unknown or failed live status never qualifies an item for destructive bulk actions.
+- [ ] Large navigation surfaces offer search, filter, or jump.
+- [ ] Registry cards consistently show owned/installed and trust states; contribution leads to in-app submission.
+- [ ] Reuse canonical list rows and grouping components; see Read ยง1.10 and the **react** skill.
+- [ ] Keep populated lists visible beneath persistent composers; cap or collapse growing editors.
+- [ ] Status labels describe every member accurately.
+- [ ] Embedded documents collapse to titled rows and expand to full text with subordinate typography.
**Edit โ€” entering & changing content** ([edit.md](references/edit.md))
-- [ ] Editors back up in-progress input to durable storage (survives reload, not in-memory only) and recover it after refresh/crash/failed-save; destructive exits warn, never silently discard โ€” including **switching the active item in a master-detail** (a shared form `resetFields()` on selection change silently wipes unsaved input, worst when it's pasted secrets โ€” channel).
-- [ ] Input affordances are stable: static placeholder, no clickable/retrievable content hidden in it.
+- [ ] Persist and recover drafts through reloads, failed saves, and item switches; warn or save before destructive exits.
+- [ ] Keep placeholders stable and meaningful content retrievable outside them.
**Act โ€” operations, flows & buttons** ([act.md](references/act.md))
-- [ ] Action leads the user forward; success offers a primary "go to result".
-- [ ] Terminal status screen (success / error `Result`) carries an action: error โ†’ escape hatch (retry / back), success โ†’ close / go-to-result; no bare `Result` without `extra`, and "auto-closing in Ns" copy only when the close can actually fire.
-- [ ] A result that changes the next step lands in a persistent state (screen / inline), not just a transient toast; "link sent" names the destination + offers resend, failures keep context + offer retry.
-- [ ] Bulk action has a single-item entry (and vice versa).
-- [ ] Async/bulk/irreversible action: confirm โ†’ in-progress (locked) โ†’ done/error. But a **slow but atomic** confirm-gated op (device/file delete, git op, seconds-long call) closes the confirm **immediately** (non-blocking `onOk`) and shows progress on the **originating surface** (optimistic removal / row spinner), not a confirm dialog held spinning on the round-trip โ€” the modal is not the progress surface.
-- [ ] A long-running / costly async op (generation / export / large upload) offers **Cancel while it runs** (aborts the work, not just delete-after-the-fact) and keeps an in-place **Retry** on error โ€” named as a generation-class norm so an absent Cancel is caught.
-- [ ] Optimistic create / rename / duplicate surfaces failure (caller catches + toasts); never a silent rollback.
-- [ ] Job-control (run / pause / stop / retry) surfaces start/stop failure โ€” a `catch` that only `console.error`s + optimistic-status rollback reads as a dead button; toast at the store-action boundary so every trigger inherits it.
-- [ ] Cross-surface coherence: an entity shown in both a list and its detail stays in sync on edit โ€” shared normalized store or invalidate the sibling (not a gated field subset); a per-surface review misses this seam, so check it explicitly.
-- [ ] Scrollable content + actions/status โ†’ pin them in a fixed footer/header, not inside the scroll area (verify at the overflowing state).
-- [ ] Exactly one primary button per surface โ€” and it's the visually dominant control (back / cancel / secondary never out-weighs it; verify on the rendered screen, not from `variant`).
-- [ ] Listed entities have their full lifecycle (not display-only); ops match source (built-in / installed / custom). A protective marker (pin / keep / lock) is honored by every removal path (bulk close, clear-idle, auto-cleanup) โ€” a marker that gates nothing is a decorative no-op.
-- [ ] An action that commits as a specific identity (OAuth consent, send-as, publish-to) shows the identity **and** a switch-account / re-auth path โ€” never locks the user to the currently-logged-in one.
-- [ ] Unrecoverable / wide-blast action (clear-all, delete-account, wipe) needs an explicit gesture (type-to-confirm / checkbox), not one-click danger; and reports partial failure, never silent half-completion.
-- [ ] A minted secret (API key / token) is shown in full once at creation (persistent reveal + Copy), hashed at rest, masked thereafter โ€” never re-revealed from a list.
-- [ ] A store of data _about the user_ (AI memory / personalization / inferred profile) offers correct-or-mark-wrong (not just blind-edit/delete), retain-without-use (per-item pause + global off-switch), export/download, and undo/soft-delete โ€” named as class norms so an absent one is caught.
+- [ ] Success leads to the result; terminal screens provide a working next action or escape.
+- [ ] Persist results that change the next step; keep transient acknowledgements in toasts.
+- [ ] Provide both bulk and single-item action entry points.
+- [ ] Show confirmation, locked progress, and outcome where required. Slow atomic operations close the confirmation and show progress on the originating surface.
+- [ ] Long-running or costly operations support cancellation while running and retry after failure.
+- [ ] Surface optimistic mutation and job-control failures; never silently roll back.
+- [ ] Keep list and detail views synchronized after edits.
+- [ ] Pin actions and status outside scrollable content; verify the overflowing state.
+- [ ] Give each surface one visually dominant primary action.
+- [ ] Provide the lifecycle operations appropriate to each entity's source; honor pin/keep/lock on every removal path.
+- [ ] Show the acting identity and an account-switch or re-authentication path.
+- [ ] Require a deliberate gesture for unrecoverable or broad destructive actions and report partial failure.
+- [ ] Reveal newly minted secrets once with Copy, hash them at rest, and mask subsequent views.
+- [ ] User-memory/profile stores support correction, retaining without use, export, and undo or soft-delete.
**Feedback โ€” loading & system response** ([feedback.md](references/feedback.md))
-- [ ] No antd `Spin`; use `NeuralNetworkLoading` / project loaders.
-- [ ] A whole-surface skeleton (route fallback, sidebar panel) matches the settled layout's **structural anchors** โ€” header height, fixed nav block, body start, first group title โ€” measured from the rendered DOM, never derived by reading the JSX. Conditional chrome that changes height (platform flags) is branched with the same condition, a shell with per-route panels drives its skeleton from a per-route shape (a panel with no body gets a skeleton with no body), and data-driven lists align only up to the first group title.
-- [ ] Every loading state can fail: on error or timeout, show a failed state with a Reload/Retry action โ€” never an infinite spinner. In an auto-dismissing surface (upload dock / progress toast), the countdown clears **success only** โ€” a failed item persists with Retry. An error state / retry action that's **modeled in the store but consumed by no surface** (`isXError` selector / `retryX` action with zero `rg` call sites) is still a missing error state โ€” a built-but-orphaned path is a permanent skeleton at the pixel. A **load-more / infinite-scroll** page fetch that fails shows an inline Retry at the list tail (distinct from end-of-list), never a silently vanished "loading more" row with `hasMore` still true that an `IntersectionObserver` re-fires into a silent retry loop (topics).
-- [ ] A compound gate waiting on a secondary/dependent fetch gates on its **in-flight** flag and releases on settled (data / resolved-`null` / error) โ€” never on the dependency being present in a map, or an absent-by-design dependency hangs it forever. An error branch **ordered after** a data-presence gate (`{error && โ€ฆ}` below `if (isLoading = !map[id]) return <Skeleton/>`) is unreachable on first-load failure โ€” it paints only on revalidation, and a resolved-`null` not-found hangs the same permanent skeleton; check error/not-found **before** the gate.
-- [ ] An awaited write that gates navigation/advance resets its busy flag in `finally` + offers retry โ€” a failed write never permanently disables the forward/Back control.
-- [ ] Autosave surfaces a save-state (saving โ†’ saved โ†’ failed with retry), never a silent write; the save-state enum actually includes a `failed` variant (a catch that resets to `idle` is a silent write); one save-feedback convention across a multi-field surface, ideally in the shared form wrapper.
-- [ ] Error copy is written for a human, not a log line (ยง4.5): no internal id (`tpc_โ€ฆ` / uuid / `#N` seq) or log framing (`Execution failed:` / `Error:`) in the headline โ€” the id rides a structured field powering "View run", the framing is localized via i18n at the view, and the body doesn't repeat identity the meta row already shows. A **deterministic-cause** failure (budget/quota โ†’ top-upใƒปupgrade; permission โ†’ request access) leads with the **remedy action**, not a bare Retry that just re-fails.
-- [ ] Capability-gated feature warns (soft, reactive, load-gated) when the model can't deliver it; copy gives the remedy.
+- [ ] Use project loaders rather than antd `Spin`.
+- [ ] Match skeleton structure to measured rendered layouts, including platform and route variants.
+- [ ] Loading and load-more failures have visible recovery paths; failed items persist rather than auto-dismiss.
+- [ ] Dependent-fetch gates release on settled data, absence, or error; error/not-found branches remain reachable.
+- [ ] Failed awaited writes release busy controls; autosave exposes saving, saved, and failed states with retry.
+- [ ] Write localized, human-readable errors; keep internal IDs in structured inspection fields and lead with the remedy for deterministic failures.
+- [ ] Capability warnings are reactive and wait for resolved configuration; distinguish model choices from platform limitations.
**Grow โ€” discoverability & progressive disclosure** ([grow.md](references/grow.md))
-- [ ] Advanced capability is progressively disclosed / discoverable at the moment of need.
-- [ ] A control that borrows a keyboard/CLI idiom (numbered `1`/`2`/`3` chips, `โŒ˜K` badge, arrow-nav, keycap hint) actually wires those keys โ€” or is restyled so it doesn't imply an absent shortcut; a keycap-looking chip with no handler is a false affordance, worst in a surface ported from a CLI. Confirm the keys fire at L3.
-- [ ] A config surface for a feature with its own data/management area links to it in-context (close the config โ†’ manage loop) โ€” not just a promise in copy.
-- [ ] Multi-step flow (>2 steps: wizard/onboarding) shows a step/progress indicator (position + total) and keeps non-essential steps skippable with a visible escape hatch.
+- [ ] Reveal advanced capabilities when useful without cluttering the novice path.
+- [ ] Keyboard hints correspond to working shortcuts, verified in the running UI.
+- [ ] Configuration surfaces link to the feature's data or management area.
+- [ ] Flows with more than two steps show progress and keep non-essential steps skippable with an escape.
## Related skills
diff --git a/.agents/skills/ux/references/read.md b/.agents/skills/ux/references/read.md
index d9f939ca48c..76379379e49 100644
--- a/.agents/skills/ux/references/read.md
+++ b/.agents/skills/ux/references/read.md
@@ -176,15 +176,6 @@ _each_ against the full set, not just the search input.
> can occur here. (This is why the surface's only read-side gap is failure handling, not
> query correctness.)
-> โŒ The Pages "all pages" drawer filters `displayDocuments` with a client-side
-> `title/content.includes(keyword)` over the loaded set **and disables load-more while
-> searching**, so searching for a page past the loaded window returns "no results" though it
-> exists (`AllPagesDrawer/Content.tsx`). โœ… Send the keyword to the server query and page
-> through matches.
-> โœ… **Memory** (่ฎฐๅฟ†) does it right: each list tab passes `q` straight into the paginated
-> `queryMemories` server call (`memory/contexts/index.tsx:57-62`, mirrored per tab), so search spans
-> the whole set โ€” no false "no results" for unfetched rows.
-
**Checklist**
- [ ] List designed across 1 โ†’ 10k rows (plain โ†’ pagination โ†’ virtual scroll). _(Certainty)_
diff --git a/.agents/skills/zustand/SKILL.md b/.agents/skills/zustand/SKILL.md
index 0fcc347d566..c7905ac0e84 100644
--- a/.agents/skills/zustand/SKILL.md
+++ b/.agents/skills/zustand/SKILL.md
@@ -1,11 +1,18 @@
---
name: zustand
-description: 'LobeHub Zustand store conventions. Use when editing src/store, store slices, public/internal actions, dispatch actions, flattenActions, optimistic updates, selectors, maps, or class action migration.'
+description: 'Use for Zustand stores: list/detail splits, state type sources, slices, actions, reducers, selectors, optimistic updates and class-action composition.'
user-invocable: false
---
# LobeHub Zustand State Management
+## State Shapes and Types
+
+- Import shared store types from `@lobechat/types`, not `@lobechat/database`.
+- Keep lightweight list-item types separate from full detail types; list types must not extend heavy detail types.
+- Use arrays for whole-list display and id-keyed maps for cached details, with per-item loading state where needed.
+- Before choosing list/detail shapes, normalized maps or state type sources, read [Data structures](references/data-structures.md). Its worked examples load only when relevant.
+
## Action Type Hierarchy
### 1. Public Actions
diff --git a/.agents/skills/zustand/references/data-structures.md b/.agents/skills/zustand/references/data-structures.md
new file mode 100644
index 00000000000..7ab99386ea2
--- /dev/null
+++ b/.agents/skills/zustand/references/data-structures.md
@@ -0,0 +1,304 @@
+# LobeHub Store Data Structures
+
+How to structure data in Zustand stores for fast list rendering, multi-detail caching, and ergonomic optimistic updates.
+
+These examples illustrate state shapes. For request lifecycle, loading, errors and retries,
+follow [data-fetching-architecture](../../data-fetching-architecture/SKILL.md).
+
+## Core Principles
+
+### โœ… DO
+
+1. **Separate List and Detail** โ€” different structures for list pages and detail pages
+2. **Use Map for Details** โ€” cache multiple detail pages with `Record<string, Detail>`
+3. **Use Array for Lists** โ€” simple arrays for list display
+4. **Types from `@lobechat/types`** โ€” never use `@lobechat/database` types in stores
+5. **Distinguish List and Detail types** โ€” List types may have computed UI fields
+
+### โŒ DON'T
+
+1. **Don't use a single detail object** โ€” can't cache multiple pages
+2. **Don't mix List and Detail types** โ€” they have different purposes
+3. **Don't use database types** โ€” use types from `@lobechat/types`
+4. **Don't use Map for lists** โ€” simple arrays are sufficient
+
+---
+
+## Type Definitions
+
+Each entity gets its own file under `@lobechat/types/`. Each file exports two types:
+
+- **Detail type** โ€” full entity, including heavy fields (rubrics, content, editor state, โ€ฆ)
+- **List item type** โ€” a **subset** that excludes heavy fields, may add computed UI fields (counts, timestamps formatted for display)
+
+**Important:** the List type is a **subset**, not an `extends` of Detail. Extending pulls the heavy fields right back in.
+
+> See [`data-structures/types.md`](./data-structures/types.md) for full worked examples (Benchmark, Document) and the heavy-field exclusion checklist.
+
+---
+
+## When to Use Map vs Array
+
+### Use Map + Reducer โ€” for Detail Data
+
+โœ… Detail page data caching โ€” multiple detail pages cached simultaneously
+โœ… Optimistic updates โ€” update UI before API responds
+โœ… Per-item loading states โ€” track which items are being updated
+โœ… Multi-page navigation โ€” user can switch between details without refetching
+
+```typescript
+benchmarkDetailMap: Record<string, AgentEvalBenchmark>;
+```
+
+Examples: benchmark detail pages, dataset detail pages, user profiles.
+
+### Use Simple Array โ€” for List Data
+
+โœ… List display โ€” lists, tables, cards
+โœ… Refresh as a whole โ€” entire list refreshes together
+โœ… No per-item updates โ€” no need to mutate individual rows in place
+โœ… Simple data flow โ€” fewer moving parts
+
+```typescript
+benchmarkList: AgentEvalBenchmarkListItem[];
+```
+
+Examples: benchmark list, dataset list, user list.
+
+---
+
+## State Structure Pattern
+
+```typescript
+// src/store/eval/slices/benchmark/initialState.ts
+import type { AgentEvalBenchmark, AgentEvalBenchmarkListItem } from '@lobechat/types';
+
+export interface BenchmarkSliceState {
+ // List โ€” simple array
+ benchmarkList: AgentEvalBenchmarkListItem[];
+ benchmarkListInit: boolean;
+
+ // Detail โ€” map for multi-entity caching
+ benchmarkDetailMap: Record<string, AgentEvalBenchmark>;
+ loadingBenchmarkDetailIds: string[]; // per-item loading
+
+ // Mutation states (drive form-level UI)
+ isCreatingBenchmark: boolean;
+ isUpdatingBenchmark: boolean;
+ isDeletingBenchmark: boolean;
+}
+
+export const benchmarkInitialState: BenchmarkSliceState = {
+ benchmarkList: [],
+ benchmarkListInit: false,
+ benchmarkDetailMap: {},
+ loadingBenchmarkDetailIds: [],
+ isCreatingBenchmark: false,
+ isUpdatingBenchmark: false,
+ isDeletingBenchmark: false,
+};
+```
+
+---
+
+## Reducer Pattern (for Detail Map)
+
+When the Detail Map needs optimistic updates (i.e. the user edits a row and the UI should reflect it before the server confirms), wire a typed reducer instead of inlining `set` calls. This keeps mutations testable and the dispatch surface small.
+
+> See [`data-structures/reducer.md`](./data-structures/reducer.md) for the full discriminated-union action types, the `produce`-based reducer, and the `internal_dispatch*` slice methods that connect them to Zustand.
+
+---
+
+## Data Structure Comparison
+
+### โŒ WRONG โ€” Single Detail Object
+
+```typescript
+interface BenchmarkSliceState {
+ benchmarkDetail: AgentEvalBenchmark | null;
+ isLoadingBenchmarkDetail: boolean;
+}
+```
+
+Problems:
+
+- Can only cache one detail page at a time
+- Switching between details forces refetch
+- No optimistic updates
+- No per-item loading states
+
+### โœ… CORRECT โ€” Separate List and Detail
+
+```typescript
+interface BenchmarkSliceState {
+ benchmarkList: AgentEvalBenchmarkListItem[];
+ benchmarkListInit: boolean;
+
+ benchmarkDetailMap: Record<string, AgentEvalBenchmark>;
+ loadingBenchmarkDetailIds: string[];
+
+ isCreatingBenchmark: boolean;
+ isUpdatingBenchmark: boolean;
+ isDeletingBenchmark: boolean;
+}
+```
+
+Benefits:
+
+- Cache multiple detail pages
+- Fast navigation between cached details
+- Optimistic updates via reducer
+- Per-item loading states
+- Clear separation of concerns
+
+---
+
+## Component Usage
+
+### Accessing List Data
+
+```tsx
+const BenchmarkList = () => {
+ const benchmarks = useEvalStore((s) => s.benchmarkList);
+ const isInit = useEvalStore((s) => s.benchmarkListInit);
+
+ if (!isInit) return <Loading />;
+ return (
+ <div>
+ {benchmarks.map((b) => (
+ <BenchmarkCard key={b.id} name={b.name} testCaseCount={b.testCaseCount} />
+ ))}
+ </div>
+ );
+};
+```
+
+### Accessing Detail Data
+
+```tsx
+const BenchmarkDetail = () => {
+ const { benchmarkId } = useParams<{ benchmarkId: string }>();
+
+ const benchmark = useEvalStore((s) =>
+ benchmarkId ? s.benchmarkDetailMap[benchmarkId] : undefined,
+ );
+ const isLoading = useEvalStore((s) =>
+ benchmarkId ? s.loadingBenchmarkDetailIds.includes(benchmarkId) : false,
+ );
+
+ if (!benchmark) return <Loading />;
+ return (
+ <div>
+ <h1>{benchmark.name}</h1>
+ {isLoading && <Spinner />}
+ </div>
+ );
+};
+```
+
+### Using Selectors (Recommended)
+
+```typescript
+// src/store/eval/slices/benchmark/selectors.ts
+export const benchmarkSelectors = {
+ getBenchmarkDetail: (id: string) => (s: EvalStore) => s.benchmarkDetailMap[id],
+ isLoadingBenchmarkDetail: (id: string) => (s: EvalStore) =>
+ s.loadingBenchmarkDetailIds.includes(id),
+};
+
+// In component
+const benchmark = useEvalStore(benchmarkSelectors.getBenchmarkDetail(benchmarkId!));
+const isLoading = useEvalStore(benchmarkSelectors.isLoadingBenchmarkDetail(benchmarkId!));
+```
+
+---
+
+## Decision Tree
+
+```text
+Need to store data?
+โ”‚
+โ”œโ”€ Is it a LIST for display?
+โ”‚ โ””โ”€ โœ… Use simple array: `xxxList: XxxListItem[]`
+โ”‚ - May include computed fields
+โ”‚ - Refreshed as a whole
+โ”‚ - No optimistic updates needed
+โ”‚
+โ””โ”€ Is it DETAIL page data?
+ โ””โ”€ โœ… Use Map: `xxxDetailMap: Record<string, Xxx>`
+ - Cache multiple details
+ - Support optimistic updates
+ - Per-item loading states
+ - Requires reducer for mutations
+```
+
+---
+
+## Checklist
+
+When designing store state structure:
+
+- [ ] **Organize types by entity** in separate files (e.g. `benchmark.ts`, `agentEvalDataset.ts`)
+- [ ] Create **Detail** type (full entity with all fields including heavy ones)
+- [ ] Create **ListItem** type:
+ - [ ] Subset of Detail (exclude heavy fields)
+ - [ ] May include computed statistics for UI
+ - [ ] **NOT** `extends` Detail
+- [ ] Use **array** for list data: `xxxList: XxxListItem[]`
+- [ ] Use **Map** for detail data: `xxxDetailMap: Record<string, Xxx>`
+- [ ] Per-item loading: `loadingXxxDetailIds: string[]`
+- [ ] **Reducer** for detail map if optimistic updates needed (see [`data-structures/reducer.md`](./data-structures/reducer.md))
+- [ ] **Internal dispatch** and **loading** methods
+- [ ] **Selectors** for clean access (optional but recommended)
+- [ ] Document in comments which fields are excluded from List and why
+
+---
+
+## Best Practices
+
+1. **File organization** โ€” one entity per file, not mixed
+2. **List is a subset** โ€” ListItem excludes heavy fields, does not `extends` Detail
+3. **Clear naming** โ€” `xxxList` for arrays, `xxxDetailMap` for maps
+4. **Consistent patterns** โ€” all detail maps follow the same shape
+5. **Type safety** โ€” never use `any`, always use proper types
+6. **Document exclusions** โ€” comment which fields are excluded and why
+7. **Selectors** โ€” encapsulate access patterns
+8. **Loading states** โ€” per-item for details, global for mutations
+9. **Immutability** โ€” use Immer in reducers
+
+### Common Mistakes to Avoid
+
+โŒ **DON'T extend Detail in List:**
+
+```typescript
+// Wrong โ€” pulls heavy fields back in
+export interface BenchmarkListItem extends Benchmark {
+ testCaseCount?: number;
+}
+```
+
+โœ… **DO create separate subset:**
+
+```typescript
+export interface BenchmarkListItem {
+ id: string;
+ name: string;
+ // ... only necessary fields
+ testCaseCount?: number; // Computed
+}
+```
+
+โŒ **DON'T mix entities in one file:**
+
+```text
+// Wrong โ€” all entities in agentEvalEntities.ts
+```
+
+โœ… **DO separate by entity:**
+
+```text
+// Correct โ€” separate files
+// benchmark.ts
+// agentEvalDataset.ts
+// agentEvalRun.ts
+```
diff --git a/.agents/skills/store-data-structures/references/reducer.md b/.agents/skills/zustand/references/data-structures/reducer.md
similarity index 97%
rename from .agents/skills/store-data-structures/references/reducer.md
rename to .agents/skills/zustand/references/data-structures/reducer.md
index d400b2a87a0..868e3f52529 100644
--- a/.agents/skills/store-data-structures/references/reducer.md
+++ b/.agents/skills/zustand/references/data-structures/reducer.md
@@ -33,9 +33,7 @@ type DeleteBenchmarkDetailAction = {
};
export type BenchmarkDetailDispatch =
- | SetBenchmarkDetailAction
- | UpdateBenchmarkDetailAction
- | DeleteBenchmarkDetailAction;
+ SetBenchmarkDetailAction | UpdateBenchmarkDetailAction | DeleteBenchmarkDetailAction;
export const benchmarkDetailReducer = (
state: Record<string, AgentEvalBenchmark> = {},
diff --git a/.agents/skills/store-data-structures/references/types.md b/.agents/skills/zustand/references/data-structures/types.md
similarity index 95%
rename from .agents/skills/store-data-structures/references/types.md
rename to .agents/skills/zustand/references/data-structures/types.md
index b3c9e51acff..8e9cc7b81d9 100644
--- a/.agents/skills/store-data-structures/references/types.md
+++ b/.agents/skills/zustand/references/data-structures/types.md
@@ -1,6 +1,6 @@
# Type Definitions in Detail
-The skill body's Type Definitions section covers the rules; this file holds the full worked examples to keep SKILL.md lean.
+The [data-shape guide](../data-structures.md#type-definitions) covers the rules; this file holds the full worked examples.
## Organization
diff --git a/AGENTS.md b/AGENTS.md
index 49a88811a72..5fe0b4eda0d 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -15,62 +15,21 @@ Guidelines for using AI coding agents in this opensource LobeHub repository.
`AGENTS.md` owns repository-wide architecture and workflow. Keep detailed implementation rules in skills so they have one source of truth.
-- **React and TSX**: Before editing components, component state, render boundaries, or memoization, read [`.agents/skills/react/SKILL.md`](.agents/skills/react/SKILL.md). It owns component selection, styling, state locality, and render-performance rules.
-- **Heavy domain features**: When splitting a fat Viewer/Page into reusable pieces (page vs portal vs share vs micro-app), read [`.agents/skills/compose-atoms/SKILL.md`](.agents/skills/compose-atoms/SKILL.md). Split on mountable capabilities, not visual sections, and do not hide unused work behind `readOnly` / `mode` flags.
+- **React and TSX**: Before editing components, component state, render boundaries, or memoization, read the `react` skill. It owns component selection, styling, state locality, and render-performance rules.
+- **Heavy domain features**: When splitting a fat Viewer/Page into reusable pieces (page vs portal vs share vs micro-app), read the `compose-atoms` skill. Split on mountable capabilities, not visual sections, and do not hide unused work behind `readOnly` / `mode` flags.
-## Project Structure
+## Code Ownership
-```plaintext
-lobehub/
-โ”œโ”€โ”€ apps/
-โ”‚ โ”œโ”€โ”€ desktop/ # Electron desktop app
-โ”‚ โ”œโ”€โ”€ cli/ # LobeHub CLI
-โ”‚ โ””โ”€โ”€ server/ # Backend service (Hono app + server routers/services)
-โ”œโ”€โ”€ packages/ # Shared packages (@lobechat/*)
-โ”‚ โ”œโ”€โ”€ database/ # Database schemas, models, repositories
-โ”‚ โ”œโ”€โ”€ agent-runtime/ # Agent runtime
-โ”‚ โ”œโ”€โ”€ locales/ # i18n source: packages/locales/src/default/
-โ”‚ โ”œโ”€โ”€ env/ # env schemas (@/envs/* โ†’ packages/env/src/*)
-โ”‚ โ””โ”€โ”€ ...
-โ”œโ”€โ”€ src/
-โ”‚ โ”œโ”€โ”€ app/ # Next.js App Router (route shell + auth)
-โ”‚ โ”‚ โ”œโ”€โ”€ (backend)/ # Backend route shells
-โ”‚ โ”‚ โ”œโ”€โ”€ spa/ # SPA HTML template service
-โ”‚ โ”‚ โ””โ”€โ”€ spa-auth/ # Auth HTML shell (SSR)
-โ”‚ โ”œโ”€โ”€ routes/ # SPA page segments (thin โ€” delegate to features/)
-โ”‚ โ”‚ โ”œโ”€โ”€ (main)/ (mobile)/ (desktop)/ (popup)/
-โ”‚ โ”‚ โ”œโ”€โ”€ auth/ # Auth page segments (signin, signup, โ€ฆ)
-โ”‚ โ”‚ โ”œโ”€โ”€ onboarding/ share/
-โ”‚ โ”œโ”€โ”€ spa/ # SPA entry points and router config
-โ”‚ โ”‚ โ”œโ”€โ”€ entry.{web,mobile,desktop,popup}.tsx
-โ”‚ โ”‚ โ””โ”€โ”€ router/ # React Router configuration
-โ”‚ โ”œโ”€โ”€ store/ # Zustand stores
-โ”‚ โ”œโ”€โ”€ services/ # Client services
-โ”‚ โ”œโ”€โ”€ libs/ # Shared client/server helpers for the app shell
-โ”‚ โ””โ”€โ”€ ...
-โ””โ”€โ”€ e2e/ # E2E tests (Cucumber + Playwright)
-```
-
-## SPA Routes and Features
-
-SPA-related code is grouped under `src/spa/` (entries + router) and `src/routes/` (page segments). We use a **roots vs features** split: route trees only hold page segments; business logic and UI live in features.
-
-- **`src/spa/`** โ€“ SPA entry points (`entry.web.tsx`, `entry.mobile.tsx`, `entry.desktop.tsx`, `entry.popup.tsx`) and React Router config (`router/`, with `desktopRouter.config.*`, `mobileRouter.config.tsx`, `popupRouter.config.tsx`). Keeps router config next to entries to avoid confusion with `src/routes/`.
-
-- **`src/routes/` (roots)**\
- Only page-segment files: `_layout/index.tsx`, `index.tsx` (or `page.tsx`), and dynamic segments like `[id]/index.tsx`. Keep these **thin**: they should only import from `@/features/*` and compose layout/page, with no business logic or heavy UI.
+For the full repository map or help locating a code layer, read the `project-overview` skill.
-- **`src/features/`**\
- Business components by **domain** (e.g. `Pages`, `PageEditor`, `Home`). Put layout chunks (sidebar, header, body), hooks, and domain-specific UI here. Each feature exposes an `index.ts` (or `index.tsx`) with clear exports.
+- `apps/server/src`: backend runtime, routers, and services, imported through `@/server/*`. `src/app/(backend)` contains Next.js route shells only; do not put backend business logic there.
+- `src/app`: Next.js HTML/auth shells. Web shell helpers belong under `src/libs` or the relevant app segment, not `src/server`.
+- `src/spa`: SPA entry points and React Router configuration. `src/routes` holds thin page segments that compose `src/features`; business UI and logic belong in features by domain.
+- `src/services` and `src/store`: client API services and Zustand state. Keep fetch/cache guidance in `data-fetching-architecture` and store conventions in `zustand`.
+- `apps/desktop`, `apps/cli`: Electron and CLI applications. `packages` holds shared code, including `database`, `agent-runtime`, `env`, and `locales`.
+- `e2e`: end-to-end tests using Cucumber and Playwright.
-When adding or changing SPA routes:
-
-1. In `src/routes/`, add only the route segment files (layout + page) that delegate to features.
-2. Implement layout and page content under `src/features/<Domain>/` and export from there.
-3. In route files, use `import { X } from '@/features/<Domain>'` (or `import Y from '@/features/<Domain>/...'`). Do not add new `features/` folders inside `src/routes/`.
-4. **Register shared desktop content routes once:** add common Web/Electron paths, nesting, metadata, lazy loaders, and `preloadId` values in `src/spa/router/desktopRouter.shared.tsx`. The thin `desktopRouter.config.tsx` and `desktopRouter.config.desktop.tsx` files contain only runtime differences: Web mounts the content tree directly, while Electron keeps slim root stubs and mounts the same tree in per-tab memory routers through `src/spa/router/tabRouter.tsx`. Add code to a platform adapter only when the route is genuinely platform-specific. `desktopRouter.sync.test.tsx` guards the shared behavior and explicit differences โ€” keep it passing.
-
-See the **spa-routes** skill for the full convention and file-division rules.
+Before changing SPA routes, read the `spa-routes` skill. Register common Web/Electron paths, metadata, lazy loaders and `preloadId` values once in `src/spa/router/desktopRouter.shared.tsx`; keep `desktopRouter.config*.tsx` limited to platform differences and `desktopRouter.sync.test.tsx` passing. Do not create `features` directories inside `src/routes`.
## Development
@@ -87,12 +46,6 @@ bun run dev
pnpm --filter @lobechat/server dev
```
-### Backend Architecture
-
-- Backend runtime code lives under `apps/server/src` and is imported through `@/server/*`.
-- `src/app/(backend)` contains Next.js route shells. Do not add backend business logic there.
-- Web shell helpers belong under `src/libs/*` or the relevant `src/app` segment, not under `src/server`.
-
After `dev:spa` starts, the terminal prints a **Debug Proxy** URL:
```plaintext
@@ -117,16 +70,12 @@ Open this URL to develop locally against the production backend (app.lobehub.com
### Quality Check
-```bash
-bun run check [changed-files...]
-```
+Use `bun run check [changed-files...]`.
-- Every bug fix must include a corresponding regression test that fails before the fix and passes after it. **Skip** when the fix is pure style/CSS (selector, hover, mask, spacing, color) and the only practical assertion would be source-string matching on the stylesheet โ€” that is not a regression test worth shipping.
-- No selector = **lint + test in a single pass** โ€” run it once; don't fire a separate pass per selector. `--lint` / `--test` / `--type` narrow scope and are composable within one run. Default files = all working-tree changes (staged + unstaged + untracked); explicit paths override.
-- `--lint` auto-fixes the given files and prints the applied fixes as a diff, so you can review what changed.
-- `--test` auto-discovers the related tests for the given source files and runs them under the nearest owning vitest config (e.g. `packages/database`) โ€” no need to `cd` into packages.
-- `--type` runs the full type-check. NEVER run `bun run test` โ€” the full suite takes \~10 minutes.
-- To run tests manually (e.g. a single file or unusual flags), `cd` into the owning package first: `cd packages/database && bunx vitest run --silent='passed-only' '[file-path]'`.
+- Every bug fix needs a regression test that fails before the fix and passes after it. Skip pure style/CSS fixes when the only practical assertion would match stylesheet source strings.
+- Run once with the selectors needed: no selector means lint + related tests; `--lint`, `--test`, and `--type` compose. Default scope is all staged, unstaged and untracked changes; explicit paths override it.
+- Lint autofixes files: review the emitted diff. Tests use the nearest owning Vitest config. `--type` checks the full repo. Never run `bun run test`, which runs the full suite.
+- For a manual package test, run from the owning package: `cd packages/database && bunx vitest run --silent='passed-only' '[file-path]'`.
### i18n