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.

✨ feat(search): filtered message search, goal search and `lh recall` (#21188)

Arvin Xu376690f828b5
diff --git a/apps/cli/src/commands/message.test.ts b/apps/cli/src/commands/message.test.ts
index 546065ef090..9a5b8bace0c 100644
--- a/apps/cli/src/commands/message.test.ts
+++ b/apps/cli/src/commands/message.test.ts
@@ -13,6 +13,7 @@ const { mockTrpcClient } = vi.hoisted(() => ({
listAll: { query: vi.fn() },
removeMessage: { mutate: vi.fn() },
removeMessages: { mutate: vi.fn() },
+ searchByKeyword: { query: vi.fn() },
searchMessages: { query: vi.fn() },
topicStats: { query: vi.fn() },
},
@@ -165,8 +166,163 @@ describe('message command', () => {
});
describe('search', () => {
- it('should search messages', async () => {
- mockTrpcClient.message.searchMessages.query.mockResolvedValue([]);
+ it('searches through the filtered endpoint with default paging', async () => {
+ mockTrpcClient.message.searchByKeyword.query.mockResolvedValue({ hasMore: false, items: [] });
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'message', 'search', 'hello']);
+
+ expect(mockTrpcClient.message.searchByKeyword.query).toHaveBeenCalledWith({
+ keywords: 'hello',
+ limit: 20,
+ offset: 0,
+ });
+ expect(mockTrpcClient.message.searchMessages.query).not.toHaveBeenCalled();
+ });
+
+ it('passes the time window, roles, scope and match options', async () => {
+ mockTrpcClient.message.searchByKeyword.query.mockResolvedValue({ hasMore: false, items: [] });
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'message',
+ 'search',
+ 'STAMP',
+ '--since',
+ '2026-10-12',
+ '--until',
+ '2026-10-18',
+ '--role',
+ 'user, assistant',
+ '--topic-id',
+ 'tpc_1',
+ '--agent-id',
+ 'agt_1',
+ '--exact',
+ '--include-system',
+ '-L',
+ '5',
+ '-P',
+ '3',
+ ]);
+
+ expect(mockTrpcClient.message.searchByKeyword.query).toHaveBeenCalledWith({
+ agentId: 'agt_1',
+ endDate: new Date(2026, 9, 18, 23, 59, 59, 999),
+ exact: true,
+ includeAutomatedPrompts: true,
+ keywords: 'STAMP',
+ limit: 5,
+ offset: 10,
+ roles: ['user', 'assistant'],
+ startDate: new Date(2026, 9, 12, 0, 0, 0, 0),
+ topicId: 'tpc_1',
+ });
+ });
+
+ it('prints time, topic and snippet, and hints at the next page', async () => {
+ mockTrpcClient.message.searchByKeyword.query.mockResolvedValue({
+ hasMore: true,
+ items: [
+ {
+ createdAt: new Date(2026, 9, 15, 9, 5),
+ id: 'msg_1',
+ role: 'user',
+ snippet: 'turning on STAMP mode',
+ topicId: 'tpc_1',
+ topicTitle: 'Weekly report',
+ },
+ ],
+ });
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'message', 'search', 'STAMP']);
+
+ const output = consoleSpy.mock.calls.map((call) => call.join(' ')).join('\n');
+ expect(output).toContain('2026-10-15 09:05');
+ expect(output).toContain('Weekly report');
+ expect(output).toContain('turning on STAMP mode');
+ expect(output).toContain('-P 2');
+ });
+
+ it('warns when the provider pool cut off lower-ranked matches', async () => {
+ mockTrpcClient.message.searchByKeyword.query.mockResolvedValue({
+ hasMore: false,
+ items: [{ createdAt: new Date(2026, 9, 15), id: 'msg_1', role: 'user', snippet: 'x' }],
+ truncated: true,
+ });
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'message', 'search', 'x']);
+
+ const output = consoleSpy.mock.calls.map((call) => call.join(' ')).join('\n');
+ expect(output).toContain('Only the most relevant matches were considered');
+ });
+
+ it('keeps the truncation caveat when filtering empties the page', async () => {
+ mockTrpcClient.message.searchByKeyword.query.mockResolvedValue({
+ hasMore: false,
+ items: [],
+ truncated: true,
+ });
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'message', 'search', 'x', '--exact']);
+
+ const output = consoleSpy.mock.calls.map((call) => call.join(' ')).join('\n');
+ expect(output).toContain('No messages found.');
+ expect(output).toContain('Only the most relevant matches were considered');
+ });
+
+ it('keeps the truncation caveat on stderr for --json output', async () => {
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ mockTrpcClient.message.searchByKeyword.query.mockResolvedValue({
+ hasMore: false,
+ items: [{ contentLength: 1, createdAt: new Date(2026, 9, 15), id: 'msg_1', role: 'user' }],
+ truncated: true,
+ });
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'message', 'search', 'x', '--json']);
+
+ // stdout stays a bare array so scripts keep parsing it
+ const stdout = consoleSpy.mock.calls.map((call) => call.join(' ')).join('\n');
+ expect(() => JSON.parse(stdout)).not.toThrow();
+ expect(JSON.parse(stdout)).toHaveLength(1);
+
+ const stderr = errorSpy.mock.calls.map((call) => call.join(' ')).join('\n');
+ expect(stderr).toContain('Only the most relevant matches were considered');
+
+ errorSpy.mockRestore();
+ });
+
+ it('rejects an impossible calendar date instead of shifting the window', async () => {
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'message', 'search', 'x', '--until', '2026-02-31']);
+
+ expect(exitSpy).toHaveBeenCalledWith(1);
+ expect(mockTrpcClient.message.searchByKeyword.query).not.toHaveBeenCalled();
+ });
+
+ it('rejects an invalid time instead of searching everything', async () => {
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'message', 'search', 'x', '--since', 'last week']);
+
+ expect(exitSpy).toHaveBeenCalledWith(1);
+ expect(mockTrpcClient.message.searchByKeyword.query).not.toHaveBeenCalled();
+ });
+
+ it('falls back to the legacy endpoint on an older server when no filters are used', async () => {
+ mockTrpcClient.message.searchByKeyword.query.mockRejectedValue(
+ Object.assign(new Error('No "query"-procedure on path "message.searchByKeyword"'), {
+ data: { code: 'NOT_FOUND' },
+ }),
+ );
+ mockTrpcClient.message.searchMessages.query.mockResolvedValue([
+ { content: 'hello there', id: 'msg_legacy', role: 'user' },
+ ]);
const program = createProgram();
await program.parseAsync(['node', 'test', 'message', 'search', 'hello']);
@@ -174,6 +330,22 @@ describe('message command', () => {
expect(mockTrpcClient.message.searchMessages.query).toHaveBeenCalledWith({
keywords: 'hello',
});
+ const output = consoleSpy.mock.calls.map((call) => call.join(' ')).join('\n');
+ expect(output).toContain('msg_legacy');
+ });
+
+ it('refuses to drop filters silently on an older server', async () => {
+ mockTrpcClient.message.searchByKeyword.query.mockRejectedValue(
+ Object.assign(new Error('No "query"-procedure on path "message.searchByKeyword"'), {
+ data: { code: 'NOT_FOUND' },
+ }),
+ );
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'message', 'search', 'hello', '--since', '7d']);
+
+ expect(exitSpy).toHaveBeenCalledWith(1);
+ expect(mockTrpcClient.message.searchMessages.query).not.toHaveBeenCalled();
});
});
diff --git a/apps/cli/src/commands/message.ts b/apps/cli/src/commands/message.ts
index 9571682dbbb..477226c0591 100644
--- a/apps/cli/src/commands/message.ts
+++ b/apps/cli/src/commands/message.ts
@@ -2,10 +2,46 @@ import type { Command } from 'commander';
import pc from 'picocolors';
import { getTrpcClient } from '../api/client';
-import { confirm, outputJson, printTable, timeAgo, truncate } from '../utils/format';
+import { isMissingProcedure } from '../utils/error';
+import {
+ confirm,
+ formatTimestamp,
+ outputJson,
+ printTable,
+ timeAgo,
+ truncate,
+} from '../utils/format';
import { log } from '../utils/logger';
+import type { TimeWindow } from '../utils/timeWindow';
+import { parseTimeWindow, TIME_POINT_HELP } from '../utils/timeWindow';
import { resolveUrlBuilder, resourcePath, withUrls } from './resourceUrl';
+interface MessageSearchOptions {
+ agentId?: string;
+ exact?: boolean;
+ includeSystem?: boolean;
+ json?: string | boolean;
+ limit?: string;
+ page?: string;
+ role?: string;
+ since?: string;
+ topicId?: string;
+ until?: string;
+ user?: boolean;
+}
+
+const TRUNCATION_NOTE =
+ 'Only the most relevant matches were considered; narrow with --since/--until or --topic-id to see the rest.';
+
+const printTruncationNote = () => console.log(pc.yellow(TRUNCATION_NOTE));
+
+/**
+ * `--json` consumers read stdout, so the caveat rides on stderr: an extra field
+ * would break both the bare-array contract and `--json <fields>` shaping, while
+ * dropping it silently hides that lower-ranked matches were cut.
+ */
+const warnTruncationNote = () => console.error(pc.yellow(TRUNCATION_NOTE));
+
export function registerMessageCommand(program: Command) {
const message = program.command('message').description('Manage messages');
@@ -86,27 +122,112 @@ export function registerMessageCommand(program: Command) {
message
.command('search <keywords>')
- .description('Search messages')
+ .description(
+ 'Search messages, newest first. System-written prompts of task/cron/eval runs are hidden unless --include-system',
+ )
+ .option('--since <when>', `Only messages created at/after this time (${TIME_POINT_HELP})`)
+ .option('--until <when>', `Only messages created at/before this time (${TIME_POINT_HELP})`)
+ .option('--role <roles>', 'Filter by role, comma-separated (user, assistant, system, task)')
+ .option('--user', 'Shorthand for --role user')
+ .option('--topic-id <id>', 'Only messages in this topic')
+ .option('--agent-id <id>', 'Only messages of this agent')
+ .option(
+ '--exact',
+ 'Case-sensitive whole-term match (STAMP will not match "stamp" or "STAMPED")',
+ )
+ .option('--include-system', 'Include system-written prompts of task, cron and eval runs')
+ .option('-L, --limit <n>', 'Page size (max 100)', '20')
+ .option('-P, --page <n>', 'Page number', '1')
.option('--json [fields]', 'Output JSON, optionally specify fields (comma-separated)')
- .action(async (keywords: string, options: { json?: string | boolean }) => {
+ .action(async (keywords: string, options: MessageSearchOptions) => {
+ let window: TimeWindow;
+ try {
+ window = parseTimeWindow(options);
+ } catch (error) {
+ log.error((error as Error).message);
+ process.exit(1);
+ return;
+ }
+
+ const limit = Math.min(Math.max(Number.parseInt(options.limit || '20', 10) || 20, 1), 100);
+ const page = Math.max(Number.parseInt(options.page || '1', 10) || 1, 1);
+ const roles = options.user
+ ? ['user']
+ : options.role
+ ?.split(',')
+ .map((role) => role.trim())
+ .filter(Boolean);
+
+ const input = {
+ keywords,
+ limit,
+ offset: (page - 1) * limit,
+ ...window,
+ ...(options.agentId && { agentId: options.agentId }),
+ ...(options.exact && { exact: true }),
+ ...(options.includeSystem && { includeAutomatedPrompts: true }),
+ ...(roles?.length && { roles }),
+ ...(options.topicId && { topicId: options.topicId }),
+ };
+
const client = await getTrpcClient();
- const result = await client.message.searchMessages.query({ keywords });
- const items = Array.isArray(result) ? result : [];
+ let result: { hasMore: boolean; items: any[]; truncated?: boolean };
+ try {
+ result = await client.message.searchByKeyword.query(input);
+ } catch (error) {
+ if (!isMissingProcedure(error)) throw error;
+ // Older servers only expose the unfiltered search.
+ const usesNewOptions =
+ Object.keys(window).length > 0 ||
+ options.agentId ||
+ options.exact ||
+ options.includeSystem ||
+ roles?.length ||
+ options.topicId ||
+ page > 1;
+ if (usesNewOptions) {
+ log.error(
+ 'This server does not support filtered message search yet. Retry without filters, or upgrade the server.',
+ );
+ process.exit(1);
+ return;
+ }
+ const legacy = await client.message.searchMessages.query({ keywords });
+ const items = Array.isArray(legacy) ? legacy : [];
+ result = { hasMore: items.length > limit, items: items.slice(0, limit) };
+ }
if (options.json !== undefined) {
const fields = typeof options.json === 'string' ? options.json : undefined;
- outputJson(withUrls(items, await resolveUrlBuilder(client), resourcePath.message), fields);
+ outputJson(
+ withUrls(result.items, await resolveUrlBuilder(client), resourcePath.message),
+ fields,
+ );
+ if (result.truncated) warnTruncationNote();
return;
}
- if (items.length === 0) {
+ if (result.items.length === 0) {
console.log('No messages found.');
+ // Hydration-only filters can empty a page cut from a truncated pool.
+ if (result.truncated) printTruncationNote();
return;
}
- const rows = items.map((m: any) => [m.id || '', m.role || '', truncate(m.content || '', 60)]);
+ const rows = result.items.map((m: any) => [
+ m.id || '',
+ m.createdAt ? formatTimestamp(m.createdAt) : '',
+ m.role || '',
+ truncate(m.topicTitle || m.topicId || '', 24),
+ truncate(m.snippet ?? m.content ?? '', 72),
+ ]);
- printTable(rows, ['ID', 'ROLE', 'CONTENT']);
+ printTable(rows, ['ID', 'CREATED', 'ROLE', 'TOPIC', 'MATCH']);
+
+ if (result.hasMore) {
+ console.log(pc.dim(`\nMore results: add -P ${page + 1}`));
+ }
+ if (result.truncated) printTruncationNote();
});
// ── delete ────────────────────────────────────────────
diff --git a/apps/cli/src/commands/recall.test.ts b/apps/cli/src/commands/recall.test.ts
new file mode 100644
index 00000000000..63c75ba5d6a
--- /dev/null
+++ b/apps/cli/src/commands/recall.test.ts
@@ -0,0 +1,185 @@
+import { Command } from 'commander';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { log } from '../utils/logger';
+import { registerRecallCommand } from './recall';
+
+const { mockTrpcClient } = vi.hoisted(() => ({
+ mockTrpcClient: {
+ search: {
+ recall: { query: vi.fn() },
+ },
+ },
+}));
+
+const { getTrpcClient: mockGetTrpcClient } = vi.hoisted(() => ({
+ getTrpcClient: vi.fn(),
+}));
+
+vi.mock('../api/client', () => ({ getTrpcClient: mockGetTrpcClient }));
+
+const emptyResult = {
+ goals: [],
+ messages: { hasMore: false, items: [] },
+ pages: [],
+ topics: [],
+};
+
+describe('recall command', () => {
+ let exitSpy: ReturnType<typeof vi.spyOn>;
+ let consoleSpy: ReturnType<typeof vi.spyOn>;
+
+ beforeEach(() => {
+ exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {}) as any);
+ consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ mockGetTrpcClient.mockResolvedValue(mockTrpcClient);
+ mockTrpcClient.search.recall.query.mockReset();
+ vi.mocked(log.error).mockClear();
+ });
+
+ afterEach(() => {
+ exitSpy.mockRestore();
+ consoleSpy.mockRestore();
+ });
+
+ function createProgram() {
+ const program = new Command();
+ program.exitOverride();
+ registerRecallCommand(program);
+ return program;
+ }
+
+ const output = () => consoleSpy.mock.calls.map((call) => call.join(' ')).join('\n');
+
+ it('sends the query, window, types and options', async () => {
+ mockTrpcClient.search.recall.query.mockResolvedValue(emptyResult);
+
+ await createProgram().parseAsync([
+ 'node',
+ 'test',
+ 'recall',
+ 'STAMP',
+ '--since',
+ '2026-10-12',
+ '--until',
+ '2026-10-18',
+ '-t',
+ 'goal,message',
+ '--exact',
+ '--include-system',
+ '-L',
+ '5',
+ ]);
+
+ expect(mockTrpcClient.search.recall.query).toHaveBeenCalledWith({
+ endDate: new Date(2026, 9, 18, 23, 59, 59, 999),
+ exact: true,
+ includeAutomatedPrompts: true,
+ limitPerType: 5,
+ query: 'STAMP',
+ startDate: new Date(2026, 9, 12, 0, 0, 0, 0),
+ types: ['goal', 'message'],
+ });
+ expect(output()).toContain('Nothing found in this window.');
+ });
+
+ it('renders each non-empty group', async () => {
+ mockTrpcClient.search.recall.query.mockResolvedValue({
+ goals: [
+ {
+ id: 'goal_dTXmv3HgsIYq',
+ status: 'paused',
+ title: 'Client reads to replica (STAMP)',
+ updatedAt: new Date(2026, 9, 18, 10, 0),
+ },
+ ],
+ messages: {
+ hasMore: true,
+ items: [
+ {
+ createdAt: new Date(2026, 9, 15, 9, 5),
+ id: 'msg_1',
+ role: 'user',
+ snippet: 'turning on STAMP mode',
+ topicTitle: 'Weekly report',
+ },
+ ],
+ },
+ pages: [{ id: 'docs_1', title: 'STAMP notes', updatedAt: new Date(2026, 9, 16, 8, 0) }],
+ topics: [
+ {
+ hitCount: 3,
+ id: 'tpc_1',
+ lastMatchedAt: new Date(2026, 9, 15, 9, 5),
+ matchedBy: ['title', 'messages'],
+ title: 'Weekly report',
+ },
+ ],
+ });
+
+ await createProgram().parseAsync(['node', 'test', 'recall', 'STAMP']);
+
+ const text = output();
+ expect(text).toContain('goal_dTXmv3HgsIYq');
+ expect(text).toContain('paused');
+ expect(text).toContain('title+messages');
+ expect(text).toContain('turning on STAMP mode');
+ expect(text).toContain('2026-10-15 09:05');
+ expect(text).toContain('docs_1');
+ expect(text).toContain('More messages');
+ });
+
+ it('keeps the truncation caveat when the window is otherwise empty', async () => {
+ mockTrpcClient.search.recall.query.mockResolvedValue({
+ ...emptyResult,
+ messages: { hasMore: false, items: [], truncated: true },
+ });
+
+ await createProgram().parseAsync(['node', 'test', 'recall', 'x', '--exact']);
+
+ expect(output()).toContain('Nothing found in this window.');
+ expect(output()).toContain('Only the most relevant message matches were considered');
+ });
+
+ it('keeps the truncation caveat when only other sections have results', async () => {
+ mockTrpcClient.search.recall.query.mockResolvedValue({
+ ...emptyResult,
+ goals: [{ id: 'goal_1', status: 'paused', title: 'x goal' }],
+ messages: { hasMore: false, items: [], truncated: true },
+ });
+
+ await createProgram().parseAsync(['node', 'test', 'recall', 'x']);
+
+ expect(output()).toContain('goal_1');
+ expect(output()).toContain('Only the most relevant message matches were considered');
+ });
+
+ it('rejects unknown types before calling the server', async () => {
+ await createProgram().parseAsync(['node', 'test', 'recall', 'x', '-t', 'goal,agent']);
+
+ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('Invalid type: agent'));
+ expect(exitSpy).toHaveBeenCalledWith(1);
+ expect(mockTrpcClient.search.recall.query).not.toHaveBeenCalled();
+ });
+
+ it('explains when the server predates recall', async () => {
+ mockTrpcClient.search.recall.query.mockRejectedValue(
+ Object.assign(new Error('No "query"-procedure on path "search.recall"'), {
+ data: { code: 'NOT_FOUND' },
+ }),
+ );
+
+ await createProgram().parseAsync(['node', 'test', 'recall', 'x']);
+
+ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('does not support recall'));
+ expect(exitSpy).toHaveBeenCalledWith(1);
+ });
+
+ it('prints JSON when asked', async () => {
+ mockTrpcClient.search.recall.query.mockResolvedValue(emptyResult);
+
+ await createProgram().parseAsync(['node', 'test', 'recall', 'x', '--json']);
+
+ expect(JSON.parse(output())).toEqual(emptyResult);
+ });
+});
diff --git a/apps/cli/src/commands/recall.ts b/apps/cli/src/commands/recall.ts
new file mode 100644
index 00000000000..668d4d6b792
--- /dev/null
+++ b/apps/cli/src/commands/recall.ts
@@ -0,0 +1,198 @@
+import type { Command } from 'commander';
+import pc from 'picocolors';
+
+import { getTrpcClient } from '../api/client';
+import { isMissingProcedure } from '../utils/error';
+import { formatTimestamp, outputJson, printTable, truncate } from '../utils/format';
+import { log } from '../utils/logger';
+import type { TimeWindow } from '../utils/timeWindow';
+import { parseTimeWindow, TIME_POINT_HELP } from '../utils/timeWindow';
+
+const RECALL_TYPES = ['message', 'topic', 'goal', 'page'] as const;
+type RecallType = (typeof RECALL_TYPES)[number];
+
+interface RecallOptions {
+ exact?: boolean;
+ includeSystem?: boolean;
+ json?: string | boolean;
+ limit?: string;
+ since?: string;
+ type?: string;
+ until?: string;
+}
+
+const section = (title: string, count: number, more = false) => {
+ console.log();
+ console.log(pc.bold(pc.cyan(`── ${title} (${count}${more ? '+' : ''}) ──`)));
+};
+
+const when = (value?: Date | string | null) => (value ? formatTimestamp(value) : '');
+
+export function registerRecallCommand(program: Command) {
+ program
+ .command('recall <query>')
+ .description(
+ 'Recall what happened around a topic: matching messages, conversations, goals and pages in one time window',
+ )
+ .option('--since <when>', `Window start (${TIME_POINT_HELP})`)
+ .option('--until <when>', `Window end (${TIME_POINT_HELP})`)
+ .option('-t, --type <types>', `Only these types, comma-separated: ${RECALL_TYPES.join(', ')}`)
+ .option(
+ '--exact',
+ 'Case-sensitive whole-term match for messages (STAMP will not match "stamp" or "STAMPED")',
+ )
+ .option('--include-system', 'Include system-written prompts of task, cron and eval runs')
+ .option('-L, --limit <n>', 'Results per type (max 50)', '10')
+ .option('--json [fields]', 'Output JSON, optionally specify fields (comma-separated)')
+ .addHelpText(
+ 'after',
+ `
+Examples:
+ $ lh recall STAMP --since 7d
+ $ lh recall "replica" --since 2026-10-12 --until 2026-10-18 --exact
+ $ lh recall 安全信道 -t message,topic --json
+
+Topics combine title matches with the conversations whose messages matched.
+Follow up with \`lh topic view <id>\`, \`lh goal show <id>\` or \`lh doc view <id>\`.`,
+ )
+ .action(async (query: string, options: RecallOptions) => {
+ let window: TimeWindow;
+ try {
+ window = parseTimeWindow(options);
+ } catch (error) {
+ log.error((error as Error).message);
+ process.exit(1);
+ return;
+ }
+
+ const types = options.type
+ ?.split(',')
+ .map((type) => type.trim())
+ .filter(Boolean);
+ const invalid = types?.filter((type) => !RECALL_TYPES.includes(type as RecallType));
+ if (invalid?.length) {
+ log.error(
+ `Invalid type: ${invalid.join(', ')}. Must be one of: ${RECALL_TYPES.join(', ')}`,
+ );
+ process.exit(1);
+ return;
+ }
+
+ const limitPerType = Math.min(
+ Math.max(Number.parseInt(options.limit || '10', 10) || 10, 1),
+ 50,
+ );
+
+ const client = await getTrpcClient();
+ let result: any;
+ try {
+ result = await client.search.recall.query({
+ limitPerType,
+ query,
+ ...window,
+ ...(options.exact && { exact: true }),
+ ...(options.includeSystem && { includeAutomatedPrompts: true }),
+ ...(types?.length && { types: types as RecallType[] }),
+ });
+ } catch (error) {
+ if (!isMissingProcedure(error)) throw error;
+ log.error(
+ 'This server does not support recall yet. Use `lh message search` and `lh search` instead, or upgrade the server.',
+ );
+ process.exit(1);
+ return;
+ }
+
+ if (options.json !== undefined) {
+ const fields = typeof options.json === 'string' ? options.json : undefined;
+ outputJson(result, fields);
+ return;
+ }
+
+ const {
+ goals = [],
+ messages = { hasMore: false, items: [], truncated: false },
+ pages = [],
+ topics = [],
+ } = result ?? {};
+
+ // Hydration-only filters can empty the message page even when the
+ // provider pool was cut, so the caveat must survive an empty section.
+ const printTruncationNote = () => {
+ if (!messages.truncated) return;
+ console.log(
+ pc.yellow(
+ 'Only the most relevant message matches were considered; narrow --since/--until to see the rest.',
+ ),
+ );
+ };
+
+ if (!goals.length && !messages.items.length && !pages.length && !topics.length) {
+ console.log('Nothing found in this window.');
+ printTruncationNote();
+ return;
+ }
+
+ if (goals.length) {
+ section('goal', goals.length);
+ printTable(
+ goals.map((goal: any) => [
+ goal.id,
+ goal.status || '',
+ truncate(goal.title || '', 56),
+ when(goal.updatedAt),
+ ]),
+ ['ID', 'STATUS', 'TITLE', 'UPDATED'],
+ );
+ }
+
+ if (topics.length) {
+ section('topic', topics.length);
+ printTable(
+ topics.map((topic: any) => [
+ topic.id,
+ truncate(topic.title || 'Untitled', 48),
+ topic.hitCount ? String(topic.hitCount) : '-',
+ (topic.matchedBy || []).join('+'),
+ when(topic.lastMatchedAt || topic.updatedAt),
+ ]),
+ ['ID', 'TITLE', 'HITS', 'MATCHED', 'LAST'],
+ );
+ }
+
+ if (messages.items.length) {
+ section('message', messages.items.length, messages.hasMore);
+ printTable(
+ messages.items.map((message: any) => [
+ message.id,
+ when(message.createdAt),
+ message.role || '',
+ truncate(message.topicTitle || message.topicId || '', 24),
+ truncate(message.snippet || '', 64),
+ ]),
+ ['ID', 'CREATED', 'ROLE', 'TOPIC', 'MATCH'],
+ );
+ if (messages.hasMore) {
+ console.log(
+ pc.dim(
+ 'More messages: `lh message search` with the same query, --since and --until pages through all of them',
+ ),
+ );
+ }
+ }
+
+ if (pages.length) {
+ section('page', pages.length);
+ printTable(
+ pages.map((page: any) => [
+ page.id,
+ truncate(page.title || 'Untitled', 56),
+ when(page.updatedAt),
+ ]),
+ ['ID', 'TITLE', 'UPDATED'],
+ );
+ }
+
+ printTruncationNote();
+ });
+}
diff --git a/apps/cli/src/commands/resourceUrl.test.ts b/apps/cli/src/commands/resourceUrl.test.ts
index 9155f5e4738..2698fc43b60 100644
--- a/apps/cli/src/commands/resourceUrl.test.ts
+++ b/apps/cli/src/commands/resourceUrl.test.ts
@@ -23,6 +23,13 @@ describe('resourcePath', () => {
resourcePath.message({ agentId: 'agt_1', id: 'msg_1', topicId: 'tpc_1' }),
'/agent/agt_1/tpc_1#msg_1',
],
+ // Group-chat hits carry `groupId` instead of `agentId`; without it the
+ // resolver falls through to a missing agent route and the URL is dropped.
+ [
+ resourcePath.message({ groupId: 'grp_1', id: 'msg_1', topicId: 'tpc_1' }),
+ '/group/grp_1/tpc_1#msg_1',
+ ],
+ [resourcePath.message({ groupId: 'grp_1', id: 'msg_1' }), '/group/grp_1#msg_1'],
[resourcePath.document({ id: 'docs_1' }), '/page/docs_1'],
[
resourcePath.document({ id: 'docs_1', knowledgeBaseId: 'kb_1' }),
diff --git a/apps/cli/src/commands/search.test.ts b/apps/cli/src/commands/search.test.ts
index 158f8af8650..af0f708bb3a 100644
--- a/apps/cli/src/commands/search.test.ts
+++ b/apps/cli/src/commands/search.test.ts
@@ -197,4 +197,33 @@ describe('search command', () => {
expect(consoleSpy).toHaveBeenCalledWith(JSON.stringify(failure, null, 2));
expect(exitSpy).toHaveBeenCalledWith(1);
});
+
+ it('opts untyped searches into goals', async () => {
+ mockTrpcClient.search.query.query.mockResolvedValue([
+ { id: 'goal_1', status: 'paused', title: 'Replica (STAMP)', type: 'goal' },
+ ]);
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'search', '-q', 'STAMP']);
+
+ expect(mockTrpcClient.search.query.query).toHaveBeenCalledWith(
+ expect.objectContaining({ includeGoals: true, query: 'STAMP' }),
+ );
+ const output = consoleSpy.mock.calls.map((call) => call.join(' ')).join('\n');
+ expect(output).toContain('goal_1');
+ });
+
+ it.each(['goal', 'task'])('accepts the %s type', async (type) => {
+ mockTrpcClient.search.query.query.mockResolvedValue([]);
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'search', '-q', 'STAMP', '-t', type]);
+
+ expect(mockTrpcClient.search.query.query).toHaveBeenCalledWith(
+ expect.not.objectContaining({ includeGoals: true }),
+ );
+ expect(mockTrpcClient.search.query.query).toHaveBeenCalledWith(
+ expect.objectContaining({ type }),
+ );
+ });
});
diff --git a/apps/cli/src/commands/search.ts b/apps/cli/src/commands/search.ts
index 203f60e854b..e6437d4ca19 100644
--- a/apps/cli/src/commands/search.ts
+++ b/apps/cli/src/commands/search.ts
@@ -18,6 +18,8 @@ const SEARCH_TYPES = [
'plugin',
'communityAgent',
'knowledgeBase',
+ 'task',
+ 'goal',
] as const;
type SearchType = (typeof SEARCH_TYPES)[number];
@@ -52,7 +54,7 @@ export function registerSearchCommand(program: Command) {
)
.option(
'-T, --time-range <range>',
- 'Time range filter (e.g. day, week, month, year, requires --web)',
+ 'Time range filter (e.g. day, week, month, year, requires --web; for local history use `recall --since`)',
)
.option('--json [fields]', 'Output JSON, optionally specify fields (comma-separated)')
.action(
@@ -119,8 +121,11 @@ async function localSearch(
const client = await getTrpcClient();
- const input: { limitPerType?: number; query: string; type?: SearchType } = { query };
+ const input: { includeGoals?: boolean; limitPerType?: number; query: string; type?: SearchType } =
+ { query };
if (options.type) input.type = options.type as SearchType;
+ // Goals are opt-in on untyped searches (the web command menu cannot render them yet).
+ else input.includeGoals = true;
if (options.limit) input.limitPerType = Number.parseInt(options.limit, 10);
const result = await client.search.query.query(input);
diff --git a/apps/cli/src/program.ts b/apps/cli/src/program.ts
index 5e972c6cd79..1c3a58cf337 100644
--- a/apps/cli/src/program.ts
+++ b/apps/cli/src/program.ts
@@ -32,6 +32,7 @@ import { registerPluginCommand } from './commands/plugin';
import { registerProjectCommand } from './commands/project';
import { registerProviderCommand } from './commands/provider';
import { registerReadCommand } from './commands/read';
+import { registerRecallCommand } from './commands/recall';
import { registerSearchCommand } from './commands/search';
import { registerSessionGroupCommand } from './commands/session-group';
import { registerSkillCommand } from './commands/skill';
@@ -88,6 +89,7 @@ export function createProgram() {
registerDocCommand(program);
registerSearchCommand(program);
registerReadCommand(program);
+ registerRecallCommand(program);
registerKbCommand(program);
registerMemoryCommand(program);
registerAgentCommand(program);
diff --git a/apps/cli/src/utils/error.ts b/apps/cli/src/utils/error.ts
index 525f528388b..a5beabc2e72 100644
--- a/apps/cli/src/utils/error.ts
+++ b/apps/cli/src/utils/error.ts
@@ -69,3 +69,12 @@ export function isTransientNetworkError(error: unknown): boolean {
return code !== undefined && TRANSIENT_NETWORK_ERROR_CODES.has(code);
});
}
+
+/**
+ * A server older than this CLI answers an unknown tRPC procedure with
+ * NOT_FOUND; callers use this to fall back to an older endpoint.
+ */
+export function isMissingProcedure(error: unknown): boolean {
+ const code = toRecord(toRecord(error)?.data)?.code;
+ return code === 'NOT_FOUND' && /procedure/i.test(getErrorMessage(error) ?? '');
+}
diff --git a/apps/cli/src/utils/format.ts b/apps/cli/src/utils/format.ts
index 024cefcde33..b49587ad476 100644
--- a/apps/cli/src/utils/format.ts
+++ b/apps/cli/src/utils/format.ts
@@ -15,6 +15,14 @@ export function timeAgo(date: Date | string): string {
return `${seconds}s ago`;
}
+/** Absolute local time (`2026-10-15 14:03`) for history listings, where "3d ago" loses the day. */
+export function formatTimestamp(date: Date | string): string {
+ const value = new Date(date);
+ if (Number.isNaN(value.getTime())) return '-';
+ const pad = (n: number) => String(n).padStart(2, '0');
+ return `${value.getFullYear()}-${pad(value.getMonth() + 1)}-${pad(value.getDate())} ${pad(value.getHours())}:${pad(value.getMinutes())}`;
+}
+
/**
* Counterpart to `timeAgo` for deadlines. `timeAgo` only formats the past, so
* feeding it a future timestamp (an invitation expiry, a lease) renders a
diff --git a/apps/cli/src/utils/timeWindow.test.ts b/apps/cli/src/utils/timeWindow.test.ts
new file mode 100644
index 00000000000..dac294c031b
--- /dev/null
+++ b/apps/cli/src/utils/timeWindow.test.ts
@@ -0,0 +1,51 @@
+import { describe, expect, it } from 'vitest';
+
+import { parseTimePoint, parseTimeWindow } from './timeWindow';
+
+const now = new Date('2026-10-19T12:00:00.000Z');
+
+describe('parseTimePoint', () => {
+ it('counts relative values back from now', () => {
+ expect(parseTimePoint('24h', 'start', now)).toEqual(new Date('2026-10-18T12:00:00.000Z'));
+ expect(parseTimePoint('7d', 'start', now)).toEqual(new Date('2026-10-12T12:00:00.000Z'));
+ expect(parseTimePoint('2W', 'start', now)).toEqual(new Date('2026-10-05T12:00:00.000Z'));
+ });
+
+ it('reads a bare date as a whole local day', () => {
+ expect(parseTimePoint('2026-10-18', 'start')).toEqual(new Date(2026, 9, 18, 0, 0, 0, 0));
+ expect(parseTimePoint('2026-10-18', 'end')).toEqual(new Date(2026, 9, 18, 23, 59, 59, 999));
+ });
+
+ it('accepts ISO timestamps as-is', () => {
+ expect(parseTimePoint('2026-10-11T16:00:00Z', 'start')).toEqual(
+ new Date('2026-10-11T16:00:00.000Z'),
+ );
+ });
+
+ it.each(['2026-02-31', '2026-00-12', '2026-13-01', '2026-02-31T00:00:00Z', '2025-02-29'])(
+ 'rejects the impossible calendar date %s instead of rolling it over',
+ (value) => {
+ expect(() => parseTimePoint(value, 'end')).toThrow(`Invalid time "${value}"`);
+ },
+ );
+
+ it('accepts a real leap day', () => {
+ expect(parseTimePoint('2028-02-29', 'start')).toEqual(new Date(2028, 1, 29, 0, 0, 0, 0));
+ });
+
+ it('rejects unparseable input', () => {
+ expect(() => parseTimePoint('last week', 'start')).toThrow('Invalid time "last week"');
+ });
+});
+
+describe('parseTimeWindow', () => {
+ it('rejects an inverted window', () => {
+ expect(() => parseTimeWindow({ since: '2026-10-18', until: '2026-10-12' })).toThrow(
+ '--since must be earlier than --until.',
+ );
+ });
+
+ it('leaves unset edges open', () => {
+ expect(parseTimeWindow({})).toEqual({});
+ });
+});
diff --git a/apps/cli/src/utils/timeWindow.ts b/apps/cli/src/utils/timeWindow.ts
new file mode 100644
index 00000000000..7166a29f447
--- /dev/null
+++ b/apps/cli/src/utils/timeWindow.ts
@@ -0,0 +1,72 @@
+const RELATIVE_PATTERN = /^(\d+)\s*([hdwm])$/i;
+const DATE_ONLY_PATTERN = /^(\d{4})-(\d{2})-(\d{2})$/;
+const LEADING_DATE_PATTERN = /^(\d{4})-(\d{2})-(\d{2})/;
+
+const UNIT_MS: Record<string, number> = {
+ d: 24 * 60 * 60 * 1000,
+ h: 60 * 60 * 1000,
+ m: 30 * 24 * 60 * 60 * 1000,
+ w: 7 * 24 * 60 * 60 * 1000,
+};
+
+export const TIME_POINT_HELP = 'ISO time, YYYY-MM-DD (local day), or relative: 24h, 7d, 2w, 1m';
+
+/**
+ * Parse a `--since` / `--until` value. Relative values count back from `now`;
+ * a bare date is a local calendar day, so `--until 2026-10-18` includes that
+ * whole day. Throws on anything else so a typo never silently widens a search.
+ */
+export function parseTimePoint(value: string, edge: 'end' | 'start', now: Date = new Date()): Date {
+ const text = value.trim();
+
+ const relative = text.match(RELATIVE_PATTERN);
+ if (relative) {
+ return new Date(now.getTime() - Number(relative[1]) * UNIT_MS[relative[2].toLowerCase()]);
+ }
+
+ // `Date` rolls impossible days over (2026-02-31 becomes March 3) for both
+ // bare dates and ISO strings, which would silently shift the window.
+ const leadingDate = text.match(LEADING_DATE_PATTERN);
+ if (
+ leadingDate &&
+ !isCalendarDate(...(leadingDate.slice(1).map(Number) as [number, number, number]))
+ ) {
+ throw new Error(`Invalid time "${value}": no such calendar date.`);
+ }
+
+ const dateOnly = text.match(DATE_ONLY_PATTERN);
+ if (dateOnly) {
+ const [year, month, day] = dateOnly.slice(1).map(Number);
+ return edge === 'start'
+ ? new Date(year, month - 1, day, 0, 0, 0, 0)
+ : new Date(year, month - 1, day, 23, 59, 59, 999);
+ }
+
+ const parsed = new Date(text);
+ if (Number.isNaN(parsed.getTime())) {
+ throw new Error(`Invalid time "${value}". Use ${TIME_POINT_HELP}.`);
+ }
+ return parsed;
+}
+
+function isCalendarDate(year: number, month: number, day: number): boolean {
+ const date = new Date(Date.UTC(year, month - 1, day));
+ return (
+ date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day
+ );
+}
+
+export interface TimeWindow {
+ endDate?: Date;
+ startDate?: Date;
+}
+
+export function parseTimeWindow(options: { since?: string; until?: string }): TimeWindow {
+ const window: TimeWindow = {};
+ if (options.since) window.startDate = parseTimePoint(options.since, 'start');
+ if (options.until) window.endDate = parseTimePoint(options.until, 'end');
+ if (window.startDate && window.endDate && window.startDate > window.endDate) {
+ throw new Error('--since must be earlier than --until.');
+ }
+ return window;
+}
diff --git a/apps/server/src/routers/lambda/__tests__/search.test.ts b/apps/server/src/routers/lambda/__tests__/search.test.ts
index 32489b86a88..6ea2aebb8ea 100644
--- a/apps/server/src/routers/lambda/__tests__/search.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/search.test.ts
@@ -1,7 +1,9 @@
// @vitest-environment node
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { MessageModel } from '@/database/models/message';
import { UserModel } from '@/database/models/user';
+import { GoalSearchRepo } from '@/database/repositories/goalSearch';
import { TaskSearchRepo } from '@/database/repositories/taskSearch';
import { DiscoverService } from '@/server/services/discover';
import { createFtsSearchRepo } from '@/server/services/ftsSearch';
@@ -20,6 +22,13 @@ vi.mock('@/database/models/user', () => ({
vi.mock('@/database/repositories/taskSearch', () => ({ TaskSearchRepo: vi.fn() }));
+vi.mock('@/database/repositories/goalSearch', () => ({ GoalSearchRepo: vi.fn() }));
+
+vi.mock('@/database/models/message', () => ({
+ MESSAGE_KEYWORD_SEARCH_MAX_LIMIT: 100,
+ MessageModel: vi.fn(),
+}));
+
vi.mock('@/server/services/discover', () => ({
DiscoverService: vi.fn(),
}));
@@ -31,6 +40,8 @@ describe('searchRouter', () => {
const getUserSettings = vi.fn();
const search = vi.fn();
const searchTasks = vi.fn();
+ const searchGoals = vi.fn();
+ const searchByKeyword = vi.fn();
beforeEach(() => {
vi.clearAllMocks();
@@ -40,6 +51,14 @@ describe('searchRouter', () => {
getUserSettings.mockResolvedValue({ market: { accessToken: 'market-token' } });
search.mockResolvedValue([]);
searchTasks.mockResolvedValue([]);
+ searchGoals.mockResolvedValue([]);
+ searchByKeyword.mockResolvedValue({ hasMore: false, items: [] });
+ vi.mocked(GoalSearchRepo).mockImplementation(function () {
+ return { search: searchGoals } as unknown as GoalSearchRepo;
+ });
+ vi.mocked(MessageModel).mockImplementation(function () {
+ return { searchByKeyword } as unknown as MessageModel;
+ });
vi.mocked(TaskSearchRepo).mockImplementation(function () {
return { search: searchTasks } as unknown as TaskSearchRepo;
});
@@ -234,4 +253,101 @@ describe('searchRouter', () => {
message: 'Marketplace agent search is currently unavailable',
});
});
+ describe('goals', () => {
+ const goal = { id: 'goal_1', status: 'paused', title: 'Replica (STAMP)', type: 'goal' };
+
+ it('searches goals for an explicit goal type without touching the index', async () => {
+ searchGoals.mockResolvedValue([goal]);
+ const caller = searchRouter.createCaller({ userId: 'test-user' } as any);
+
+ const result = await caller.query({ limitPerType: 7, query: 'STAMP', type: 'goal' });
+
+ expect(result).toEqual([goal]);
+ expect(searchGoals).toHaveBeenCalledWith({ limit: 7, query: 'STAMP' });
+ expect(search).not.toHaveBeenCalled();
+ expect(getAssistantList).not.toHaveBeenCalled();
+ });
+
+ it('keeps goals out of untyped searches unless the caller opts in', async () => {
+ searchGoals.mockResolvedValue([goal]);
+ const caller = searchRouter.createCaller({ userId: 'test-user' } as any);
+
+ await caller.query({ includeMarketplace: false, query: 'STAMP' });
+ expect(searchGoals).not.toHaveBeenCalled();
+
+ const result = await caller.query({
+ includeGoals: true,
+ includeMarketplace: false,
+ query: 'STAMP',
+ });
+ expect(result).toEqual([goal]);
+ });
+ });
+
+ describe('recall', () => {
+ it('combines message, topic, goal and page hits in the window without the marketplace', async () => {
+ const startDate = new Date('2026-10-12T00:00:00.000Z');
+ const endDate = new Date('2026-10-18T23:59:59.000Z');
+ searchByKeyword.mockResolvedValue({
+ hasMore: false,
+ items: [
+ {
+ createdAt: new Date('2026-10-15T00:00:00.000Z'),
+ id: 'msg_1',
+ role: 'user',
+ snippet: 'STAMP mode',
+ topicId: 'tpc_1',
+ topicTitle: 'Weekly',
+ },
+ ],
+ });
+ search.mockImplementation(async ({ type }: { type: string }) =>
+ type === 'page'
+ ? [
+ {
+ id: 'docs_in',
+ title: 'STAMP notes',
+ type: 'page',
+ updatedAt: new Date('2026-10-16T00:00:00.000Z'),
+ },
+ ]
+ : [],
+ );
+ searchGoals.mockResolvedValue([{ id: 'goal_1', title: 'Replica (STAMP)', type: 'goal' }]);
+ const caller = searchRouter.createCaller({ userId: 'test-user' } as any);
+
+ const result = await caller.recall({ endDate, exact: true, query: 'STAMP', startDate });
+
+ expect(searchByKeyword).toHaveBeenCalledWith(
+ expect.objectContaining({ endDate, exact: true, keyword: 'STAMP', startDate }),
+ );
+ expect(searchGoals).toHaveBeenCalledWith({ endDate, limit: 10, query: 'STAMP', startDate });
+ expect(result.messages.items.map(({ id }) => id)).toEqual(['msg_1']);
+ expect(result.topics).toMatchObject([{ hitCount: 1, id: 'tpc_1', title: 'Weekly' }]);
+ expect(result.goals.map(({ id }) => id)).toEqual(['goal_1']);
+ expect(result.pages.map(({ id }) => id)).toEqual(['docs_in']);
+ // The window reaches the repository, which applies it during retrieval.
+ expect(search).toHaveBeenCalledWith(
+ expect.objectContaining({
+ excludeKnowledgeBaseIds: expect.any(Array),
+ timeRange: { end: endDate, field: 'updatedAt', start: startDate },
+ type: 'page',
+ }),
+ );
+ expect(DiscoverService).not.toHaveBeenCalled();
+ expect(UserModel.findById).not.toHaveBeenCalled();
+ });
+
+ it('runs a goal-only recall without initializing full-text search', async () => {
+ vi.mocked(createFtsSearchRepo).mockRejectedValue(new Error('provider unavailable'));
+ searchGoals.mockResolvedValue([{ id: 'goal_1', title: 'Replica', type: 'goal' }]);
+ const caller = searchRouter.createCaller({ userId: 'test-user' } as any);
+
+ const result = await caller.recall({ query: 'replica', types: ['goal'] });
+
+ expect(result.goals.map(({ id }) => id)).toEqual(['goal_1']);
+ expect(createFtsSearchRepo).not.toHaveBeenCalled();
+ expect(MessageModel).not.toHaveBeenCalled();
+ });
+ });
});
diff --git a/apps/server/src/routers/lambda/__tests__/shareVisitorEntryGuard.router.test.ts b/apps/server/src/routers/lambda/__tests__/shareVisitorEntryGuard.router.test.ts
index 6ea5d409244..09dcab488d7 100644
--- a/apps/server/src/routers/lambda/__tests__/shareVisitorEntryGuard.router.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/shareVisitorEntryGuard.router.test.ts
@@ -52,6 +52,7 @@ const mockMessageDeleteMessagesBySession = vi.fn();
const mockMessageUpdateTTS = vi.fn();
const mockMessageUpdateTranslate = vi.fn();
vi.mock('@/database/models/message', () => ({
+ MESSAGE_KEYWORD_SEARCH_MAX_LIMIT: 100,
MessageModel: vi.fn(function () {
return {
deleteMessagesBySession: mockMessageDeleteMessagesBySession,
diff --git a/apps/server/src/routers/lambda/message.ts b/apps/server/src/routers/lambda/message.ts
index fc8ef1e7be7..9aa2b283b41 100644
--- a/apps/server/src/routers/lambda/message.ts
+++ b/apps/server/src/routers/lambda/message.ts
@@ -15,7 +15,7 @@ import {
cloudWorkspaceAuth,
wsCompatProcedure,
} from '@/business/server/trpc-middlewares/workspaceAuth';
-import { MessageModel } from '@/database/models/message';
+import { MESSAGE_KEYWORD_SEARCH_MAX_LIMIT, MessageModel } from '@/database/models/message';
import { TopicShareModel } from '@/database/models/topicShare';
import { CompressionRepository } from '@/database/repositories/compression';
import { TopicDoctorRepo } from '@/database/repositories/topicDoctor';
@@ -695,6 +695,31 @@ export const messageRouter = router({
return ctx.messageModel.queryByKeyword(input.keywords);
}),
+ /**
+ * Filtered, paginated history search for CLI and agent callers. Returns a
+ * lean projection (topic title, snippet) instead of full message rows, and
+ * hides system-written prompts of automation topics unless asked.
+ */
+ searchByKeyword: messageSearchProcedure
+ .input(
+ z.object({
+ agentId: z.string().optional(),
+ endDate: z.coerce.date().optional(),
+ exact: z.boolean().optional(),
+ includeAutomatedPrompts: z.boolean().optional(),
+ keywords: z.string(),
+ limit: z.number().int().min(1).max(MESSAGE_KEYWORD_SEARCH_MAX_LIMIT).optional(),
+ offset: z.number().int().min(0).optional(),
+ roles: z.array(z.string()).optional(),
+ startDate: z.coerce.date().optional(),
+ topicId: z.string().optional(),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ const { keywords, ...params } = input;
+ return ctx.messageModel.searchByKeyword({ ...params, keyword: keywords });
+ }),
+
update: messageProcedure
.use(withScopedPermission('message:update'))
.input(
diff --git a/apps/server/src/routers/lambda/search.ts b/apps/server/src/routers/lambda/search.ts
index 8ac6a33dd9e..d79e9178350 100644
--- a/apps/server/src/routers/lambda/search.ts
+++ b/apps/server/src/routers/lambda/search.ts
@@ -2,11 +2,14 @@ import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
+import { MessageModel } from '@/database/models/message';
+import { GoalSearchRepo } from '@/database/repositories/goalSearch';
import { TaskSearchRepo } from '@/database/repositories/taskSearch';
import { router } from '@/libs/trpc/lambda';
import { resolveMarketUserContext, serverDatabase } from '@/libs/trpc/lambda/middleware';
import { DiscoverService } from '@/server/services/discover';
import { createFtsSearchRepo } from '@/server/services/ftsSearch';
+import { RECALL_MAX_LIMIT_PER_TYPE, RECALL_TYPES, RecallService } from '@/server/services/recall';
import { getRestrictedKnowledgeBaseIds } from './_helpers/knowledgeBaseAccess';
@@ -67,6 +70,15 @@ const searchProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =
});
});
+/** Memoizes an async factory so concurrent callers share one initialization. */
+const once = <T>(load: () => Promise<T>) => {
+ let pending: Promise<T> | undefined;
+ return () => (pending ??= load());
+};
+
+/** Recall is DB-only, so it skips the marketplace identity lookup entirely. */
+const recallProcedure = wsCompatProcedure.use(serverDatabase);
+
/**
* The unified search router for all entities in the database.
*
@@ -85,6 +97,12 @@ export const searchRouter = router({
* always queries the marketplace, other types never do.
*/
includeMarketplace: z.boolean().optional(),
+ /**
+ * Whether an untyped search also returns goals (default false). The
+ * command menu has no goal rendering yet; the CLI opts in. `type:
+ * 'goal'` always searches goals.
+ */
+ includeGoals: z.boolean().optional(),
limitPerType: z.number().optional(),
locale: z.string().optional(),
offset: z.number().optional(),
@@ -104,6 +122,7 @@ export const searchRouter = router({
'communityAgent',
'knowledgeBase',
'task',
+ 'goal',
])
.optional(),
}),
@@ -162,6 +181,16 @@ export const searchRouter = router({
);
}
+ // Goals are not in the full-text index either; untyped searches opt in.
+ if (type === 'goal' || (!type && input.includeGoals)) {
+ searchPromises.push(
+ new GoalSearchRepo(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined).search({
+ limit: limitPerType,
+ query,
+ }),
+ );
+ }
+
// Marketplace searches: see `includeMarketplace` on the input schema —
// untyped searches include them by default, the command menu opts out.
const marketplaceEnabled = wantsMarketplace(input);
@@ -288,4 +317,63 @@ export const searchRouter = router({
// instead of re-sorting the merged list by relevance.
return results.flat();
}),
+
+ /**
+ * History recall for agents and the CLI: messages, topics, goals and pages
+ * matching a query inside an optional time window, grouped by type. Never
+ * reaches the marketplace.
+ */
+ recall: recallProcedure
+ .input(
+ z.object({
+ endDate: z.coerce.date().optional(),
+ exact: z.boolean().optional(),
+ includeAutomatedPrompts: z.boolean().optional(),
+ limitPerType: z.number().int().min(1).max(RECALL_MAX_LIMIT_PER_TYPE).optional(),
+ query: z.string(),
+ startDate: z.coerce.date().optional(),
+ types: z.array(z.enum(RECALL_TYPES)).optional(),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ const workspaceId = ctx.workspaceId ?? undefined;
+ // Dependencies resolve on first use, so a goal-only recall never needs
+ // the full-text provider (or the restricted-KB lookup) to be available.
+ const entitySearch = once(async () => {
+ const [excludeKnowledgeBaseIds, repo] = await Promise.all([
+ getRestrictedKnowledgeBaseIds(ctx),
+ createFtsSearchRepo({
+ db: ctx.serverDB,
+ userId: ctx.userId,
+ usage: 'unified_search',
+ workspaceId,
+ }),
+ ]);
+ return { excludeKnowledgeBaseIds, repo };
+ });
+ const messageModel = once(
+ async () =>
+ new MessageModel(
+ ctx.serverDB,
+ ctx.userId,
+ workspaceId,
+ await createFtsSearchRepo({
+ db: ctx.serverDB,
+ userId: ctx.userId,
+ usage: 'message_search',
+ workspaceId,
+ }),
+ ),
+ );
+ const goalSearchRepo = new GoalSearchRepo(ctx.serverDB, ctx.userId, workspaceId);
+
+ return new RecallService({
+ searchEntities: async (options) => {
+ const { excludeKnowledgeBaseIds, repo } = await entitySearch();
+ return repo.search({ ...options, excludeKnowledgeBaseIds });
+ },
+ searchGoals: goalSearchRepo.search,
+ searchMessages: async (params) => (await messageModel()).searchByKeyword(params),
+ }).recall(input);
+ }),
});
diff --git a/apps/server/src/services/recall/index.test.ts b/apps/server/src/services/recall/index.test.ts
new file mode 100644
index 00000000000..0fad98597cf
--- /dev/null
+++ b/apps/server/src/services/recall/index.test.ts
@@ -0,0 +1,186 @@
+// @vitest-environment node
+import { describe, expect, it, vi } from 'vitest';
+
+import type { RecallDependencies } from './index';
+import { RecallService } from './index';
+
+const at = (iso: string) => new Date(iso);
+
+const message = (id: string, topicId: string | null, createdAt: string, topicTitle = 'Topic') => ({
+ agentId: null,
+ contentLength: 10,
+ createdAt: at(createdAt),
+ id,
+ role: 'user',
+ snippet: id,
+ threadId: null,
+ topicId,
+ topicTitle,
+});
+
+const createDeps = (overrides: Partial<RecallDependencies> = {}): RecallDependencies => ({
+ searchEntities: vi.fn().mockResolvedValue([]),
+ searchGoals: vi.fn().mockResolvedValue([]),
+ searchMessages: vi.fn().mockResolvedValue({ hasMore: false, items: [] }),
+ ...overrides,
+});
+
+describe('RecallService', () => {
+ it('returns nothing and queries nothing for a blank query', async () => {
+ const deps = createDeps();
+
+ const result = await new RecallService(deps).recall({ query: ' ' });
+
+ expect(result).toEqual({
+ goals: [],
+ messages: { hasMore: false, items: [], truncated: false },
+ pages: [],
+ topics: [],
+ });
+ expect(deps.searchMessages).not.toHaveBeenCalled();
+ });
+
+ it('rolls message hits up into topics and merges title matches', async () => {
+ const deps = createDeps({
+ searchEntities: vi.fn().mockImplementation(async ({ type }) =>
+ type === 'topic'
+ ? [
+ {
+ id: 'tpc_a',
+ title: 'A title',
+ type: 'topic',
+ updatedAt: at('2026-10-16T00:00:00Z'),
+ },
+ {
+ id: 'tpc_c',
+ title: 'C title',
+ type: 'topic',
+ updatedAt: at('2026-10-17T00:00:00Z'),
+ },
+ ]
+ : [],
+ ),
+ searchMessages: vi.fn().mockResolvedValue({
+ hasMore: false,
+ items: [
+ message('m3', 'tpc_b', '2026-10-15T00:00:00Z', 'B'),
+ message('m2', 'tpc_a', '2026-10-14T00:00:00Z', 'A'),
+ message('m1', 'tpc_b', '2026-10-13T00:00:00Z', 'B'),
+ message('m0', null, '2026-10-12T00:00:00Z'),
+ ],
+ }),
+ });
+
+ const result = await new RecallService(deps).recall({
+ endDate: at('2026-10-18T23:59:59Z'),
+ query: 'replica',
+ startDate: at('2026-10-12T00:00:00Z'),
+ });
+
+ expect(result.topics).toEqual([
+ {
+ hitCount: 2,
+ id: 'tpc_b',
+ lastMatchedAt: at('2026-10-15T00:00:00Z'),
+ matchedBy: ['messages'],
+ title: 'B',
+ updatedAt: null,
+ },
+ {
+ hitCount: 1,
+ id: 'tpc_a',
+ lastMatchedAt: at('2026-10-14T00:00:00Z'),
+ matchedBy: ['title', 'messages'],
+ title: 'A',
+ updatedAt: at('2026-10-16T00:00:00Z'),
+ },
+ {
+ hitCount: 0,
+ id: 'tpc_c',
+ lastMatchedAt: null,
+ matchedBy: ['title'],
+ title: 'C title',
+ updatedAt: at('2026-10-17T00:00:00Z'),
+ },
+ ]);
+ });
+
+ it('trims messages to the per-type limit while keeping the wider pool for topics', async () => {
+ const items = Array.from({ length: 5 }, (_, i) =>
+ message(`m${i}`, `tpc_${i}`, `2026-10-1${5 - i}T00:00:00Z`),
+ );
+ const deps = createDeps({
+ searchMessages: vi.fn().mockResolvedValue({ hasMore: false, items }),
+ });
+
+ const result = await new RecallService(deps).recall({ limitPerType: 2, query: 'x' });
+
+ expect(deps.searchMessages).toHaveBeenCalledWith(expect.objectContaining({ limit: 100 }));
+ expect(result.messages.items.map(({ id }) => id)).toEqual(['m0', 'm1']);
+ expect(result.messages.hasMore).toBe(true);
+ expect(result.topics).toHaveLength(2);
+ });
+
+ it('only runs the requested types', async () => {
+ const deps = createDeps({
+ searchGoals: vi.fn().mockResolvedValue([{ id: 'goal_1', type: 'goal' }]),
+ });
+
+ const result = await new RecallService(deps).recall({ query: 'x', types: ['goal'] });
+
+ expect(result.goals).toEqual([{ id: 'goal_1', type: 'goal' }]);
+ expect(deps.searchMessages).not.toHaveBeenCalled();
+ expect(deps.searchEntities).not.toHaveBeenCalled();
+ });
+
+ it('pushes the window into topic and page retrieval instead of trimming afterwards', async () => {
+ const deps = createDeps({
+ searchEntities: vi.fn().mockImplementation(async ({ type }) =>
+ type === 'page'
+ ? [
+ {
+ description: null,
+ id: 'p_in',
+ title: 'In',
+ type: 'page',
+ updatedAt: at('2026-10-14T00:00:00Z'),
+ },
+ ]
+ : [],
+ ),
+ });
+ const startDate = at('2026-10-12T00:00:00Z');
+
+ const result = await new RecallService(deps).recall({
+ limitPerType: 4,
+ query: 'x',
+ startDate,
+ types: ['page', 'topic'],
+ });
+
+ for (const type of ['page', 'topic']) {
+ expect(deps.searchEntities).toHaveBeenCalledWith({
+ limitPerType: 4,
+ query: 'x',
+ timeRange: { end: undefined, field: 'updatedAt', start: startDate },
+ type,
+ });
+ }
+ expect(result.pages).toEqual([
+ { description: null, id: 'p_in', title: 'In', updatedAt: at('2026-10-14T00:00:00Z') },
+ ]);
+ });
+
+ it('passes no window when none is given and surfaces message truncation', async () => {
+ const deps = createDeps({
+ searchMessages: vi.fn().mockResolvedValue({ hasMore: false, items: [], truncated: true }),
+ });
+
+ const result = await new RecallService(deps).recall({ query: 'x', types: ['message', 'page'] });
+
+ expect(deps.searchEntities).toHaveBeenCalledWith(
+ expect.objectContaining({ timeRange: undefined, type: 'page' }),
+ );
+ expect(result.messages.truncated).toBe(true);
+ });
+});
diff --git a/apps/server/src/services/recall/index.ts b/apps/server/src/services/recall/index.ts
new file mode 100644
index 00000000000..2b81b020492
--- /dev/null
+++ b/apps/server/src/services/recall/index.ts
@@ -0,0 +1,198 @@
+import type {
+ MessageKeywordSearchItem,
+ MessageKeywordSearchParams,
+ MessageKeywordSearchResult,
+} from '@/database/models/message';
+import type {
+ FtsSearchGoalResult,
+ FtsSearchResult,
+ FtsSearchTimeRange,
+} from '@/database/repositories/ftsSearch';
+import type { GoalSearchOptions } from '@/database/repositories/goalSearch';
+
+export const RECALL_TYPES = ['message', 'topic', 'goal', 'page'] as const;
+export type RecallType = (typeof RECALL_TYPES)[number];
+
+export const RECALL_MAX_LIMIT_PER_TYPE = 50;
+
+/**
+ * Messages are fetched in one wider page so the topic roll-up reflects more
+ * history than the message list shows; it stays within the model's page cap.
+ */
+const MESSAGE_POOL_SIZE = 100;
+
+export interface RecallInput {
+ endDate?: Date;
+ exact?: boolean;
+ includeAutomatedPrompts?: boolean;
+ limitPerType?: number;
+ query: string;
+ startDate?: Date;
+ types?: RecallType[];
+}
+
+export interface RecallTopic {
+ /** Matching messages in the window, counted within the fetched message pool. */
+ hitCount: number;
+ id: string;
+ lastMatchedAt: Date | null;
+ matchedBy: ('messages' | 'title')[];
+ title: string | null;
+ updatedAt: Date | null;
+}
+
+export interface RecallPage {
+ description: string | null;
+ id: string;
+ title: string;
+ updatedAt: Date;
+}
+
+export interface RecallResult {
+ goals: FtsSearchGoalResult[];
+ messages: { hasMore: boolean; items: MessageKeywordSearchItem[]; truncated: boolean };
+ pages: RecallPage[];
+ topics: RecallTopic[];
+}
+
+export interface RecallDependencies {
+ /** Must apply `timeRange` during retrieval, not after a ranked cut. */
+ searchEntities: (options: {
+ limitPerType: number;
+ query: string;
+ timeRange?: FtsSearchTimeRange;
+ type: 'page' | 'topic';
+ }) => Promise<FtsSearchResult[]>;
+ searchGoals: (options: GoalSearchOptions) => Promise<FtsSearchGoalResult[]>;
+ searchMessages: (params: MessageKeywordSearchParams) => Promise<MessageKeywordSearchResult>;
+}
+
+/**
+ * "What did I do about X in this period": one query across messages, topics,
+ * goals and pages, each scoped to the caller and to the time window. Topics
+ * merge title matches with the conversations whose messages matched, so a
+ * topic named differently from the query still surfaces.
+ */
+export class RecallService {
+ constructor(private readonly deps: RecallDependencies) {}
+
+ recall = async ({
+ endDate,
+ exact,
+ includeAutomatedPrompts,
+ limitPerType = 10,
+ query,
+ startDate,
+ types,
+ }: RecallInput): Promise<RecallResult> => {
+ const empty: RecallResult = {
+ goals: [],
+ messages: { hasMore: false, items: [], truncated: false },
+ pages: [],
+ topics: [],
+ };
+ const text = query.trim();
+ if (!text) return empty;
+
+ const limit = Math.min(Math.max(limitPerType, 1), RECALL_MAX_LIMIT_PER_TYPE);
+ const wanted = new Set<RecallType>(types?.length ? types : RECALL_TYPES);
+ const wantsMessagePool = wanted.has('message') || wanted.has('topic');
+ // Topic titles and pages count as active in the window when last updated in it.
+ const timeRange: FtsSearchTimeRange | undefined =
+ startDate || endDate ? { end: endDate, field: 'updatedAt', start: startDate } : undefined;
+
+ const [messagePool, topicHits, goals, pageHits] = await Promise.all([
+ wantsMessagePool
+ ? this.deps.searchMessages({
+ endDate,
+ exact,
+ includeAutomatedPrompts,
+ keyword: text,
+ limit: Math.max(MESSAGE_POOL_SIZE, limit),
+ startDate,
+ })
+ : undefined,
+ wanted.has('topic')
+ ? this.deps.searchEntities({ limitPerType: limit, query: text, timeRange, type: 'topic' })
+ : [],
+ wanted.has('goal') ? this.deps.searchGoals({ endDate, limit, query: text, startDate }) : [],
+ wanted.has('page')
+ ? this.deps.searchEntities({ limitPerType: limit, query: text, timeRange, type: 'page' })
+ : [],
+ ]);
+
+ const poolItems = messagePool?.items ?? [];
+
+ return {
+ goals,
+ messages: wanted.has('message')
+ ? {
+ hasMore: poolItems.length > limit || Boolean(messagePool?.hasMore),
+ items: poolItems.slice(0, limit),
+ truncated: Boolean(messagePool?.truncated),
+ }
+ : empty.messages,
+ pages: pageHits
+ .filter((hit) => hit.type === 'page')
+ .slice(0, limit)
+ .map(({ description, id, title, updatedAt }) => ({
+ description: description ?? null,
+ id,
+ title,
+ updatedAt,
+ })),
+ topics: wanted.has('topic') ? mergeTopics(poolItems, topicHits, limit) : [],
+ };
+ };
+}
+
+const mergeTopics = (
+ messages: MessageKeywordSearchItem[],
+ topicHits: FtsSearchResult[],
+ limit: number,
+): RecallTopic[] => {
+ const topics = new Map<string, RecallTopic>();
+
+ for (const message of messages) {
+ if (!message.topicId) continue;
+ const topic = topics.get(message.topicId);
+ if (topic) {
+ topic.hitCount += 1;
+ continue;
+ }
+ // Messages arrive newest first, so the first one seen is the latest match.
+ topics.set(message.topicId, {
+ hitCount: 1,
+ id: message.topicId,
+ lastMatchedAt: message.createdAt,
+ matchedBy: ['messages'],
+ title: message.topicTitle,
+ updatedAt: null,
+ });
+ }
+
+ for (const hit of topicHits) {
+ if (hit.type !== 'topic') continue;
+ const topic = topics.get(hit.id);
+ if (topic) {
+ topic.matchedBy.unshift('title');
+ topic.updatedAt = hit.updatedAt;
+ continue;
+ }
+ topics.set(hit.id, {
+ hitCount: 0,
+ id: hit.id,
+ lastMatchedAt: null,
+ matchedBy: ['title'],
+ title: hit.title,
+ updatedAt: hit.updatedAt,
+ });
+ }
+
+ const latest = (topic: RecallTopic) =>
+ Math.max(topic.lastMatchedAt?.getTime() ?? 0, topic.updatedAt?.getTime() ?? 0);
+
+ return [...topics.values()]
+ .sort((a, b) => b.hitCount - a.hitCount || latest(b) - latest(a))
+ .slice(0, limit);
+};
diff --git a/packages/builtin-skills/src/lobehub/content.ts b/packages/builtin-skills/src/lobehub/content.ts
index 96bea2058b6..b78d3b61dac 100644
--- a/packages/builtin-skills/src/lobehub/content.ts
+++ b/packages/builtin-skills/src/lobehub/content.ts
@@ -54,7 +54,7 @@ run commands.
| \`lh kb\` | Knowledge base management (create, upload, organize) | \`references/kb\` |
| \`lh file\` | File management | \`references/file\` |
| \`lh memory\` | User memory management (identity, activity, preference) | \`references/memory\` |
-| \`lh search\` | Search local resources or the web | \`references/search\` |
+| \`lh search\` / \`lh recall\` | Search local resources or the web / recall past work in a time window | \`references/search\` |
| \`lh gen\` | Content generation (text, image, video, TTS, ASR) | \`references/generate\` |
| \`lh project\` / \`lh task\` | Projects and agent tasks | \`references/project\` |
| \`lh goal\` | Long-running goal graphs | \`references/goal\` |
@@ -107,7 +107,10 @@ lh kb list
lh kb create-doc <kbId> -t "Meeting Notes" -c "..."
# Search messages
-lh message search "deployment issue"
+lh message search "deployment issue" --since 7d
+
+# Recall everything about a topic from last week (messages, topics, goals, pages)
+lh recall "replica" --since 2026-10-12 --until 2026-10-18
# Generate an image
lh gen image "a sunset over mountains" -m dall-e-3
diff --git a/packages/builtin-skills/src/lobehub/references/message.ts b/packages/builtin-skills/src/lobehub/references/message.ts
index 09d3719fb96..565aef2dfeb 100644
--- a/packages/builtin-skills/src/lobehub/references/message.ts
+++ b/packages/builtin-skills/src/lobehub/references/message.ts
@@ -5,7 +5,7 @@ Manage chat messages.
## Subcommands
- \`lh message list [--topic-id <id>] [--agent-id <id>] [-L <limit>] [--page <n>]\` - List messages
-- \`lh message search <keywords>\` - Search messages by keywords
+- \`lh message search <keywords> [--since <when>] [--until <when>] [--role <roles>] [--topic-id <id>] [--agent-id <id>] [--exact] [--include-system] [-L <n>] [-P <n>]\` - Search messages, newest first, with time, topic title and a match snippet
- \`lh message delete <ids...> [--yes]\` - Delete messages
- \`lh message count [--start <date>] [--end <date>]\` - Count messages
- \`lh message heatmap\` - Get message activity heatmap
@@ -21,6 +21,8 @@ Use it to report back to a conversation after background work finishes.
- Filter by \`--topic-id\` to get messages from a specific conversation
- Use \`--user\` flag to filter by message role (user/assistant)
+- \`message search\` hides system-written prompts of task, cron and eval runs; \`--include-system\` shows them
+- For "what happened around X this week", prefer \`lh recall\` (see \`references/search\`): it also covers topics, goals and pages
`;
export default content;
diff --git a/packages/builtin-skills/src/lobehub/references/search.ts b/packages/builtin-skills/src/lobehub/references/search.ts
index a96c9de7768..2e7775c8ce7 100644
--- a/packages/builtin-skills/src/lobehub/references/search.ts
+++ b/packages/builtin-skills/src/lobehub/references/search.ts
@@ -1,16 +1,29 @@
-const content = `# lh search - Search Resources
+const content = `# lh search / lh recall - Search Resources and History
-Search local resources or the web.
+Search local resources or the web, or recall past work inside a time window.
## Subcommands
- \`lh search -q <query> [-t <type>] [-L <limit>]\` - Search local resources
- \`lh search -q <query> -w [-e <engines>] [-c <categories>]\` - Search the web
- \`lh search view <target>\` - View search result details or crawl a URL
+- \`lh recall <query> [--since <when>] [--until <when>] [-t message,topic,goal,page] [--exact] [-L <n>]\` - Matching messages, conversations, goals and pages in one window
## Search Types (local)
-agent, topic, file, folder, message, page, memory, mcp, plugin, communityAgent, knowledgeBase
+agent, topic, file, folder, message, page, memory, mcp, plugin, communityAgent, knowledgeBase, task, goal
+
+## Recalling past work
+
+Use \`lh recall\` for questions like "what did I do about X last week" (weekly reports, retros, picking up an
+earlier thread). One call replaces paging through \`lh message list\` and grepping locally.
+
+- \`--since\` / \`--until\` take an ISO time, a local day (\`2026-10-12\`), or a relative span (\`24h\`, \`7d\`, \`2w\`)
+- Topics merge title matches with conversations whose messages matched, so a topic named differently still shows up
+- Goals are matched by title and requirement; internal code names often live there rather than in messages
+- \`--exact\` makes message matching a case-sensitive whole-term match, so an acronym like \`STAMP\` stops matching "stamp" or "STAMPED"
+- System-written prompts of task, cron and eval runs are hidden; add \`--include-system\` to see them
+- Follow up with \`lh topic view <id>\`, \`lh goal show <id>\` or \`lh doc view <id>\`
## Tips
diff --git a/packages/database/src/models/__tests__/messages/message.keywordSearch.test.ts b/packages/database/src/models/__tests__/messages/message.keywordSearch.test.ts
new file mode 100644
index 00000000000..f44a7570eda
--- /dev/null
+++ b/packages/database/src/models/__tests__/messages/message.keywordSearch.test.ts
@@ -0,0 +1,412 @@
+import { eq } from 'drizzle-orm';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { agents, chatGroups, messages, topics, users } from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { MessageModel } from '../../message';
+import { buildMessageSnippet, MESSAGE_KEYWORD_SEARCH_CANDIDATE_POOL } from '../../message/search';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'message-keyword-search-test';
+const otherUserId = 'message-keyword-search-test-other';
+
+/**
+ * Keyword retrieval belongs to the provider (BM25 needs pg_search, which PGlite
+ * lacks), so these tests hand back every seeded row as a candidate and assert
+ * the filters, projection and paging applied by PostgreSQL hydration.
+ */
+const modelWithCandidates = (ids: string[]) =>
+ new MessageModel(serverDB, userId, undefined, {
+ ftsSearchCandidateEnabled: true,
+ ftsSearchCandidates: vi.fn().mockResolvedValue({
+ candidates: ids.map((id) => ({ id, score: 1 })),
+ total: ids.length,
+ }),
+ });
+
+beforeEach(async () => {
+ await serverDB.delete(users).where(eq(users.id, userId));
+ await serverDB.delete(users).where(eq(users.id, otherUserId));
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ await serverDB.insert(agents).values([{ id: 'kw-agent', title: 'Agent', userId }]);
+ await serverDB.insert(topics).values([
+ { id: 'kw-chat', title: 'Weekly planning', trigger: 'chat', userId },
+ { id: 'kw-task', title: 'T-472 daily report', trigger: 'task', userId },
+ { id: 'kw-eval', title: 'BrowseComp', trigger: 'eval', userId },
+ { id: 'kw-doc', title: 'Doc chat', trigger: 'document', userId },
+ ]);
+});
+
+const seed = async (rows: (typeof messages.$inferInsert)[]) => {
+ await serverDB.insert(messages).values(rows);
+ return modelWithCandidates(rows.map(({ id }) => id!));
+};
+
+describe('MessageModel.searchByKeyword', () => {
+ it('returns topic titles, snippets and recency order, scoped to the caller', async () => {
+ const messageModel = await seed([
+ {
+ content: 'older note about replica rollout',
+ createdAt: new Date('2026-10-12T00:00:00.000Z'),
+ id: 'kw-old',
+ role: 'user',
+ topicId: 'kw-chat',
+ userId,
+ },
+ {
+ content: 'newer replica summary',
+ createdAt: new Date('2026-10-15T00:00:00.000Z'),
+ id: 'kw-new',
+ role: 'assistant',
+ topicId: 'kw-chat',
+ userId,
+ },
+ { content: 'replica from someone else', id: 'kw-other', role: 'user', userId: otherUserId },
+ ]);
+
+ const result = await messageModel.searchByKeyword({ keyword: 'replica' });
+
+ expect(result.hasMore).toBe(false);
+ expect(result.items.map(({ id }) => id)).toEqual(['kw-new', 'kw-old']);
+ expect(result.items[0]).toMatchObject({
+ role: 'assistant',
+ snippet: 'newer replica summary',
+ topicId: 'kw-chat',
+ topicTitle: 'Weekly planning',
+ });
+ });
+
+ it('retains groupId so a group-chat hit keeps its route', async () => {
+ await serverDB.insert(chatGroups).values([{ id: 'kw-group', title: 'Squad', userId }]);
+ const messageModel = await seed([
+ {
+ content: 'group replica handoff',
+ groupId: 'kw-group',
+ id: 'kw-group-msg',
+ role: 'user',
+ userId,
+ },
+ ]);
+
+ const result = await messageModel.searchByKeyword({ keyword: 'replica' });
+
+ // A group message carries `groupId` rather than `agentId`; the CLI resolves
+ // its URL from these two, so the projection has to keep the group ref.
+ expect(result.items[0]).toMatchObject({
+ agentId: null,
+ groupId: 'kw-group',
+ id: 'kw-group-msg',
+ });
+ });
+
+ it('filters by time range, role, topic and agent', async () => {
+ const messageModel = await seed([
+ {
+ agentId: 'kw-agent',
+ content: 'goal review in range',
+ createdAt: new Date('2026-10-14T00:00:00.000Z'),
+ id: 'kw-in',
+ role: 'user',
+ topicId: 'kw-chat',
+ userId,
+ },
+ {
+ content: 'goal review before range',
+ createdAt: new Date('2026-10-01T00:00:00.000Z'),
+ id: 'kw-before',
+ role: 'user',
+ topicId: 'kw-chat',
+ userId,
+ },
+ {
+ content: 'goal review reply',
+ createdAt: new Date('2026-10-14T01:00:00.000Z'),
+ id: 'kw-reply',
+ role: 'assistant',
+ topicId: 'kw-doc',
+ userId,
+ },
+ ]);
+
+ const range = {
+ endDate: new Date('2026-10-18T23:59:59.000Z'),
+ keyword: 'goal review',
+ startDate: new Date('2026-10-12T00:00:00.000Z'),
+ };
+
+ const inRange = await messageModel.searchByKeyword(range);
+ expect(inRange.items.map(({ id }) => id)).toEqual(['kw-reply', 'kw-in']);
+
+ const userOnly = await messageModel.searchByKeyword({ ...range, roles: ['user'] });
+ expect(userOnly.items.map(({ id }) => id)).toEqual(['kw-in']);
+
+ const byTopic = await messageModel.searchByKeyword({ ...range, topicId: 'kw-doc' });
+ expect(byTopic.items.map(({ id }) => id)).toEqual(['kw-reply']);
+
+ const byAgent = await messageModel.searchByKeyword({ ...range, agentId: 'kw-agent' });
+ expect(byAgent.items.map(({ id }) => id)).toEqual(['kw-in']);
+ });
+
+ it('hides system-written prompts of automation topics unless asked', async () => {
+ const messageModel = await seed([
+ {
+ content: '<task> latency report </task>',
+ id: 'kw-task-prompt',
+ role: 'user',
+ topicId: 'kw-task',
+ userId,
+ },
+ {
+ content: 'latency report delivered',
+ id: 'kw-task-reply',
+ role: 'assistant',
+ topicId: 'kw-task',
+ userId,
+ },
+ {
+ content: 'eval latency report question',
+ id: 'kw-eval-prompt',
+ role: 'user',
+ topicId: 'kw-eval',
+ userId,
+ },
+ {
+ content: 'my latency report idea',
+ id: 'kw-doc-prompt',
+ role: 'user',
+ topicId: 'kw-doc',
+ userId,
+ },
+ { content: 'latency report without topic', id: 'kw-no-topic', role: 'user', userId },
+ ]);
+
+ const visible = await messageModel.searchByKeyword({ keyword: 'latency report' });
+ expect(visible.items.map(({ id }) => id).sort()).toEqual([
+ 'kw-doc-prompt',
+ 'kw-no-topic',
+ 'kw-task-reply',
+ ]);
+
+ const all = await messageModel.searchByKeyword({
+ includeAutomatedPrompts: true,
+ keyword: 'latency report',
+ });
+ expect(all.items).toHaveLength(5);
+ });
+
+ it('matches case-sensitively in exact mode', async () => {
+ const messageModel = await seed([
+ {
+ content: 'Rolling out the STAMP mode',
+ id: 'kw-upper',
+ role: 'user',
+ topicId: 'kw-chat',
+ userId,
+ },
+ {
+ content: 'a rare stamp collection',
+ id: 'kw-lower',
+ role: 'user',
+ topicId: 'kw-chat',
+ userId,
+ },
+ ]);
+
+ const loose = await messageModel.searchByKeyword({ keyword: 'STAMP' });
+ expect(loose.items.map(({ id }) => id).sort()).toEqual(['kw-lower', 'kw-upper']);
+
+ const exact = await messageModel.searchByKeyword({ exact: true, keyword: 'STAMP' });
+ expect(exact.items.map(({ id }) => id)).toEqual(['kw-upper']);
+ });
+
+ it('matches whole terms in exact mode, the same on every provider', async () => {
+ const messageModel = await seed([
+ { content: '打通KESTREL模式', id: 'kw-cjk', role: 'user', topicId: 'kw-chat', userId },
+ { content: 'KESTREL.', id: 'kw-punct', role: 'user', topicId: 'kw-chat', userId },
+ { content: 'the KESTRELS flew', id: 'kw-plural', role: 'user', topicId: 'kw-chat', userId },
+ { content: 'MKESTREL build', id: 'kw-prefixed', role: 'user', topicId: 'kw-chat', userId },
+ { content: 'ship C++20 now', id: 'kw-cpp', role: 'user', topicId: 'kw-chat', userId },
+ ]);
+
+ const term = await messageModel.searchByKeyword({ exact: true, keyword: 'KESTREL' });
+ // A tokenizing provider never retrieves "KESTRELS"/"MKESTREL" for KESTREL; pg_like
+ // does, so the PostgreSQL check must drop them for the providers to agree.
+ expect(term.items.map(({ id }) => id).sort()).toEqual(['kw-cjk', 'kw-punct']);
+
+ const partial = await messageModel.searchByKeyword({ exact: true, keyword: 'STREL' });
+ expect(partial.items).toEqual([]);
+
+ const symbol = await messageModel.searchByKeyword({ exact: true, keyword: 'C++' });
+ expect(symbol.items.map(({ id }) => id)).toEqual(['kw-cpp']);
+ });
+
+ it('pages with limit and offset', async () => {
+ const messageModel = await seed(
+ [1, 2, 3].map((n) => ({
+ content: `paging keyword ${n}`,
+ createdAt: new Date(`2026-10-1${n}T00:00:00.000Z`),
+ id: `kw-page-${n}`,
+ role: 'user',
+ topicId: 'kw-chat',
+ userId,
+ })),
+ );
+
+ const first = await messageModel.searchByKeyword({ keyword: 'paging', limit: 2 });
+ expect(first.items.map(({ id }) => id)).toEqual(['kw-page-3', 'kw-page-2']);
+ expect(first.hasMore).toBe(true);
+
+ const second = await messageModel.searchByKeyword({ keyword: 'paging', limit: 2, offset: 2 });
+ expect(second.items.map(({ id }) => id)).toEqual(['kw-page-1']);
+ expect(second.hasMore).toBe(false);
+ });
+
+ it('short-circuits an empty candidate pool', async () => {
+ await serverDB.insert(messages).values([
+ {
+ content: 'candidate in chat',
+ id: 'kw-cand-chat',
+ role: 'user',
+ topicId: 'kw-chat',
+ userId,
+ },
+ {
+ content: 'candidate task prompt',
+ id: 'kw-cand-task',
+ role: 'user',
+ topicId: 'kw-task',
+ userId,
+ },
+ ]);
+ const ftsSearchCandidates = vi
+ .fn()
+ .mockResolvedValueOnce({
+ candidates: [
+ { id: 'kw-cand-task', score: 2 },
+ { id: 'kw-cand-chat', score: 1 },
+ ],
+ total: 2,
+ })
+ .mockResolvedValueOnce({ candidates: [], total: 0 });
+ const model = new MessageModel(serverDB, userId, undefined, {
+ ftsSearchCandidateEnabled: true,
+ ftsSearchCandidates,
+ });
+
+ const result = await model.searchByKeyword({ keyword: 'candidate' });
+ expect(result.items.map(({ id }) => id)).toEqual(['kw-cand-chat']);
+ expect(result.truncated).toBe(false);
+ expect(ftsSearchCandidates).toHaveBeenCalledWith({
+ entity: 'messages',
+ filters: {},
+ pagination: { limit: MESSAGE_KEYWORD_SEARCH_CANDIDATE_POOL },
+ query: { fields: ['content'], text: 'candidate' },
+ });
+
+ const empty = await model.searchByKeyword({ keyword: 'nothing' });
+ expect(empty).toEqual({ hasMore: false, items: [], truncated: false });
+ });
+
+ it('bounds the candidate pool, pushes the window into it and reports truncation', async () => {
+ await serverDB.insert(messages).values([
+ {
+ content: 'bounded pool hit',
+ id: 'kw-pool-hit',
+ role: 'user',
+ topicId: 'kw-chat',
+ userId,
+ },
+ ]);
+ const ftsSearchCandidates = vi.fn().mockResolvedValue({
+ candidates: [{ id: 'kw-pool-hit', score: 1 }],
+ total: 5000,
+ });
+ const model = new MessageModel(serverDB, userId, undefined, {
+ ftsSearchCandidateEnabled: true,
+ ftsSearchCandidates,
+ });
+ const startDate = new Date('2026-10-12T00:00:00.000Z');
+
+ const result = await model.searchByKeyword({ keyword: 'bounded', startDate });
+
+ expect(ftsSearchCandidates).toHaveBeenCalledWith(
+ expect.objectContaining({
+ filters: { timeRange: { end: undefined, field: 'createdAt', start: startDate } },
+ pagination: { limit: MESSAGE_KEYWORD_SEARCH_CANDIDATE_POOL },
+ }),
+ );
+ // The provider matched 5000 rows but returned one: lower-ranked matches were dropped.
+ expect(result.truncated).toBe(true);
+ });
+
+ it('does not report truncation for a complete pool larger than the nominal size', async () => {
+ // Providers over-fetch past the requested pool, so 1,500 of 1,500 is complete.
+ const candidates = Array.from({ length: 1500 }, (_, i) => ({ id: `kw-full-${i}`, score: 1 }));
+ const model = new MessageModel(serverDB, userId, undefined, {
+ ftsSearchCandidateEnabled: true,
+ ftsSearchCandidates: vi.fn().mockResolvedValue({ candidates, total: candidates.length }),
+ });
+
+ const result = await model.searchByKeyword({ keyword: 'complete' });
+
+ expect(candidates.length).toBeGreaterThan(MESSAGE_KEYWORD_SEARCH_CANDIDATE_POOL);
+ expect(result.truncated).toBe(false);
+ });
+
+ it('narrows candidate retrieval to the requested roles, topic and agent', async () => {
+ const ftsSearchCandidates = vi.fn().mockResolvedValue({ candidates: [], total: 0 });
+ const model = new MessageModel(serverDB, userId, undefined, {
+ ftsSearchCandidateEnabled: true,
+ ftsSearchCandidates,
+ });
+
+ await model.searchByKeyword({
+ agentId: 'kw-agent',
+ keyword: 'scoped',
+ roles: ['user'],
+ topicId: 'kw-chat',
+ });
+
+ expect(ftsSearchCandidates).toHaveBeenCalledWith(
+ expect.objectContaining({
+ filters: {
+ messageScope: { roles: ['user'], topicId: 'kw-chat' },
+ topicScope: { agentId: 'kw-agent' },
+ },
+ }),
+ );
+ });
+});
+
+// BM25 retrieval requires the pg_search extension (ParadeDB), not available in PGlite.
+describe.skipIf(process.env.TEST_SERVER_DB !== '1')('MessageModel.searchByKeyword (BM25)', () => {
+ it('retrieves through pg_search when no candidate provider is enabled', async () => {
+ await serverDB.insert(messages).values([
+ { content: 'apple pie recipe', id: 'kw-bm25-hit', role: 'user', topicId: 'kw-chat', userId },
+ { content: 'banana bread', id: 'kw-bm25-miss', role: 'user', topicId: 'kw-chat', userId },
+ ]);
+
+ const result = await new MessageModel(serverDB, userId).searchByKeyword({ keyword: 'apple' });
+
+ expect(result.items.map(({ id }) => id)).toEqual(['kw-bm25-hit']);
+ });
+});
+
+describe('buildMessageSnippet', () => {
+ it('centers on the first match and marks truncation', () => {
+ const content = `${'a'.repeat(200)} needle ${'b'.repeat(300)}`;
+ const snippet = buildMessageSnippet(content, 'needle');
+
+ expect(snippet.startsWith('…')).toBe(true);
+ expect(snippet.endsWith('…')).toBe(true);
+ // The match sits near the front so a truncated table column still shows it.
+ expect(snippet.indexOf('needle')).toBeLessThan(30);
+ });
+
+ it('falls back to a query term and then to the head of the text', () => {
+ expect(buildMessageSnippet('alpha beta', 'missing beta')).toBe('alpha beta');
+ expect(buildMessageSnippet('line one\n\nline two', 'zzz')).toBe('line one line two');
+ });
+});
diff --git a/packages/database/src/models/__tests__/messages/message.publicApi.test.ts b/packages/database/src/models/__tests__/messages/message.publicApi.test.ts
index 0c7f1f66b86..41781202a93 100644
--- a/packages/database/src/models/__tests__/messages/message.publicApi.test.ts
+++ b/packages/database/src/models/__tests__/messages/message.publicApi.test.ts
@@ -116,6 +116,7 @@ describe('MessageModel public API', () => {
it('keeps the runtime exports of the module entry', () => {
expect(Object.keys(messageModule).sort()).toEqual([
'HumanApprovalAlreadyResolvedError',
+ 'MESSAGE_KEYWORD_SEARCH_MAX_LIMIT',
'MessageModel',
'redactCreatorPrivateBlob',
'sanitizeVisitorError',
diff --git a/packages/database/src/models/message/index.ts b/packages/database/src/models/message/index.ts
index 0fd729754c2..d06d66944a2 100644
--- a/packages/database/src/models/message/index.ts
+++ b/packages/database/src/models/message/index.ts
@@ -17,6 +17,7 @@ import { MessageByIdsQueries } from './queryByIds';
import { MessagePageQueries } from './queryWithWhere';
import { MessageRelationQueries } from './relations';
import type { MessageScopeArgs } from './scope';
+import { MessageKeywordSearchQueries } from './search';
import { MessageSpineQueries } from './spine';
import { MessageToolMutations } from './tool';
import { MessageTrashMutations } from './trash';
@@ -42,6 +43,7 @@ export class MessageModel {
queryBySessionId: MessageLookupQueries['queryBySessionId'];
queryByKeyword: MessageLookupQueries['queryByKeyword'];
searchInTopic: MessageLookupQueries['searchInTopic'];
+ searchByKeyword: MessageKeywordSearchQueries['searchByKeyword'];
queryByIds: MessageByIdsQueries['queryByIds'];
@@ -131,6 +133,7 @@ export class MessageModel {
const args: MessageScopeArgs = [db, userId, workspaceId, ftsSearchCandidateSource, options];
const lookups = new MessageLookupQueries(...args);
+ const keywordSearch = new MessageKeywordSearchQueries(args, { lookups });
const relations = new MessageRelationQueries(...args);
const byIds = new MessageByIdsQueries(args, { relations });
const page = new MessagePageQueries(args, { relations, byIds });
@@ -160,6 +163,7 @@ export class MessageModel {
this.queryBySessionId = lookups.queryBySessionId;
this.queryByKeyword = lookups.queryByKeyword;
this.searchInTopic = lookups.searchInTopic;
+ this.searchByKeyword = keywordSearch.searchByKeyword;
this.queryByIds = byIds.queryByIds;
this.queryWithWhere = page.queryWithWhere;
this.queryLastUserMessageByTopics = conversation.queryLastUserMessageByTopics;
@@ -251,5 +255,11 @@ export class MessageModel {
}
export { HumanApprovalAlreadyResolvedError } from './plugin';
+export type {
+ MessageKeywordSearchItem,
+ MessageKeywordSearchParams,
+ MessageKeywordSearchResult,
+} from './search';
+export { MESSAGE_KEYWORD_SEARCH_MAX_LIMIT } from './search';
export * from './types';
export { redactCreatorPrivateBlob, sanitizeVisitorError, toVisitorMessage } from './visitor';
diff --git a/packages/database/src/models/message/search.ts b/packages/database/src/models/message/search.ts
new file mode 100644
index 00000000000..049dd720ac2
--- /dev/null
+++ b/packages/database/src/models/message/search.ts
@@ -0,0 +1,255 @@
+import type { SQL } from 'drizzle-orm';
+import { and, desc, eq, gte, inArray, isNull, lte, ne, notInArray, or, sql } from 'drizzle-orm';
+
+import type { FtsSearchBackendFilters } from '../../repositories/ftsSearch';
+import { messages, topics } from '../../schemas';
+import { sanitizeBm25Query } from '../../utils/bm25';
+import { inJsonStringArray } from '../../utils/inJsonStringArray';
+import { searchableMessage } from '../../utils/searchableMessage';
+import type { MessageLookupQueries } from './lookup';
+import type { MessageScopeArgs } from './scope';
+import { MessageScope } from './scope';
+
+/**
+ * Topic triggers whose `user` turns are written by the system (task runs, cron
+ * jobs, evals, goal supervision), not typed by a person. Their assistant turns
+ * are still real work and stay searchable. Doc-anchored chat (`document`) is
+ * human input and is deliberately absent.
+ */
+export const AUTOMATED_PROMPT_TOPIC_TRIGGERS = [
+ 'cron',
+ 'eval',
+ 'goal_supervision',
+ 'task',
+ 'task_manager',
+];
+
+export const MESSAGE_KEYWORD_SEARCH_MAX_LIMIT = 100;
+
+/**
+ * Requested size of the external candidate pool (Elasticsearch, `pg_like`).
+ * Retrieval is ranked by relevance and filtered here, so an unbounded pool
+ * would walk every match on each page; the time window is pushed into the
+ * provider so the bound applies to an already narrowed set.
+ */
+export const MESSAGE_KEYWORD_SEARCH_CANDIDATE_POOL = 1000;
+
+const DEFAULT_LIMIT = 20;
+/** Short lead-in so the match stays visible in a truncated terminal column. */
+const SNIPPET_BEFORE = 24;
+const SNIPPET_AFTER = 200;
+
+export interface MessageKeywordSearchParams {
+ agentId?: string;
+ endDate?: Date;
+ /**
+ * Case-sensitive whole-term match on top of full-text retrieval: `STAMP`
+ * matches "STAMP mode" but not "stamp" or "STAMPED". Whole terms keep the
+ * result identical across tokenizing (pg_search, Elasticsearch) and
+ * substring (pg_like) providers.
+ */
+ exact?: boolean;
+ /** Keep system-written `user` prompts of automation topics in the results. */
+ includeAutomatedPrompts?: boolean;
+ keyword: string;
+ limit?: number;
+ offset?: number;
+ roles?: string[];
+ startDate?: Date;
+ topicId?: string;
+}
+
+export interface MessageKeywordSearchItem {
+ agentId: string | null;
+ contentLength: number;
+ createdAt: Date;
+ /**
+ * Kept so callers can resolve a group-topic hit back to its group route: a
+ * group message carries `groupId` instead of `agentId`, so dropping it loses
+ * the link (and an agent-only resolver would build the wrong URL).
+ */
+ groupId: string | null;
+ id: string;
+ role: string;
+ snippet: string;
+ threadId: string | null;
+ topicId: string | null;
+ topicTitle: string | null;
+}
+
+export interface MessageKeywordSearchResult {
+ hasMore: boolean;
+ items: MessageKeywordSearchItem[];
+ /**
+ * The provider had more matches than the candidate pool holds, so lower-ranked
+ * matches were not considered. Narrow the window or scope to see them.
+ */
+ truncated: boolean;
+}
+
+const ASCII_WORD = /\w/;
+
+/**
+ * PostgreSQL regex for a case-sensitive whole-term match. A boundary is only
+ * required on a side where the term starts or ends with an ASCII word
+ * character, so `C++` still matches "C++20" and CJK terms match inside CJK text.
+ */
+export const exactTermPattern = (term: string) => {
+ const escaped = term.replaceAll(/[$()*+.?[\\\]^{|}]/g, '\\$&');
+ const left = ASCII_WORD.test(term[0]) ? '(^|[^A-Za-z0-9_])' : '';
+ const right = ASCII_WORD.test(term.at(-1)!) ? '([^A-Za-z0-9_]|$)' : '';
+ return `${left}${escaped}${right}`;
+};
+
+/**
+ * Candidate-side narrowing. Every filter re-applied after hydration that the
+ * index can express goes here, so a bounded pool is cut inside the caller's
+ * scope rather than across all of their messages. The agent filter rides on
+ * `topicScope`, which keeps legacy rows without `agent_id` for the
+ * authoritative session-aware check in PostgreSQL.
+ */
+const candidateFilters = ({
+ agentId,
+ endDate,
+ roles,
+ startDate,
+ topicId,
+}: Pick<
+ MessageKeywordSearchParams,
+ 'agentId' | 'endDate' | 'roles' | 'startDate' | 'topicId'
+>): FtsSearchBackendFilters => ({
+ ...((startDate || endDate) && {
+ timeRange: { end: endDate, field: 'createdAt', start: startDate },
+ }),
+ ...(agentId && { topicScope: { agentId } }),
+ ...((roles?.length || topicId) && {
+ messageScope: { ...(roles?.length && { roles }), ...(topicId && { topicId }) },
+ }),
+});
+
+/**
+ * A window of `content` around the first keyword occurrence, whitespace
+ * collapsed. Falls back to the first query term, then to the head of the text.
+ */
+export const buildMessageSnippet = (content: string, keyword: string, exact?: boolean) => {
+ const haystack = exact ? content : content.toLowerCase();
+ const needles = [keyword.trim(), ...keyword.trim().split(/\s+/)].filter(Boolean);
+ let index = -1;
+ let length = 0;
+ for (const needle of needles) {
+ index = haystack.indexOf(exact ? needle : needle.toLowerCase());
+ if (index !== -1) {
+ length = needle.length;
+ break;
+ }
+ }
+
+ const start = index === -1 ? 0 : Math.max(0, index - SNIPPET_BEFORE);
+ const end = index === -1 ? SNIPPET_BEFORE + SNIPPET_AFTER : index + length + SNIPPET_AFTER;
+ const body = content.slice(start, end).replaceAll(/\s+/g, ' ').trim();
+
+ return `${start > 0 ? '…' : ''}${body}${end < content.length ? '…' : ''}`;
+};
+
+/**
+ * Filtered, paginated keyword search for callers that read history rather than
+ * render a command palette (CLI, agents). Unlike `queryByKeyword` it returns a
+ * lean projection with the parent topic title and a match snippet.
+ */
+export class MessageKeywordSearchQueries extends MessageScope {
+ private lookups: MessageLookupQueries;
+
+ constructor(args: MessageScopeArgs, deps: { lookups: MessageLookupQueries }) {
+ super(...args);
+ this.lookups = deps.lookups;
+ }
+
+ searchByKeyword = async ({
+ agentId,
+ endDate,
+ exact,
+ includeAutomatedPrompts,
+ keyword,
+ limit = DEFAULT_LIMIT,
+ offset = 0,
+ roles,
+ startDate,
+ topicId,
+ }: MessageKeywordSearchParams): Promise<MessageKeywordSearchResult> => {
+ const text = keyword.trim();
+ if (!text) return { hasMore: false, items: [], truncated: false };
+
+ const pageSize = Math.min(Math.max(limit, 1), MESSAGE_KEYWORD_SEARCH_MAX_LIMIT);
+
+ const candidateResult = this.ftsSearchCandidateSource?.ftsSearchCandidateEnabled
+ ? await this.ftsSearchCandidateSource.ftsSearchCandidates({
+ entity: 'messages',
+ filters: candidateFilters({ agentId, endDate, roles, startDate, topicId }),
+ pagination: { limit: MESSAGE_KEYWORD_SEARCH_CANDIDATE_POOL },
+ query: { fields: ['content'], text },
+ })
+ : undefined;
+ const candidateIds = candidateResult?.candidates.map(({ id }) => id);
+ if (candidateIds?.length === 0) return { hasMore: false, items: [], truncated: false };
+ // Providers over-fetch past the requested pool size, so its nominal size
+ // says nothing; only a provider total above what came back means the
+ // cutoff actually dropped lower-ranked matches.
+ const truncated = candidateResult
+ ? candidateResult.total > candidateResult.candidates.length
+ : false;
+
+ const conditions: (SQL | undefined)[] = [
+ this.ownership(),
+ searchableMessage(),
+ candidateIds
+ ? inJsonStringArray(messages.id, candidateIds)
+ : sql`${messages.content} @@@ ${sanitizeBm25Query(text)}`,
+ exact ? sql`${messages.content} ~ ${exactTermPattern(text)}` : undefined,
+ startDate ? gte(messages.createdAt, startDate) : undefined,
+ endDate ? lte(messages.createdAt, endDate) : undefined,
+ roles?.length ? inArray(messages.role, roles) : undefined,
+ topicId ? eq(messages.topicId, topicId) : undefined,
+ agentId ? await this.lookups.buildAgentCondition(agentId) : undefined,
+ includeAutomatedPrompts
+ ? undefined
+ : or(
+ ne(messages.role, 'user'),
+ isNull(topics.trigger),
+ notInArray(topics.trigger, AUTOMATED_PROMPT_TOPIC_TRIGGERS),
+ ),
+ ];
+
+ const rows = await this.db
+ .select({
+ agentId: messages.agentId,
+ content: messages.content,
+ createdAt: messages.createdAt,
+ groupId: messages.groupId,
+ id: messages.id,
+ role: messages.role,
+ summary: messages.summary,
+ threadId: messages.threadId,
+ topicId: messages.topicId,
+ topicTitle: topics.title,
+ })
+ .from(messages)
+ .leftJoin(topics, eq(messages.topicId, topics.id))
+ .where(and(...conditions))
+ .orderBy(desc(messages.createdAt), desc(messages.id))
+ .limit(pageSize + 1)
+ .offset(Math.max(offset, 0));
+
+ return {
+ truncated,
+ hasMore: rows.length > pageSize,
+ items: rows.slice(0, pageSize).map(({ content, summary, ...row }) => {
+ const body = content || summary || '';
+ return {
+ ...row,
+ contentLength: body.length,
+ snippet: buildMessageSnippet(body, text, exact),
+ };
+ }),
+ };
+ };
+}
diff --git a/packages/database/src/repositories/ftsSearch/__tests__/elasticsearch.candidateFilters.test.ts b/packages/database/src/repositories/ftsSearch/__tests__/elasticsearch.candidateFilters.test.ts
new file mode 100644
index 00000000000..bce25941a39
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearch/__tests__/elasticsearch.candidateFilters.test.ts
@@ -0,0 +1,89 @@
+// @vitest-environment node
+import { describe, expect, it, vi } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import type { LobeChatDatabase } from '../../../type';
+import { ElasticsearchFtsSearchBackend, type ElasticsearchFtsSearchClient } from '../elasticsearch';
+import type { FtsSearchBackendRequest } from '../types';
+
+const db: LobeChatDatabase = await getTestDB();
+
+const userId = 'es-time-range-user';
+const start = new Date('2026-10-12T00:00:00.000Z');
+const end = new Date('2026-10-18T23:59:59.000Z');
+
+const createClient = (): ElasticsearchFtsSearchClient => ({
+ search: vi.fn().mockResolvedValue({ hits: { hits: [] } }),
+});
+
+const candidates = (
+ entity: FtsSearchBackendRequest['entity'],
+ filters: FtsSearchBackendRequest['filters'],
+): FtsSearchBackendRequest => ({
+ entity,
+ filters,
+ mode: 'candidates',
+ pagination: { limit: 10 },
+ query: { text: 'kestrel' },
+ scope: { userId },
+});
+
+const sentFilters = (client: ElasticsearchFtsSearchClient) =>
+ vi.mocked(client.search).mock.calls[0][0].body.query.bool.filter;
+
+describe('ElasticsearchFtsSearchBackend candidate filters', () => {
+ it.each([
+ ['messages', 'createdAt', 'created_at'],
+ ['topics', 'updatedAt', 'updated_at'],
+ ] as const)(
+ 'narrows %s candidates by %s inside the query',
+ async (entity, field, documentField) => {
+ const client = createClient();
+ const backend = new ElasticsearchFtsSearchBackend(db, { client, indexNamespace: 'test' });
+
+ await backend.search(candidates(entity, { timeRange: { end, field, start } }));
+
+ expect(sentFilters(client)).toContainEqual({
+ range: { [documentField]: { gte: start.toISOString(), lte: end.toISOString() } },
+ });
+ },
+ );
+
+ it('narrows page candidates and keeps an open edge open', async () => {
+ const client = createClient();
+ const backend = new ElasticsearchFtsSearchBackend(db, { client, indexNamespace: 'test' });
+
+ await backend.search(
+ candidates('documents', { documentKind: 'page', timeRange: { field: 'updatedAt', start } }),
+ );
+
+ expect(sentFilters(client)).toContainEqual({
+ range: { updated_at: { gte: start.toISOString() } },
+ });
+ });
+
+ it('ignores the window for entities without one', async () => {
+ const client = createClient();
+ const backend = new ElasticsearchFtsSearchBackend(db, { client, indexNamespace: 'test' });
+
+ await backend.search(candidates('agents', { timeRange: { end, field: 'createdAt', start } }));
+
+ expect(sentFilters(client).some((clause: object) => 'range' in clause)).toBe(false);
+ });
+
+ it('narrows message candidates to the requested roles and topic', async () => {
+ const client = createClient();
+ const backend = new ElasticsearchFtsSearchBackend(db, { client, indexNamespace: 'test' });
+
+ await backend.search(
+ candidates('messages', { messageScope: { roles: ['user', 'assistant'], topicId: 'tpc_x' } }),
+ );
+
+ expect(sentFilters(client)).toEqual(
+ expect.arrayContaining([
+ { terms: { role: ['user', 'assistant'] } },
+ { term: { topic_id: 'tpc_x' } },
+ ]),
+ );
+ });
+});
diff --git a/packages/database/src/repositories/ftsSearch/__tests__/timeRangeBehavior.ts b/packages/database/src/repositories/ftsSearch/__tests__/timeRangeBehavior.ts
new file mode 100644
index 00000000000..034a1250529
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearch/__tests__/timeRangeBehavior.ts
@@ -0,0 +1,176 @@
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import { documents } from '../../../schemas';
+import { messages } from '../../../schemas/message';
+import { topics } from '../../../schemas/topic';
+import { users } from '../../../schemas/user';
+import type { LobeChatDatabase } from '../../../type';
+import type { FtsSearchRepo } from '../index';
+import type { FtsSearchTimeRange } from '../types';
+
+const userId = 'time-range-search-user';
+
+const day = (offset: number) => new Date(Date.UTC(2026, 9, 1 + offset));
+
+/** Oct 12 – Oct 18, 2026. */
+const window = (field: FtsSearchTimeRange['field']): FtsSearchTimeRange => ({
+ end: day(17),
+ field,
+ start: day(11),
+});
+
+export interface FtsSearchTimeRangeBehaviorOptions {
+ createRepo: (db: LobeChatDatabase, userId: string) => FtsSearchRepo;
+ db: LobeChatDatabase;
+ /** Whether the provider answers candidate-only requests. */
+ supportsCandidates: boolean;
+}
+
+/**
+ * Provider-neutral time-window behaviour. Every case seeds a stronger match
+ * outside the window and asks for a one-row pool, so a provider that filters
+ * after cutting the ranked pool returns nothing instead of the in-window row.
+ */
+export const describeFtsSearchTimeRangeBehavior = ({
+ createRepo,
+ db,
+ supportsCandidates,
+}: FtsSearchTimeRangeBehaviorOptions) => {
+ describe('search - time range', () => {
+ let repo: FtsSearchRepo;
+
+ beforeEach(async () => {
+ await db.delete(users);
+ await db.insert(users).values({ id: userId });
+ repo = createRepo(db, userId);
+ });
+
+ it('keeps topics updated inside the window ahead of stronger stale matches', async () => {
+ await db.insert(topics).values([
+ {
+ content: 'kestrel kestrel kestrel',
+ createdAt: day(0),
+ id: 'tr-topic-stale',
+ title: 'Kestrel',
+ updatedAt: day(1),
+ userId,
+ },
+ {
+ createdAt: day(2),
+ id: 'tr-topic-active',
+ title: 'Weekly notes on the kestrel rollout',
+ updatedAt: day(14),
+ userId,
+ },
+ {
+ createdAt: day(19),
+ id: 'tr-topic-future',
+ title: 'Kestrel follow-up',
+ updatedAt: day(20),
+ userId,
+ },
+ ]);
+
+ const results = await repo.search({
+ limitPerType: 1,
+ query: 'kestrel',
+ timeRange: window('updatedAt'),
+ type: 'topic',
+ });
+
+ expect(results.map(({ id }) => id)).toEqual(['tr-topic-active']);
+ });
+
+ it('keeps pages updated inside the window', async () => {
+ const page = (id: string, title: string, updatedAt: Date) => ({
+ content: title,
+ createdAt: day(0),
+ fileType: 'custom/document',
+ filename: `${id}.md`,
+ id,
+ source: `internal://${id}`,
+ sourceType: 'file' as const,
+ title,
+ totalCharCount: title.length,
+ totalLineCount: 1,
+ updatedAt,
+ userId,
+ });
+ await db
+ .insert(documents)
+ .values([
+ page('tr-page-stale', 'Kestrel', day(1)),
+ page('tr-page-active', 'Notes about the kestrel mode', day(15)),
+ ]);
+
+ const results = await repo.search({
+ limitPerType: 1,
+ query: 'kestrel',
+ timeRange: window('updatedAt'),
+ type: 'page',
+ });
+
+ expect(results.map(({ id }) => id)).toEqual(['tr-page-active']);
+ });
+
+ it('keeps messages created inside the window', async () => {
+ await db.insert(messages).values([
+ // Newer and stronger, but after the window: recency ordering alone would pick it.
+ {
+ content: 'kestrel kestrel',
+ createdAt: day(20),
+ id: 'tr-msg-later',
+ role: 'user',
+ userId,
+ },
+ {
+ content: 'we turned on the kestrel mode',
+ createdAt: day(13),
+ id: 'tr-msg-active',
+ role: 'user',
+ userId,
+ },
+ ]);
+
+ const results = await repo.search({
+ limitPerType: 1,
+ query: 'kestrel',
+ timeRange: window('createdAt'),
+ type: 'message',
+ });
+
+ expect(results.map(({ id }) => id)).toEqual(['tr-msg-active']);
+ });
+
+ it.runIf(supportsCandidates)(
+ 'narrows bounded message candidates before the pool is cut',
+ async () => {
+ await db.insert(messages).values([
+ {
+ content: 'kestrel kestrel',
+ createdAt: day(1),
+ id: 'tr-cand-stale',
+ role: 'user',
+ userId,
+ },
+ {
+ content: 'kestrel mode notes',
+ createdAt: day(13),
+ id: 'tr-cand-active',
+ role: 'user',
+ userId,
+ },
+ ]);
+
+ const response = await repo.ftsSearchCandidates({
+ entity: 'messages',
+ filters: { timeRange: window('createdAt') },
+ pagination: { limit: 1 },
+ query: { fields: ['content'], text: 'kestrel' },
+ });
+
+ expect(response.candidates.map(({ id }) => id)).toEqual(['tr-cand-active']);
+ },
+ );
+ });
+};
diff --git a/packages/database/src/repositories/ftsSearch/elasticsearch/candidates.ts b/packages/database/src/repositories/ftsSearch/elasticsearch/candidates.ts
index ba3f3a5710f..0b3e30710a4 100644
--- a/packages/database/src/repositories/ftsSearch/elasticsearch/candidates.ts
+++ b/packages/database/src/repositories/ftsSearch/elasticsearch/candidates.ts
@@ -284,6 +284,9 @@ export const searchElasticsearchCandidates = async (
}
if (entity === 'messages') {
mustNot.push({ term: { role: 'tool' } });
+ const { roles, topicId } = request.filters.messageScope ?? {};
+ if (roles?.length) filter.push({ terms: { role: roles } });
+ if (topicId) filter.push({ term: { topic_id: topicId } });
}
if (request.filters.excludeVirtual && entity === 'agents') {
mustNot.push({ term: { virtual: true } });
@@ -321,6 +324,20 @@ export const searchElasticsearchCandidates = async (
}
}
+ if (
+ request.filters.timeRange &&
+ (entity === 'topics' || entity === 'messages' || entity === 'documents')
+ ) {
+ const { end, field, start } = request.filters.timeRange;
+ const dateRange = {
+ ...(start ? { gte: start.toISOString() } : {}),
+ ...(end ? { lte: end.toISOString() } : {}),
+ };
+ if (Object.keys(dateRange).length > 0) {
+ filter.push({ range: { [field === 'createdAt' ? 'created_at' : 'updated_at']: dateRange } });
+ }
+ }
+
appendMemoryFilters(entity, request.filters, filter);
appendTopicScopeFilters(entity, request.filters, filter);
diff --git a/packages/database/src/repositories/ftsSearch/index.ts b/packages/database/src/repositories/ftsSearch/index.ts
index a858c28d5b1..f0a69fc70e3 100644
--- a/packages/database/src/repositories/ftsSearch/index.ts
+++ b/packages/database/src/repositories/ftsSearch/index.ts
@@ -144,6 +144,7 @@ export class FtsSearchRepo {
const trimmedQuery = query.trim();
const limits = this.calculateLimits(limitPerType, type, agentId, contextType);
const excludeKnowledgeBaseIds = options.excludeKnowledgeBaseIds ?? [];
+ const { timeRange } = options;
const searches: Promise<FtsSearchBackendResponse>[] = [];
if ((!type || type === 'agent') && limits.agent > 0) {
@@ -154,12 +155,19 @@ export class FtsSearchRepo {
}
if ((!type || type === 'topic') && limits.topic > 0) {
searches.push(
- this.execute(this.createRequest('topics', trimmedQuery, limits.topic, { agentId })),
+ this.execute(
+ this.createRequest('topics', trimmedQuery, limits.topic, { agentId, timeRange }),
+ ),
);
}
if ((!type || type === 'message') && limits.message > 0) {
searches.push(
- this.execute(this.createRequest('messages', trimmedQuery, limits.message, { agentId })),
+ this.execute(
+ this.createRequest('messages', trimmedQuery, limits.message, {
+ agentId,
+ timeRange,
+ }),
+ ),
);
}
if ((!type || type === 'file') && limits.file > 0) {
@@ -185,6 +193,7 @@ export class FtsSearchRepo {
this.createRequest('documents', trimmedQuery, limits.page, {
documentKind: 'page',
excludeKnowledgeBaseIds,
+ timeRange,
}),
),
);
diff --git a/packages/database/src/repositories/ftsSearch/pgLike/candidates.ts b/packages/database/src/repositories/ftsSearch/pgLike/candidates.ts
index 6b6218a4603..ff8f4ac3de5 100644
--- a/packages/database/src/repositories/ftsSearch/pgLike/candidates.ts
+++ b/packages/database/src/repositories/ftsSearch/pgLike/candidates.ts
@@ -38,6 +38,7 @@ import { searchableMessage } from '../../../utils/searchableMessage';
import { buildWorkspaceWhere } from '../../../utils/workspace';
import type { PostgresFtsSearchContext } from '../postgres/context';
import type { PostgresFtsSearchField } from '../postgres/dialect';
+import { timeRangeWhere } from '../postgres/timeRange';
import type {
FtsSearchBackendCandidate,
FtsSearchBackendEntity,
@@ -323,6 +324,7 @@ const CANDIDATE_TARGETS: Record<FtsSearchBackendEntity, CandidateTarget | undefi
where: (scope, filters, db) => [
buildWorkspaceWhere(scope, documents),
...documentKindWhere(db, filters),
+ timeRangeWhere(documents, filters.timeRange),
],
},
files: {
@@ -496,6 +498,13 @@ const CANDIDATE_TARGETS: Record<FtsSearchBackendEntity, CandidateTarget | undefi
// rows crowd out eligible hits that hydration would have kept.
searchableMessage(),
...topicScopeWhere(messages, filters, true),
+ timeRangeWhere(messages, filters.timeRange),
+ filters.messageScope?.roles?.length
+ ? inArray(messages.role, filters.messageScope.roles)
+ : undefined,
+ filters.messageScope?.topicId
+ ? eq(messages.topicId, filters.messageScope.topicId)
+ : undefined,
],
},
personaDocuments: {
@@ -523,6 +532,7 @@ const CANDIDATE_TARGETS: Record<FtsSearchBackendEntity, CandidateTarget | undefi
where: (scope, filters) => [
buildWorkspaceWhere(scope, topics),
...topicScopeWhere(topics, filters, false),
+ timeRangeWhere(topics, filters.timeRange),
],
},
userMemories: {
@@ -599,14 +609,21 @@ export async function searchCandidates(
.orderBy(sql`${score} DESC`);
// An omitted limit is the unbounded contract: consumers filter and order the
// whole candidate set themselves, so no cap may hide matches from them.
- if (request.pagination.limit)
- query = query.limit(request.pagination.limit * CANDIDATE_MULTIPLIER);
+ // A bounded pool reads one row past its cutoff so `total` can tell callers
+ // whether the cutoff dropped anything, without a separate COUNT.
+ const cutoff = request.pagination.limit
+ ? request.pagination.limit * CANDIDATE_MULTIPLIER
+ : undefined;
+ if (cutoff) query = query.limit(cutoff + 1);
const rows = await query;
- const candidates: FtsSearchBackendCandidate[] = rows.map((row) => ({
+ const kept = cutoff ? rows.slice(0, cutoff) : rows;
+ const candidates: FtsSearchBackendCandidate[] = kept.map((row) => ({
id: String(row.id),
score: row.score,
}));
- return { candidates, items: [], total: candidates.length };
+ // Past the cutoff the true count is unknown; any value above the returned
+ // length marks the pool as cut, which is all callers rely on.
+ return { candidates, items: [], total: rows.length };
}
diff --git a/packages/database/src/repositories/ftsSearch/pgLike/index.test.ts b/packages/database/src/repositories/ftsSearch/pgLike/index.test.ts
index 654478eb62e..76e14beba0b 100644
--- a/packages/database/src/repositories/ftsSearch/pgLike/index.test.ts
+++ b/packages/database/src/repositories/ftsSearch/pgLike/index.test.ts
@@ -21,6 +21,7 @@ import {
otherUserId,
userId,
} from '../__tests__/productSearchBehavior';
+import { describeFtsSearchTimeRangeBehavior } from '../__tests__/timeRangeBehavior';
import { FtsSearchRepo } from '../index';
import { PgLikeFtsSearchBackend } from './index';
@@ -47,6 +48,7 @@ const createRepo = (
*/
describe('FtsSearchRepo (pg_like)', () => {
describeFtsSearchProductBehavior({ createRepo, db: serverDB });
+ describeFtsSearchTimeRangeBehavior({ createRepo, db: serverDB, supportsCandidates: true });
describe('LIKE wildcard escaping', () => {
beforeEach(async () => {
@@ -522,6 +524,77 @@ describe('FtsSearchRepo (pg_like)', () => {
expect(response.candidates.map((candidate) => candidate.id)).not.toContain(early.id);
});
+ it('reports a bounded pool as cut only when matches lie past its cutoff', async () => {
+ const insertHits = (count: number, offset = 0) =>
+ serverDB.insert(messages).values(
+ Array.from({ length: count }, (_, i) => ({
+ content: `cutoff kubernetes ${offset + i}`,
+ id: `cutoff-${offset + i}`,
+ role: 'user',
+ userId,
+ })),
+ );
+ const repo = createRepo(serverDB, userId);
+ // A limit of 1 over-fetches to a cutoff of 4.
+ const request = {
+ entity: 'messages' as const,
+ filters: {},
+ pagination: { limit: 1 },
+ query: { text: 'cutoff' },
+ };
+
+ await insertHits(4);
+ const exact = await repo.ftsSearchCandidates(request);
+ expect(exact.candidates).toHaveLength(4);
+ expect(exact.total).toBe(4);
+
+ await insertHits(1, 4);
+ const cut = await repo.ftsSearchCandidates(request);
+ expect(cut.candidates).toHaveLength(4);
+ expect(cut.total).toBeGreaterThan(cut.candidates.length);
+ });
+
+ it('applies the message scope before the candidate limit', async () => {
+ await serverDB.insert(topics).values([
+ { id: 'scope-topic-a', title: 'A', userId },
+ { id: 'scope-topic-b', title: 'B', userId },
+ ]);
+ await serverDB.insert(messages).values([
+ // Stronger matches outside the requested topic and role.
+ {
+ content: 'kubernetes',
+ id: 'scope-other-topic',
+ role: 'user',
+ topicId: 'scope-topic-b',
+ userId,
+ },
+ {
+ content: 'kubernetes',
+ id: 'scope-other-role',
+ role: 'assistant',
+ topicId: 'scope-topic-a',
+ userId,
+ },
+ {
+ content: 'notes on kubernetes upgrades',
+ id: 'scope-hit',
+ role: 'user',
+ topicId: 'scope-topic-a',
+ userId,
+ },
+ ]);
+
+ const repo = createRepo(serverDB, userId);
+ const response = await repo.ftsSearchCandidates({
+ entity: 'messages',
+ filters: { messageScope: { roles: ['user'], topicId: 'scope-topic-a' } },
+ pagination: { limit: 1 },
+ query: { text: 'kubernetes' },
+ });
+
+ expect(response.candidates.map((candidate) => candidate.id)).toEqual(['scope-hit']);
+ });
+
it('applies topic scope to topics and messages before the candidate limit', async () => {
const [agentA, agentB] = await serverDB
.insert(agents)
diff --git a/packages/database/src/repositories/ftsSearch/pgSearch/timeRange.test.ts b/packages/database/src/repositories/ftsSearch/pgSearch/timeRange.test.ts
new file mode 100644
index 00000000000..cc0c3982c37
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearch/pgSearch/timeRange.test.ts
@@ -0,0 +1,22 @@
+// @vitest-environment node
+import { describe } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import type { LobeChatDatabase } from '../../../type';
+import { describeFtsSearchTimeRangeBehavior } from '../__tests__/timeRangeBehavior';
+import { FtsSearchRepo } from '../index';
+import { PgSearchFtsSearchBackend } from './index';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+// BM25 retrieval requires the pg_search extension (ParadeDB), not available in PGlite.
+describe.skipIf(process.env.TEST_SERVER_DB !== '1')('FtsSearchRepo time range (pg_search)', () => {
+ describeFtsSearchTimeRangeBehavior({
+ createRepo: (db, userId) =>
+ new FtsSearchRepo(db, userId, undefined, undefined, {
+ backend: new PgSearchFtsSearchBackend(db, { userId }),
+ }),
+ db: serverDB,
+ supportsCandidates: false,
+ });
+});
diff --git a/packages/database/src/repositories/ftsSearch/postgres/backend.ts b/packages/database/src/repositories/ftsSearch/postgres/backend.ts
index 4f644a6f8af..f697d2c79df 100644
--- a/packages/database/src/repositories/ftsSearch/postgres/backend.ts
+++ b/packages/database/src/repositories/ftsSearch/postgres/backend.ts
@@ -46,8 +46,12 @@ export abstract class PostgresFtsSearchBackend implements FtsSearchBackend {
if (entity === 'agents') return searchAgents(this.context, query, limit);
if (entity === 'chatGroups') return searchChatGroups(this.context, query, limit);
- if (entity === 'topics') return searchTopics(this.context, query, limit, filters.agentId);
- if (entity === 'messages') return searchMessages(this.context, query, limit, filters.agentId);
+ if (entity === 'topics') {
+ return searchTopics(this.context, query, limit, filters.agentId, filters.timeRange);
+ }
+ if (entity === 'messages') {
+ return searchMessages(this.context, query, limit, filters.agentId, filters.timeRange);
+ }
if (entity === 'files') {
return searchFiles(this.context, query, limit, filters.excludeKnowledgeBaseIds);
}
@@ -61,7 +65,13 @@ export abstract class PostgresFtsSearchBackend implements FtsSearchBackend {
return searchFolders(this.context, query, limit, filters.excludeKnowledgeBaseIds);
}
if (filters.documentKind === 'page') {
- return searchPages(this.context, query, limit, filters.excludeKnowledgeBaseIds);
+ return searchPages(
+ this.context,
+ query,
+ limit,
+ filters.excludeKnowledgeBaseIds,
+ filters.timeRange,
+ );
}
if (filters.documentKind === 'knowledgeBaseDocument') {
return searchKnowledgeBaseDocuments(
diff --git a/packages/database/src/repositories/ftsSearch/postgres/command-menu.ts b/packages/database/src/repositories/ftsSearch/postgres/command-menu.ts
index 06e339f825b..126db8a6cd2 100644
--- a/packages/database/src/repositories/ftsSearch/postgres/command-menu.ts
+++ b/packages/database/src/repositories/ftsSearch/postgres/command-menu.ts
@@ -26,12 +26,14 @@ import type {
FtsSearchFileResult,
FtsSearchKnowledgeBaseResult,
FtsSearchMessageResult,
+ FtsSearchTimeRange,
FtsSearchTopicResult,
} from '../types';
import type { PostgresFtsSearchContext } from './context';
import { AGENT_SCOPE_CANDIDATE_POOL } from './context';
import type { PostgresFtsSearchField } from './dialect';
import { buildResponse, buildSelectedResponse, mapScoresToRelevance, truncate } from './results';
+import { timeRangeWhere } from './timeRange';
/** Topics and messages are displayed by recency after a larger scored candidate pool is fetched. */
const RECENCY_CANDIDATE_MULTIPLIER = 4;
@@ -145,6 +147,7 @@ export async function searchTopics(
query: string,
limit: number,
agentId?: string,
+ timeRange?: FtsSearchTimeRange,
): Promise<FtsSearchBackendResponse<FtsSearchTopicResult>> {
const candidateLimit = limit * RECENCY_CANDIDATE_MULTIPLIER;
const { db, dialect } = context;
@@ -174,6 +177,7 @@ export async function searchTopics(
// the creator's command-menu search.
notShareVisitorTopic(),
agentId && !context.liftsAgentFilter ? eq(topics.agentId, agentId) : undefined,
+ timeRangeWhere(topics, timeRange),
dialect.match(TOPIC_FIELDS, preparedQuery),
),
)
@@ -262,6 +266,7 @@ export async function searchMessages(
query: string,
limit: number,
agentId?: string,
+ timeRange?: FtsSearchTimeRange,
): Promise<FtsSearchBackendResponse<FtsSearchMessageResult>> {
const candidateLimit = limit * RECENCY_CANDIDATE_MULTIPLIER;
const { db, dialect } = context;
@@ -292,6 +297,7 @@ export async function searchMessages(
// userId and are only identifiable through their parent topic.
notShareVisitorMessage(),
agentId && !context.liftsAgentFilter ? eq(messages.agentId, agentId) : undefined,
+ timeRangeWhere(messages, timeRange),
dialect.match(MESSAGE_FIELDS, preparedQuery),
),
)
diff --git a/packages/database/src/repositories/ftsSearch/postgres/documents.ts b/packages/database/src/repositories/ftsSearch/postgres/documents.ts
index b917d8824e2..3ca09545dcf 100644
--- a/packages/database/src/repositories/ftsSearch/postgres/documents.ts
+++ b/packages/database/src/repositories/ftsSearch/postgres/documents.ts
@@ -10,10 +10,12 @@ import type {
FtsSearchFolderResult,
FtsSearchKnowledgeBaseDocumentHit,
FtsSearchPageResult,
+ FtsSearchTimeRange,
} from '../types';
import type { PostgresFtsSearchContext } from './context';
import type { PostgresFtsSearchField } from './dialect';
import { buildResponse, truncate } from './results';
+import { timeRangeWhere } from './timeRange';
const FOLDER_FIELDS: PostgresFtsSearchField[] = [
{ column: documents.title, weight: 4 },
@@ -116,6 +118,7 @@ export async function searchPages(
query: string,
limit: number,
excludeKbIds?: string[],
+ timeRange?: FtsSearchTimeRange,
): Promise<FtsSearchBackendResponse<FtsSearchPageResult>> {
const { db, dialect } = context;
const preparedQuery = dialect.prepare(query);
@@ -160,6 +163,7 @@ export async function searchPages(
context.liftsExclusionFilter
? undefined
: excludeKb(documents.knowledgeBaseId, documents.fileId),
+ timeRangeWhere(documents, timeRange),
dialect.match(PAGE_FIELDS, preparedQuery),
),
)
diff --git a/packages/database/src/repositories/ftsSearch/postgres/timeRange.ts b/packages/database/src/repositories/ftsSearch/postgres/timeRange.ts
new file mode 100644
index 00000000000..c72e5a6e4eb
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearch/postgres/timeRange.ts
@@ -0,0 +1,23 @@
+import type { SQL } from 'drizzle-orm';
+import { and, gte, lte } from 'drizzle-orm';
+import type { AnyPgColumn } from 'drizzle-orm/pg-core';
+
+import type { FtsSearchTimeRange } from '../types';
+
+/**
+ * Time-window predicate for conversation and page retrieval. Pools are cut by
+ * score before hydration, so the window must narrow the scan itself; applying
+ * it afterwards lets out-of-window hits exhaust the pool.
+ */
+export const timeRangeWhere = (
+ table: { createdAt: AnyPgColumn; updatedAt: AnyPgColumn },
+ range?: FtsSearchTimeRange,
+): SQL | undefined => {
+ if (!range || (!range.start && !range.end)) return;
+ const column = range.field === 'createdAt' ? table.createdAt : table.updatedAt;
+
+ return and(
+ range.start ? gte(column, range.start) : undefined,
+ range.end ? lte(column, range.end) : undefined,
+ );
+};
diff --git a/packages/database/src/repositories/ftsSearch/types.ts b/packages/database/src/repositories/ftsSearch/types.ts
index 60567f0f740..21dfbd46708 100644
--- a/packages/database/src/repositories/ftsSearch/types.ts
+++ b/packages/database/src/repositories/ftsSearch/types.ts
@@ -12,7 +12,8 @@ export type FtsSearchResultType =
| 'plugin'
| 'communityAgent'
| 'knowledgeBase'
- | 'task';
+ | 'task'
+ | 'goal';
export interface FtsSearchBaseResult {
createdAt: Date;
@@ -128,6 +129,16 @@ export interface FtsSearchTaskResult extends FtsSearchBaseResult {
type: 'task';
}
+/** Goal lookup result. Goals are not indexed; `GoalSearchRepo` queries them directly. */
+export interface FtsSearchGoalResult extends FtsSearchBaseResult {
+ /** Supervising agent, when one is assigned. */
+ agentId: string | null;
+ completedAt: Date | null;
+ projectId: string | null;
+ status: string;
+ type: 'goal';
+}
+
/**
* Hydrated BM25 hit for KB-scoped documents. `fileId` identifies a parsed-file
* source; inline pages use `documentId` directly.
@@ -168,7 +179,8 @@ export type FtsSearchResult =
| FtsSearchMCPResult
| FtsSearchPluginResult
| FtsSearchAssistantResult
- | FtsSearchTaskResult;
+ | FtsSearchTaskResult
+ | FtsSearchGoalResult;
export interface FtsSearchOptions {
agentId?: string;
@@ -178,6 +190,8 @@ export interface FtsSearchOptions {
limitPerType?: number;
offset?: number;
query: string;
+ /** Narrows topic, message and page results; other types ignore it. */
+ timeRange?: FtsSearchTimeRange;
type?: FtsSearchResultType;
}
@@ -208,6 +222,13 @@ export interface FtsSearchBackendScope {
workspaceId?: string;
}
+/** Time window on a row's creation or last update. */
+export interface FtsSearchTimeRange {
+ end?: Date;
+ field: 'createdAt' | 'updatedAt';
+ start?: Date;
+}
+
export interface FtsSearchBackendFilters {
agentId?: string;
documentKind?: 'folder' | 'knowledgeBaseDocument' | 'page';
@@ -226,6 +247,20 @@ export interface FtsSearchBackendFilters {
start?: Date;
};
memoryTypes?: string[];
+ /**
+ * Message-only candidate narrowing (roles, parent topic). Bounded pools are
+ * cut by score, so filters a caller re-applies after hydration must also
+ * narrow retrieval or stronger out-of-scope rows exhaust the pool.
+ */
+ messageScope?: {
+ roles?: string[];
+ topicId?: string;
+ };
+ /**
+ * Window for topics, messages and documents; other entities ignore it. Every
+ * provider applies it during retrieval so bounded pools stay in the window.
+ */
+ timeRange?: FtsSearchTimeRange;
topicScope?: {
agentId?: string | null;
containerId?: string | null;
@@ -320,6 +355,10 @@ export type FtsSearchCandidateRequest = Omit<FtsSearchBackendRequest, 'mode' | '
export interface FtsSearchCandidateResult {
candidates: FtsSearchBackendCandidate[];
+ /**
+ * Provider match count. It may be a lower bound once a bounded pool hits its
+ * cutoff, but `total > candidates.length` always means matches were dropped.
+ */
total: number;
}
diff --git a/packages/database/src/repositories/goalSearch/index.test.ts b/packages/database/src/repositories/goalSearch/index.test.ts
new file mode 100644
index 00000000000..886a7129072
--- /dev/null
+++ b/packages/database/src/repositories/goalSearch/index.test.ts
@@ -0,0 +1,140 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { goals, users, workspaces } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { GoalSearchRepo } from './index';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'goal-search-user';
+const otherUserId = 'goal-search-other-user';
+const workspaceId = 'ws_goal_search';
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+});
+
+afterEach(async () => {
+ await serverDB.delete(users);
+});
+
+const insertGoal = (values: Partial<typeof goals.$inferInsert> & { id: string; title: string }) =>
+ serverDB.insert(goals).values({ userId, ...values });
+
+describe('GoalSearchRepo', () => {
+ it('finds goals by title or requirement, ranking title matches first', async () => {
+ await insertGoal({
+ id: 'goal_req',
+ requirement: 'Prove the STAMP loop on a second domain',
+ title: 'Second domain rollout',
+ });
+ await insertGoal({ id: 'goal_title', status: 'paused', title: 'Replica migration (STAMP)' });
+ await insertGoal({ id: 'goal_miss', title: 'Unrelated' });
+
+ const results = await new GoalSearchRepo(serverDB, userId).search({ query: 'stamp' });
+
+ expect(results.map(({ id }) => id)).toEqual(['goal_title', 'goal_req']);
+ expect(results[0]).toMatchObject({
+ relevance: 3,
+ status: 'paused',
+ title: 'Replica migration (STAMP)',
+ type: 'goal',
+ });
+ expect(results[1].description).toBe('Prove the STAMP loop on a second domain');
+ });
+
+ it('keeps goals whose lifetime overlaps the window', async () => {
+ const at = (iso: string) => new Date(`${iso}T00:00:00.000Z`);
+ await insertGoal({
+ completedAt: at('2026-09-05'),
+ createdAt: at('2026-09-01'),
+ id: 'goal_finished_before',
+ status: 'achieved',
+ title: 'replica finished before',
+ updatedAt: at('2026-09-05'),
+ });
+ await insertGoal({
+ // Still open and not edited since September: active the whole window.
+ createdAt: at('2026-09-01'),
+ id: 'goal_open_untouched',
+ status: 'paused',
+ title: 'replica open untouched',
+ updatedAt: at('2026-09-05'),
+ });
+ await insertGoal({
+ // Edited after it finished: the edit must not extend its lifetime.
+ completedAt: at('2026-09-10'),
+ createdAt: at('2026-09-01'),
+ id: 'goal_finished_edited_later',
+ status: 'canceled',
+ title: 'replica finished edited later',
+ updatedAt: at('2026-10-15'),
+ });
+ await insertGoal({
+ completedAt: at('2026-10-14'),
+ createdAt: at('2026-10-01'),
+ id: 'goal_finished_inside',
+ status: 'achieved',
+ title: 'replica finished inside',
+ updatedAt: at('2026-10-14'),
+ });
+ await insertGoal({
+ // Terminal row that predates `completedAt`: falls back to its last update.
+ createdAt: at('2026-08-01'),
+ id: 'goal_legacy_terminal',
+ status: 'failed',
+ title: 'replica legacy terminal',
+ updatedAt: at('2026-08-05'),
+ });
+ await insertGoal({
+ createdAt: at('2026-10-20'),
+ id: 'goal_future',
+ title: 'replica future',
+ updatedAt: at('2026-10-21'),
+ });
+
+ const results = await new GoalSearchRepo(serverDB, userId).search({
+ endDate: new Date('2026-10-18T23:59:59.000Z'),
+ limit: 10,
+ query: 'replica',
+ startDate: at('2026-10-12'),
+ });
+
+ expect(results.map(({ id }) => id).sort()).toEqual([
+ 'goal_finished_inside',
+ 'goal_open_untouched',
+ ]);
+ });
+
+ it('never returns other users, other scopes or trashed goals', async () => {
+ await serverDB.insert(workspaces).values({
+ id: workspaceId,
+ name: 'Workspace',
+ primaryOwnerId: userId,
+ slug: 'goal-search-ws',
+ });
+ await insertGoal({ id: 'goal_own', title: 'harvest farm' });
+ await insertGoal({ id: 'goal_other', title: 'harvest farm', userId: otherUserId });
+ await insertGoal({ id: 'goal_ws', title: 'harvest farm', workspaceId });
+ await insertGoal({ id: 'goal_trashed', isDeleted: true, title: 'harvest farm' });
+
+ const personal = await new GoalSearchRepo(serverDB, userId).search({ query: 'harvest' });
+ expect(personal.map(({ id }) => id)).toEqual(['goal_own']);
+
+ const workspace = await new GoalSearchRepo(serverDB, userId, workspaceId).search({
+ query: 'harvest',
+ });
+ expect(workspace.map(({ id }) => id)).toEqual(['goal_ws']);
+ });
+
+ it('returns nothing for a blank query or non-positive limit', async () => {
+ await insertGoal({ id: 'goal_any', title: 'anything' });
+ const repo = new GoalSearchRepo(serverDB, userId);
+
+ expect(await repo.search({ query: ' ' })).toEqual([]);
+ expect(await repo.search({ limit: 0, query: 'anything' })).toEqual([]);
+ });
+});
diff --git a/packages/database/src/repositories/goalSearch/index.ts b/packages/database/src/repositories/goalSearch/index.ts
new file mode 100644
index 00000000000..c6e5acbc551
--- /dev/null
+++ b/packages/database/src/repositories/goalSearch/index.ts
@@ -0,0 +1,99 @@
+import type { GoalStatus } from '@lobechat/const/goal';
+import { and, asc, desc, inArray, lte, or, sql } from 'drizzle-orm';
+
+import { goals } from '../../schemas/goal';
+import type { LobeChatDatabase } from '../../type';
+import { escapeLike, ilikeContains } from '../../utils/like';
+import { buildWorkspaceWhere } from '../../utils/workspace';
+import type { FtsSearchGoalResult } from '../ftsSearch/types';
+
+/** Lifecycle states after which a goal is no longer active. */
+const TERMINAL_STATUSES: GoalStatus[] = ['achieved', 'failed', 'canceled'];
+
+export interface GoalSearchOptions {
+ /** Only goals created at or before this instant. */
+ endDate?: Date;
+ limit?: number;
+ query: string;
+ /** Only goals still open, or finished at or after this instant. */
+ startDate?: Date;
+}
+
+/**
+ * When a goal stopped being active. `GoalModel` stamps `completedAt` on every
+ * terminal transition, while `updatedAt` only records the last edit — an open
+ * goal untouched since before the window was still active throughout it.
+ * Terminal rows that predate `completedAt` fall back to their last update.
+ */
+const lifetimeEnd = sql`COALESCE(${goals.completedAt}, CASE WHEN ${inArray(goals.status, TERMINAL_STATUSES)} THEN ${goals.updatedAt} END)`;
+
+/** Open goals have no end, so they overlap every window that starts after their creation. */
+const activeSince = (startDate: Date) =>
+ sql<boolean>`(${lifetimeEnd} IS NULL OR ${lifetimeEnd} >= ${startDate})`;
+
+/**
+ * Lookup for goals by title or requirement.
+ *
+ * Goals are not part of the full-text index, so this queries the `goals` table
+ * directly under the same workspace ownership as `GoalModel`, never returning
+ * trashed rows. The optional window keeps goals whose lifetime overlaps it.
+ */
+export class GoalSearchRepo {
+ constructor(
+ private readonly db: LobeChatDatabase,
+ private readonly userId: string,
+ private readonly workspaceId?: string,
+ ) {}
+
+ search = async ({
+ endDate,
+ limit = 5,
+ query,
+ startDate,
+ }: GoalSearchOptions): Promise<FtsSearchGoalResult[]> => {
+ const text = query.trim();
+ if (!text || limit <= 0) return [];
+
+ const titlePrefix = sql`${goals.title} ILIKE ${`${escapeLike(text)}%`} ESCAPE '\\'`;
+ const titleContains = ilikeContains(goals.title, text);
+
+ // Lower is better, matching FtsSearchBaseResult.relevance.
+ const relevance = sql<number>`CASE
+ WHEN lower(${goals.title}) = ${text.toLowerCase()} THEN 1
+ WHEN ${titlePrefix} THEN 2
+ WHEN ${titleContains} THEN 3
+ ELSE 4
+ END`;
+
+ const rows = await this.db
+ .select({
+ agentId: goals.agentId,
+ completedAt: goals.completedAt,
+ createdAt: goals.createdAt,
+ description: goals.requirement,
+ id: goals.id,
+ projectId: goals.projectId,
+ relevance,
+ status: goals.status,
+ title: goals.title,
+ updatedAt: goals.updatedAt,
+ })
+ .from(goals)
+ .where(
+ and(
+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, goals),
+ or(titleContains, ilikeContains(goals.requirement, text)),
+ startDate ? activeSince(startDate) : undefined,
+ endDate ? lte(goals.createdAt, endDate) : undefined,
+ ),
+ )
+ .orderBy(asc(relevance), desc(goals.updatedAt), desc(goals.id))
+ .limit(limit);
+
+ return rows.map(({ relevance, ...row }) => ({
+ ...row,
+ relevance: Number(relevance),
+ type: 'goal' as const,
+ }));
+ };
+}
diff --git a/packages/heterogeneous-agents/src/protocol/lobeHubCliGuide.ts b/packages/heterogeneous-agents/src/protocol/lobeHubCliGuide.ts
index 08afd0f5d76..34ab22d135f 100644
--- a/packages/heterogeneous-agents/src/protocol/lobeHubCliGuide.ts
+++ b/packages/heterogeneous-agents/src/protocol/lobeHubCliGuide.ts
@@ -50,7 +50,7 @@ export const lobeHubCliGuide = [
'- **You already know where you are.** `LOBEHUB_TOPIC_ID` (this conversation) and `LOBEHUB_OPERATION_ID` (this run) are in your environment, and `LOBEHUB_AGENT_ID` (you) and `LOBEHUB_WORKSPACE_ID` (the workspace this conversation belongs to, which scopes every `lh` call) are too whenever the run carries them. They are ordinary environment variables, so every sub-shell, script or tool you spawn inherits them. Pass them straight to commands rather than listing agents or topics to find yourself; if the one you need is empty, say so instead of guessing an id.',
'- **If `lh` is older than this app**, the shell may have found a stale global install first: `lh man` lacks a command you expect, or `lh` reports an unknown command. When `LOBEHUB_CLI` is set it is the path of the CLI this app ships — run that path instead of `lh` for the rest of the session.',
'- **Look commands up, do not guess them.** `lh man <command>` (e.g. `lh man doc create`) prints the manual for the CLI actually installed here, including exactly which flags that command takes. Many commands offer `--json` for structured output, but not all of them — the manual is what says so, and an invented flag just fails the call.',
- '- **What it reaches:** `lh kb` knowledge bases · `lh doc` documents · `lh file` files · `lh artifact` artifacts · `lh topic` / `lh message` past conversations · `lh agent` agents · `lh task` / `lh project` work · `lh widget` / `lh dashboard` monitoring widgets and dashboards · `lh search` local resources and the web · `lh gen` text/image/video/TTS/ASR generation · `lh memory` user memory · `lh notify` notifications to the user · `lh model` / `lh provider` / `lh plugin` / `lh skill` platform configuration · `lh bot` chat-platform bots.',
+ '- **What it reaches:** `lh kb` knowledge bases · `lh doc` documents · `lh file` files · `lh artifact` artifacts · `lh topic` / `lh message` past conversations · `lh agent` agents · `lh task` / `lh project` work · `lh widget` / `lh dashboard` monitoring widgets and dashboards · `lh search` local resources and the web · `lh recall` past messages, topics, goals and pages in a time window · `lh gen` text/image/video/TTS/ASR generation · `lh memory` user memory · `lh notify` notifications to the user · `lh model` / `lh provider` / `lh plugin` / `lh skill` platform configuration · `lh bot` chat-platform bots.',
"- **Widgets run code with the user's credentials.** Before `lh widget dry-run` of a draft that declares connector credentials (`manifest.env`) or network hosts (`manifest.network.allow`), show the user that version id, what the script does and which credentials and hosts it uses, and wait for their explicit approval of that exact version before passing `--version <id> --yes`. Never publish (`lh widget publish`) without the user's confirmation.",
'- **When to use it:** whenever the user asks for something that lives in LobeHub rather than in this working directory — saving a document, recalling an earlier conversation, generating an image, or changing your own agent configuration. Say what you did and where it landed.',
"- **If a command comes back with an authentication or permission error**, clear `LOBEHUB_JWT` and `LOBEHUB_JWT_FILE` and retry it once — some runs carry a narrow token scoped to this conversation, which shadows the machine's own login. An empty value is enough, so use whichever form your shell takes: `LOBEHUB_JWT= LOBEHUB_JWT_FILE= lh …` (sh/bash/zsh), `$env:LOBEHUB_JWT=''; $env:LOBEHUB_JWT_FILE=''; lh …` (PowerShell), `set LOBEHUB_JWT=` and `set LOBEHUB_JWT_FILE=` then `lh …` (cmd). If it still fails, tell the user what you were trying to do — do not work around it.",