🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(bot-retro): nightly retro for bot agents, lessons kept in an agent document (#22098)
Arvin Xu0b74730468a7
diff --git a/apps/server/src/router-hono/workflows/agent-signal/handlers/__tests__/scheduleNightlyReview.test.ts b/apps/server/src/router-hono/workflows/agent-signal/handlers/__tests__/scheduleNightlyReview.test.tsindex 8522570f448..15ee0d66d4b 100644--- a/apps/server/src/router-hono/workflows/agent-signal/handlers/__tests__/scheduleNightlyReview.test.ts+++ b/apps/server/src/router-hono/workflows/agent-signal/handlers/__tests__/scheduleNightlyReview.test.ts@@ -44,17 +44,25 @@ describe('scheduleNightlyReview', () => {expect(response.status).toBe(202);await expect(response.json()).resolves.toEqual({+ jobs: ['self-review', 'bot-retro'],+ messageId: 'nightly-message-1',+ messageIds: ['nightly-message-1', 'nightly-message-1'],scheduled: true,success: true,- messageId: 'nightly-message-1',});- expect(mocks.publishPaginateUsersEntry).toHaveBeenCalledWith({+ const defaults = {cursor: undefined,pageSize: 50,requestedAt: '2026-05-03T18:30:00.000Z',targetLimit: 20,whitelist: undefined,+ };+ expect(mocks.publishPaginateUsersEntry).toHaveBeenCalledTimes(2);+ expect(mocks.publishPaginateUsersEntry).toHaveBeenCalledWith({+ ...defaults,+ job: 'self-review',});+ expect(mocks.publishPaginateUsersEntry).toHaveBeenCalledWith({ ...defaults, job: 'bot-retro' });});it('forwards valid scheduler options from the request body', async () => {@@ -65,6 +73,7 @@ describe('scheduleNightlyReview', () => {const response = await createApp().request('/cron-hourly-nightly-self-review', {body: JSON.stringify({cursor: { createdAt: '2026-05-04T00:00:00.000Z', id: 'user-1' },+ jobs: ['bot-retro', 'unknown'],limit: 100,targetLimit: 5,whitelist: ['user-1', ''],@@ -75,12 +84,16 @@ describe('scheduleNightlyReview', () => {expect(response.status).toBe(202);await expect(response.json()).resolves.toEqual({+ jobs: ['bot-retro'],+ messageId: 'nightly-message-1',+ messageIds: ['nightly-message-1'],scheduled: true,success: true,- messageId: 'nightly-message-1',});+ expect(mocks.publishPaginateUsersEntry).toHaveBeenCalledTimes(1);expect(mocks.publishPaginateUsersEntry).toHaveBeenCalledWith({cursor: { createdAt: '2026-05-04T00:00:00.000Z', id: 'user-1' },+ job: 'bot-retro',pageSize: 100,requestedAt: '2026-05-03T18:30:00.000Z',targetLimit: 5,diff --git a/apps/server/src/router-hono/workflows/agent-signal/handlers/scheduleNightlyReview.ts b/apps/server/src/router-hono/workflows/agent-signal/handlers/scheduleNightlyReview.tsindex b1981e84211..662fa03b8f3 100644--- a/apps/server/src/router-hono/workflows/agent-signal/handlers/scheduleNightlyReview.ts+++ b/apps/server/src/router-hono/workflows/agent-signal/handlers/scheduleNightlyReview.ts@@ -3,6 +3,7 @@ import { tracer } from '@lobechat/observability-otel/modules/agent-signal';import { isRecord } from '@lobechat/utils';import type { Context } from 'hono';+import type { NightlyJob } from '@/server/services/agentSignal/services';import {AgentSignalNightlyReviewWorkflow,type NightlyReviewWorkflowCursor,@@ -13,6 +14,7 @@ const HARD_MAX_USER_PAGE_SIZE = 200;const DEFAULT_TARGET_LIMIT = 20;const HARD_MAX_TARGET_LIMIT = 50;const CRON_SPAN_NAME = 'agent_signal.cron.hourly_nightly_self_review';+const NIGHTLY_JOBS: NightlyJob[] = ['self-review', 'bot-retro'];/*** Request body accepted by the Agent Signal nightly review scheduler endpoint.@@ -25,6 +27,12 @@ export interface ScheduleNightlyReviewPayload {/** Stable user id from the last user row in the previous page. */id: string;};+ /**+ * Nightly jobs to start. Each runs in its own local night window.+ *+ * @default ['self-review', 'bot-retro']+ */+ jobs?: NightlyJob[];/*** Maximum eligible users read by each pagination workflow.*@@ -57,6 +65,14 @@ const readWhitelist = (value: unknown) => {return whitelist.length > 0 ? whitelist : undefined;};+const readJobs = (value: unknown): NightlyJob[] => {+ if (!Array.isArray(value)) return NIGHTLY_JOBS;++ const jobs = NIGHTLY_JOBS.filter((job) => value.includes(job));++ return jobs.length > 0 ? jobs : NIGHTLY_JOBS;+};+const readCursor = (value: unknown): NightlyReviewWorkflowCursor | undefined => {if (!isRecord(value)) return;@@ -127,17 +143,27 @@ export async function scheduleNightlyReview(c: Context) {: {}),});+ const jobs = readJobs(payload.jobs);const startedAt = Date.now();- const result = await AgentSignalNightlyReviewWorkflow.publishPaginateUsersEntry(options);+ const results = await Promise.all(+ jobs.map((job) =>+ AgentSignalNightlyReviewWorkflow.publishPaginateUsersEntry({ ...options, job }),+ ),+ );+ const messageIds = results.map((result) => result.messageId);span.setAttributes({+ 'agent.signal.cron.jobs': jobs.join(','),'agent.signal.cron.publish_duration_ms': Date.now() - startedAt,'agent.signal.cron.success': true,- 'agent.signal.cron.message_id': result.messageId,+ 'agent.signal.cron.message_id': messageIds.join(','),});span.setStatus({ code: SpanStatusCode.OK });- return c.json({ messageId: result.messageId, scheduled: true, success: true }, 202);+ return c.json(+ { messageId: messageIds[0], messageIds, jobs, scheduled: true, success: true },+ 202,+ );} catch (error) {// This log is the only trace a failed tick leaves behind: a stalled publish used to be// killed by Cloudflare at 100s, which produced a 524 with no body and nothing on the server.diff --git a/apps/server/src/router-hono/workflows/agent-signal/workflows/__tests__/nightlyReview.test.ts b/apps/server/src/router-hono/workflows/agent-signal/workflows/__tests__/nightlyReview.test.tsindex bed8dc2ca79..6ad9793ff98 100644--- a/apps/server/src/router-hono/workflows/agent-signal/workflows/__tests__/nightlyReview.test.ts+++ b/apps/server/src/router-hono/workflows/agent-signal/workflows/__tests__/nightlyReview.test.ts@@ -12,6 +12,9 @@ import type {import type { NightlyReviewWorkflowDependencies } from '../nightlyReview';import { executeNightlyReviewUser, paginateNightlyReviewUsers } from '../nightlyReview';+// The real retro service pulls in the document editor stack; the workflow only orchestrates it.+vi.mock('@/server/services/agentSignal/services/botRetro', () => ({ BotRetroService: class {} }));+const createContext = <TPayload>(payload: TPayload): WorkflowContext<TPayload> => {const run = vi.fn(async (_stepName: string, handler: () => Promise<unknown>) => {const result = await handler();@@ -93,6 +96,7 @@ describe('nightly review layered workflows', () => {createdAt: users.at(-1)!.createdAt.toISOString(),id: users.at(-1)!.id,},+ job: 'self-review',pageSize: 50,requestedAt: '2026-05-03T18:30:00.000Z',targetLimit: 20,@@ -100,6 +104,47 @@ describe('nightly review layered workflows', () => {});});+ it('carries the bot-retro job through the page scan and every child trigger', async () => {+ const service = createService();+ vi.mocked(service.listEligibleUsersPage).mockResolvedValue({+ users: [{ createdAt: new Date('2026-01-01T00:00:00.000Z'), id: 'user-1' }],+ });+ const { dependencies, triggerExecuteUser, triggerPaginateUsers } = createDependencies(service);++ await paginateNightlyReviewUsers(+ createContext<PaginateNightlyReviewUsersPayload>({+ job: 'bot-retro',+ pageSize: 50,+ requestedAt: '2026-05-03T20:30:00.000Z',+ targetLimit: 20,+ }),+ dependencies,+ );++ expect(service.listEligibleUsersPage).toHaveBeenCalledWith(+ expect.objectContaining({ job: 'bot-retro' }),+ );+ expect(triggerPaginateUsers).toHaveBeenCalledWith(+ expect.objectContaining({+ job: 'bot-retro',+ users: [expect.objectContaining({ id: 'user-1' })],+ }),+ );++ await paginateNightlyReviewUsers(+ createContext<PaginateNightlyReviewUsersPayload>({+ job: 'bot-retro',+ pageSize: 50,+ requestedAt: '2026-05-03T20:30:00.000Z',+ targetLimit: 20,+ users: [{ createdAt: '2026-01-01T00:00:00.000Z', id: 'user-1' }],+ }),+ dependencies,+ );++ expect(triggerExecuteUser).toHaveBeenCalledWith(expect.objectContaining({ job: 'bot-retro' }));+ });+it('turns one fan-out chunk into one execution workflow per user without querying a page', async () => {/*** @example@@ -167,4 +212,62 @@ describe('nightly review layered workflows', () => {},});});++ it("runs one retro step per bot agent over the user's previous local day", async () => {+ const service = createService();+ const listTargets = vi.fn().mockResolvedValue(['agent-a', 'agent-b']);+ const runForAgent = vi.fn().mockResolvedValue({ status: 'written' });+ const { dependencies } = createDependencies(service);+ // 04:30 in Shanghai on 2026-05-04: inside the bot-retro window, reviewing 2026-05-03.+ const context = createContext<ExecuteNightlyReviewUserPayload>({+ job: 'bot-retro',+ requestedAt: '2026-05-03T20:30:00.000Z',+ targetLimit: 5,+ user: { createdAt: '2026-01-01T00:00:00.000Z', id: 'user-1', timezone: 'Asia/Shanghai' },+ });++ await expect(+ executeNightlyReviewUser(context, {+ ...dependencies,+ createBotRetroService: () => ({ listTargets, runForAgent }),+ }),+ ).resolves.toEqual({ enqueued: 2, skipped: 0, success: true, userId: 'user-1' });++ const windowStart = new Date('2026-05-02T16:00:00.000Z');+ const windowEnd = new Date('2026-05-03T16:00:00.000Z');+ expect(listTargets).toHaveBeenCalledWith({ limit: 5, windowEnd, windowStart });+ expect(runForAgent).toHaveBeenCalledTimes(2);+ expect(runForAgent).toHaveBeenCalledWith({+ agentId: 'agent-b',+ localDate: '2026-05-03',+ windowEnd,+ windowStart,+ });+ expect(vi.mocked(context.run).mock.calls.map(([name]) => name)).toEqual([+ 'agent-signal:nightly-bot-retro:list-agents:user-1',+ 'agent-signal:nightly-bot-retro:run:agent-a',+ 'agent-signal:nightly-bot-retro:run:agent-b',+ ]);+ expect(service.dispatchNightlyReviewForUser).not.toHaveBeenCalled();+ });++ it('skips the bot retro outside the 04:00-06:00 local window', async () => {+ const listTargets = vi.fn();+ const { dependencies } = createDependencies(createService());+ // 02:30 in Shanghai is the self-review window, not the bot retro one.+ const context = createContext<ExecuteNightlyReviewUserPayload>({+ job: 'bot-retro',+ requestedAt: '2026-05-03T18:30:00.000Z',+ targetLimit: 5,+ user: { createdAt: '2026-01-01T00:00:00.000Z', id: 'user-1', timezone: 'Asia/Shanghai' },+ });++ await expect(+ executeNightlyReviewUser(context, {+ ...dependencies,+ createBotRetroService: () => ({ listTargets, runForAgent: vi.fn() }),+ }),+ ).resolves.toEqual({ enqueued: 0, skipped: 1, success: true, userId: 'user-1' });+ expect(listTargets).not.toHaveBeenCalled();+ });});diff --git a/apps/server/src/router-hono/workflows/agent-signal/workflows/nightlyReview.ts b/apps/server/src/router-hono/workflows/agent-signal/workflows/nightlyReview.tsindex bc9416916c0..49540eeab56 100644--- a/apps/server/src/router-hono/workflows/agent-signal/workflows/nightlyReview.ts+++ b/apps/server/src/router-hono/workflows/agent-signal/workflows/nightlyReview.ts@@ -2,7 +2,11 @@ import type { WorkflowContext } from '@upstash/workflow';import { chunk } from 'es-toolkit/compat';import { getServerDB } from '@/database/server';-import { createServerNightlyReviewScheduleService } from '@/server/services/agentSignal/services';+import {+ createServerNightlyReviewScheduleService,+ getLocalNightWindow,+} from '@/server/services/agentSignal/services';+import { BotRetroService } from '@/server/services/agentSignal/services/botRetro';import {AgentSignalNightlyReviewWorkflow,type ExecuteNightlyReviewUserPayload,@@ -21,6 +25,14 @@ const USER_FAN_OUT_CHUNK_SIZE = 20;/** Dependencies that isolate nightly-review workflow orchestration from storage and child triggers. */export interface NightlyReviewWorkflowDependencies {+ /** Creates the per-user bot retro service used by the `bot-retro` job. */+ createBotRetroService?: (+ db: Awaited<ReturnType<typeof getServerDB>>,+ userId: string,+ ) => {+ listTargets: BotRetroService['listTargets'];+ runForAgent: BotRetroService['runForAgent'];+ };/** Creates the database-backed scheduler service used inside durable steps. */createScheduleService?: typeof createServerNightlyReviewScheduleService;/** Resolves the main database connection used by scheduler steps. */@@ -77,6 +89,10 @@ export const paginateNightlyReviewUsers = async (parseWorkflowDate(payload.requestedAt, 'Invalid nightly review requestedAt');+ const job = payload.job ?? 'self-review';+ // Self-review keeps its original step names so runs in flight across a deploy replay cleanly.+ const stepPrefix =+ job === 'self-review' ? 'agent-signal:nightly-review' : 'agent-signal:nightly-bot-retro';const pageSize = boundedInteger(payload.pageSize, DEFAULT_PAGE_SIZE, HARD_MAX_PAGE_SIZE);const targetLimit = boundedInteger(payload.targetLimit,@@ -91,8 +107,9 @@ export const paginateNightlyReviewUsers = async (if (payload.users && payload.users.length > 0) {await Promise.all(payload.users.map((user) =>- runStep(context, `agent-signal:nightly-review:execute:${user.id}`, () =>+ runStep(context, `${stepPrefix}:execute:${user.id}`, () =>triggerExecuteUser({+ job,requestedAt: payload.requestedAt,targetLimit,user,@@ -118,13 +135,14 @@ export const paginateNightlyReviewUsers = async (const getDb = dependencies.getDb ?? getServerDB;const page = await runStep(context,- `agent-signal:nightly-review:list-users:${cursor?.id ?? 'root'}`,+ `${stepPrefix}:list-users:${cursor?.id ?? 'root'}`,async () => {const db = await getDb();const service = createScheduleService(db);return service.listEligibleUsersPage({cursor,+ job,limit: pageSize,requestedAt: parseWorkflowDate(payload.requestedAt, 'Invalid nightly review requestedAt'),whitelist: payload.whitelist,@@ -137,8 +155,9 @@ export const paginateNightlyReviewUsers = async (await Promise.all(batches.map((batchUsers, index) =>- runStep(context, `agent-signal:nightly-review:fanout:${index + 1}/${batches.length}`, () =>+ runStep(context, `${stepPrefix}:fanout:${index + 1}/${batches.length}`, () =>triggerPaginateUsers({+ job,pageSize,requestedAt: payload.requestedAt,targetLimit,@@ -157,9 +176,10 @@ export const paginateNightlyReviewUsers = async (: undefined;if (nextCursor) {- await runStep(context, `agent-signal:nightly-review:next-page:${nextCursor.id}`, () =>+ await runStep(context, `${stepPrefix}:next-page:${nextCursor.id}`, () =>triggerPaginateUsers({cursor: nextCursor,+ job,pageSize,requestedAt: payload.requestedAt,targetLimit,@@ -214,9 +234,19 @@ export const executeNightlyReviewUser = async (DEFAULT_TARGET_LIMIT,HARD_MAX_TARGET_LIMIT,);+ const getDb = dependencies.getDb ?? getServerDB;++ if (payload.job === 'bot-retro') {+ return executeBotRetroUser(context, {+ createBotRetroService: dependencies.createBotRetroService,+ getDb,+ requestedAt,+ targetLimit,+ });+ }+const createScheduleService =dependencies.createScheduleService ?? createServerNightlyReviewScheduleService;- const getDb = dependencies.getDb ?? getServerDB;const summary = await runStep(context,`agent-signal:nightly-review:dispatch-user:${payload.user.id}`,@@ -239,6 +269,63 @@ export const executeNightlyReviewUser = async (return { ...summary, success: true, userId: payload.user.id };};+/**+ * Runs the `bot-retro` job for one user: one durable step lists the agents that worked in a bot+ * topic on the user's previous local day, then one step per agent writes its retro, so a failed+ * agent retries alone.+ *+ * Call stack:+ *+ * executeNightlyReviewUser (job: 'bot-retro')+ * -> executeBotRetroUser+ * -> {@link BotRetroService.listTargets}+ * -> {@link BotRetroService.runForAgent}+ */+const executeBotRetroUser = async (+ context: WorkflowContext<ExecuteNightlyReviewUserPayload>,+ options: {+ createBotRetroService?: NightlyReviewWorkflowDependencies['createBotRetroService'];+ getDb: typeof getServerDB;+ requestedAt: Date;+ targetLimit: number;+ },+) => {+ const { user } = context.requestPayload;+ const window = getLocalNightWindow(options.requestedAt, user.timezone, 'bot-retro');++ if (!window.withinWindow) return { enqueued: 0, skipped: 1, success: true, userId: user.id };++ const createService =+ options.createBotRetroService ??+ ((db: Awaited<ReturnType<typeof getServerDB>>, userId: string) =>+ new BotRetroService(db, userId));+ const withService = async () => createService(await options.getDb(), user.id);++ const agentIds = await runStep(+ context,+ `agent-signal:nightly-bot-retro:list-agents:${user.id}`,+ async () =>+ (await withService()).listTargets({+ limit: options.targetLimit,+ windowEnd: window.reviewWindowEnd,+ windowStart: window.reviewWindowStart,+ }),+ );++ for (const agentId of agentIds) {+ await runStep(context, `agent-signal:nightly-bot-retro:run:${agentId}`, async () =>+ (await withService()).runForAgent({+ agentId,+ localDate: window.localDate,+ windowEnd: window.reviewWindowEnd,+ windowStart: window.reviewWindowStart,+ }),+ );+ }++ return { enqueued: agentIds.length, skipped: 0, success: true, userId: user.id };+};+/*** Serve options for serialized cursor pagination.*diff --git a/apps/server/src/services/agentSignal/services/botRetro/__tests__/documents.test.ts b/apps/server/src/services/agentSignal/services/botRetro/__tests__/documents.test.tsnew file mode 100644index 00000000000..f9808c9ab67--- /dev/null+++ b/apps/server/src/services/agentSignal/services/botRetro/__tests__/documents.test.ts@@ -0,0 +1,81 @@+import { describe, expect, it } from 'vitest';++import {+ hasBotRetroLogEntry,+ parseBotLessons,+ prependBotRetroLogEntry,+ renderBotLessons,+ renderBotRetroLogEntry,+} from '../documents';++describe('bot retro documents', () => {+ it('round-trips lessons through the lessons document', () => {+ const lessons = [+ 'Confirm the thread before replying',+ 'Change approach after one failed retry',+ ];++ expect(parseBotLessons(renderBotLessons(lessons))).toEqual(lessons);+ });++ it('reads lessons the owner edited by hand, whatever list marker they used', () => {+ const content = '# Bot lessons\n\nIntro line\n\n* first\n1. second\n- third\nnot a list item';++ expect(parseBotLessons(content)).toEqual(['first', 'second', 'third']);+ expect(parseBotLessons(undefined)).toEqual([]);+ });++ it('marks each platform issue as vented or not and leaves empty sections out', () => {+ const entry = renderBotRetroLogEntry({+ date: '2026-11-01',+ platformIssues: [+ { detail: 'returned 500 three times', title: 'web search down', vented: true },+ { detail: 'no tool to edit a sent message', title: 'missing edit tool', vented: false },+ ],+ selfMistakes: [],+ summary: 'A busy day.',+ });++ expect(entry).toContain('## 2026-11-01');+ expect(entry).toContain('- [vented] **web search down** — returned 500 three times');+ expect(entry).toContain('- [not vented] **missing edit tool**');+ expect(entry).not.toContain('### My mistakes');+ });++ it('prepends the newest entry, keeps the owner header and caps the entry count', () => {+ let content: string | undefined;+ for (const day of ['01', '02', '03']) {+ content = prependBotRetroLogEntry(+ content,+ renderBotRetroLogEntry({+ date: `2026-11-${day}`,+ platformIssues: [],+ selfMistakes: [{ lesson: 'ask first', what: `guessed on day ${day}` }],+ summary: `Day ${day}.`,+ }),+ 2,+ );+ }++ expect(content!.startsWith('# Bot retro log')).toBe(true);+ expect(content!.indexOf('## 2026-11-03')).toBeLessThan(content!.indexOf('## 2026-11-02'));+ expect(content).not.toContain('## 2026-11-01');+ expect(content).toContain('- guessed on day 03 → next time: ask first');+ });++ it('detects an already written day so a second tick skips it', () => {+ const content = prependBotRetroLogEntry(+ undefined,+ renderBotRetroLogEntry({+ date: '2026-11-01',+ platformIssues: [],+ selfMistakes: [],+ summary: 'Quiet.',+ }),+ );++ expect(hasBotRetroLogEntry(content, '2026-11-01')).toBe(true);+ expect(hasBotRetroLogEntry(content, '2026-11-02')).toBe(false);+ expect(hasBotRetroLogEntry(undefined, '2026-11-01')).toBe(false);+ });+});diff --git a/apps/server/src/services/agentSignal/services/botRetro/__tests__/index.test.ts b/apps/server/src/services/agentSignal/services/botRetro/__tests__/index.test.tsnew file mode 100644index 00000000000..e378cef6421--- /dev/null+++ b/apps/server/src/services/agentSignal/services/botRetro/__tests__/index.test.ts@@ -0,0 +1,277 @@+// @vitest-environment node+import { PolicyLoad } from '@lobechat/agent-templates';+import { TRACING_SCENARIOS } from '@lobechat/const';+import { BOT_RETRO_JSON_SCHEMA, BOT_RETRO_PROMPT_VERSION } from '@lobechat/prompts';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { AgentDocumentVfsError } from '@/server/services/agentDocumentVfs/errors';++import {+ BOT_LESSONS_FILENAME,+ BOT_REFLECTION_FOLDER,+ BOT_RETRO_LOG_FILENAME,+ renderBotLessons,+} from '../documents';+import { BotRetroService, toBotRetroVent } from '../index';++const mocks = vi.hoisted(() => ({+ createFolder: vi.fn(),+ generateObject: vi.fn(),+ getAgentMeta: vi.fn(),+ getDocumentByFilename: vi.fn(),+ listBotTopics: vi.fn(),+ listOwnerWakeMarks: vi.fn(),+ listVents: vi.fn(),+ moveDocuments: vi.fn(),+ upsertDocument: vi.fn(),+ upsertDocumentByFilename: vi.fn(),+}));++vi.mock('@/database/models/agentSignal/botRetro', () => ({+ AgentBotRetroModel: class {+ getAgentMeta = mocks.getAgentMeta;+ listBotActiveAgents = vi.fn();+ listBotTopics = mocks.listBotTopics;+ listOwnerWakeMarks = mocks.listOwnerWakeMarks;+ listVents = mocks.listVents;+ },+}));++vi.mock('@/server/services/agentDocuments', () => ({+ AgentDocumentsService: class {+ createFolder = mocks.createFolder;+ getDocumentByFilename = mocks.getDocumentByFilename;+ moveDocuments = mocks.moveDocuments;+ upsertDocument = mocks.upsertDocument;+ upsertDocumentByFilename = mocks.upsertDocumentByFilename;+ },+}));++vi.mock('@/server/services/aiGeneration', () => ({+ AiGenerationService: class {+ generateObject = mocks.generateObject;+ },+}));++const input = {+ agentId: 'agent-1',+ localDate: '2026-11-01',+ windowEnd: new Date('2026-11-02T00:00:00.000Z'),+ windowStart: new Date('2026-11-01T00:00:00.000Z'),+};++const topic = {+ assistantMessageCount: 3,+ failedMessages: [],+ failedToolCalls: [{ apiName: 'search', errorSummary: '500', identifier: 'web-search' }],+ lastActivityAt: new Date('2026-11-01T12:00:00.000Z'),+ messageCount: 6,+ platform: 'discord',+ summary: 'deploy help',+ title: 'deploy thread',+ topicId: 'tpc-1',+};++const ventRow = {+ arguments: '{"category":"platform_bug","severity":"high","summary":"search 500s"}',+ createdAt: new Date('2026-11-01T12:00:00.000Z'),+ messageId: 'msg-vent',+ state: { recorded: true },+ topicId: 'tpc-1',+};++const files = (docs: Record<string, string | undefined>) =>+ mocks.getDocumentByFilename.mockImplementation(async (_agentId: string, filename: string) =>+ docs[filename] === undefined ? undefined : { content: docs[filename] },+ );++describe('BotRetroService.runForAgent', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.listBotTopics.mockResolvedValue([topic]);+ mocks.listVents.mockResolvedValue([ventRow]);+ mocks.listOwnerWakeMarks.mockResolvedValue([+ { label: 'false_wake', outcome: 'wake', reason: null, topicId: 'tpc-1' },+ ]);+ mocks.getAgentMeta.mockResolvedValue({ description: null, title: 'Shadow' });+ files({});+ mocks.upsertDocument.mockImplementation(async ({ filename }) => ({ id: `row-${filename}` }));+ mocks.moveDocuments.mockResolvedValue([{ id: 'row', status: 'moved' }]);+ mocks.createFolder.mockResolvedValue({+ created: true,+ folder: { documentId: 'docs_folder' },+ });+ });++ it('skips a day the log already holds, before reading or calling the model', async () => {+ files({ [BOT_RETRO_LOG_FILENAME]: '# Bot retro log\n\n## 2026-11-01\n\nDone.' });++ const outcome = await new BotRetroService({} as never, 'user-1').runForAgent(input);++ expect(outcome).toEqual({ reason: 'already_reviewed', status: 'skipped' });+ expect(mocks.listBotTopics).not.toHaveBeenCalled();+ expect(mocks.generateObject).not.toHaveBeenCalled();+ expect(mocks.createFolder).not.toHaveBeenCalled();+ });++ it('skips an agent with no bot conversation in the window', async () => {+ mocks.listBotTopics.mockResolvedValue([]);++ const outcome = await new BotRetroService({} as never, 'user-1').runForAgent(input);++ expect(outcome).toEqual({ reason: 'no_bot_activity', status: 'skipped' });+ expect(mocks.generateObject).not.toHaveBeenCalled();+ expect(mocks.createFolder).not.toHaveBeenCalled();+ });++ it('splits platform issues from own mistakes and writes both documents into the folder', async () => {+ mocks.generateObject.mockResolvedValue({+ lessons: ['Reply only when addressed or clearly invited'],+ platformIssues: [+ { detail: 'web search returned 500', title: 'search down', ventId: 'msg-vent' },+ { detail: 'cannot edit a sent message', title: 'no edit tool', ventId: 'made-up' },+ ],+ selfMistakes: [+ {+ lesson: 'Reply only when addressed or clearly invited',+ topicId: 'tpc-1',+ what: 'Jumped into a conversation between two people',+ },+ ],+ summary: 'Busy day with one bad wake.',+ });++ const outcome = await new BotRetroService({} as never, 'user-1').runForAgent(input);++ expect(outcome).toEqual({+ lessonCount: 1,+ platformIssueCount: 2,+ selfMistakeCount: 1,+ status: 'written',+ });++ const [request, options] = mocks.generateObject.mock.calls[0];+ expect(request.schema).toBe(BOT_RETRO_JSON_SCHEMA);+ const prompt = request.messages[1].content as string;+ expect(prompt).toContain('ventId msg-vent · platform_bug/high');+ expect(prompt).toContain('- false_wake (you woke) · topicId tpc-1');+ expect(prompt).toContain('failed tool web-search/search: 500');+ expect(options.tracing).toMatchObject({+ agentId: 'agent-1',+ promptVersion: BOT_RETRO_PROMPT_VERSION,+ scenario: TRACING_SCENARIOS.BotRetro,+ schemaName: BOT_RETRO_JSON_SCHEMA.name,+ });++ expect(mocks.upsertDocument).toHaveBeenCalledWith({+ agentId: 'agent-1',+ content: renderBotLessons(['Reply only when addressed or clearly invited']),+ filename: BOT_LESSONS_FILENAME,+ policyLoad: PolicyLoad.ALWAYS,+ });+ expect(mocks.createFolder).toHaveBeenCalledTimes(1);+ expect(mocks.createFolder).toHaveBeenCalledWith('agent-1', BOT_REFLECTION_FOLDER);+ expect(mocks.moveDocuments.mock.calls).toEqual([+ ['agent-1', [`row-${BOT_LESSONS_FILENAME}`], 'docs_folder'],+ ['agent-1', [`row-${BOT_RETRO_LOG_FILENAME}`], 'docs_folder'],+ ]);++ const logWrite = mocks.upsertDocument.mock.calls.find(+ ([call]) => call.filename === BOT_RETRO_LOG_FILENAME,+ )![0];+ expect(logWrite.policyLoad).toBe(PolicyLoad.DISABLED);+ expect(logWrite.content).toContain('- [vented] **search down**');+ // A vent id the agent never filed does not count as reported.+ expect(logWrite.content).toContain('- [not vented] **no edit tool**');+ expect(logWrite.content).toContain(+ '- Jumped into a conversation between two people → next time: Reply only when addressed or clearly invited',+ );+ });++ it('keeps existing lessons on a quiet day and updates existing documents in place', async () => {+ const existingLessons = renderBotLessons(['Confirm the thread first']);+ files({+ [BOT_LESSONS_FILENAME]: existingLessons,+ [BOT_RETRO_LOG_FILENAME]: '# Bot retro log\n\n## 2026-10-31\n\nQuiet.',+ });+ mocks.generateObject.mockResolvedValue({+ lessons: [],+ platformIssues: [],+ selfMistakes: [],+ summary: 'Nothing went wrong.',+ });++ await new BotRetroService({} as never, 'user-1').runForAgent(input);++ expect(mocks.generateObject.mock.calls[0][0].messages[1].content).toContain(+ '- Confirm the thread first',+ );+ expect(mocks.upsertDocument).not.toHaveBeenCalled();+ // Existing documents are updated wherever they are; nothing is created or moved.+ expect(mocks.createFolder).not.toHaveBeenCalled();+ expect(mocks.moveDocuments).not.toHaveBeenCalled();+ expect(mocks.upsertDocumentByFilename).toHaveBeenCalledTimes(1);+ const [logWrite] = mocks.upsertDocumentByFilename.mock.calls[0];+ expect(logWrite.filename).toBe(BOT_RETRO_LOG_FILENAME);+ expect(logWrite.content.indexOf('## 2026-11-01')).toBeLessThan(+ logWrite.content.indexOf('## 2026-10-31'),+ );+ });++ it('falls back to the top level when an ordinary document already has the folder name', async () => {+ mocks.createFolder.mockRejectedValue(+ new AgentDocumentVfsError('A document named "Bot Reflection" already exists', 'CONFLICT'),+ );+ mocks.generateObject.mockResolvedValue({+ lessons: ['Ask before guessing'],+ platformIssues: [],+ selfMistakes: [],+ summary: 'Fine.',+ });++ await new BotRetroService({} as never, 'user-1').runForAgent(input);++ expect(mocks.upsertDocument).toHaveBeenCalledTimes(2);+ expect(mocks.moveDocuments).not.toHaveBeenCalled();+ });++ it('does not swallow other folder failures', async () => {+ mocks.createFolder.mockRejectedValue(new Error('db down'));+ mocks.generateObject.mockResolvedValue({+ lessons: ['Ask before guessing'],+ platformIssues: [],+ selfMistakes: [],+ summary: 'Fine.',+ });++ await expect(new BotRetroService({} as never, 'user-1').runForAgent(input)).rejects.toThrow(+ 'db down',+ );+ expect(mocks.moveDocuments).not.toHaveBeenCalled();+ });++ it('rejects a malformed model answer without touching the documents', async () => {+ mocks.generateObject.mockResolvedValue({ summary: 'missing lists' });++ await expect(new BotRetroService({} as never, 'user-1').runForAgent(input)).rejects.toThrow();+ expect(mocks.upsertDocument).not.toHaveBeenCalled();+ expect(mocks.upsertDocumentByFilename).not.toHaveBeenCalled();+ });+});++describe('toBotRetroVent', () => {+ it('reads the vent arguments and treats a rejected call as not recorded', () => {+ expect(toBotRetroVent(ventRow)).toEqual({+ category: 'platform_bug',+ details: undefined,+ id: 'msg-vent',+ recorded: true,+ severity: 'high',+ summary: 'search 500s',+ topicId: 'tpc-1',+ });+ expect(+ toBotRetroVent({ ...ventRow, arguments: 'not json', state: { recorded: false } }),+ ).toMatchObject({ category: undefined, id: 'msg-vent', recorded: false });+ });+});diff --git a/apps/server/src/services/agentSignal/services/botRetro/documents.ts b/apps/server/src/services/agentSignal/services/botRetro/documents.tsnew file mode 100644index 00000000000..b3599a85a97--- /dev/null+++ b/apps/server/src/services/agentSignal/services/botRetro/documents.ts@@ -0,0 +1,118 @@+/** Folder the retro documents live in, so they do not crowd the agent's top-level documents. */+export const BOT_REFLECTION_FOLDER = 'Bot Reflection';++/**+ * Agent document holding the lessons a bot agent keeps in front of itself. Loaded into every run+ * of the agent; the owner may edit or disable it, and the next retro starts from whatever is there.+ */+export const BOT_LESSONS_FILENAME = 'bot-lessons.md';++/** Agent document holding the dated retro entries, newest first. Not loaded into runs. */+export const BOT_RETRO_LOG_FILENAME = 'bot-retro-log.md';++/** Oldest entries past this count are dropped from the retro log. */+export const BOT_RETRO_LOG_MAX_ENTRIES = 30;++const LESSONS_HEADER = [+ '# Bot lessons',+ '',+ 'Habits I keep after reviewing my chat-platform conversations each night. Edit freely; the next nightly retro starts from this list.',+ '',+].join('\n');++const LOG_HEADER = [+ '# Bot retro log',+ '',+ 'What I reviewed each night: platform problems (and whether I vented them) and my own mistakes.',+ '',+].join('\n');++const LIST_ITEM = /^\s*(?:[-*+]|\d+\.)\s+(.+?)\s*$/;+const ENTRY_HEADING = /^## \d{4}-\d{2}-\d{2}\s*$/m;++export interface BotRetroPlatformIssue {+ detail: string;+ title: string;+ /** Whether a vent the agent filed covers this issue. */+ vented: boolean;+}++export interface BotRetroSelfMistake {+ lesson: string;+ what: string;+}++export interface BotRetroLogEntryInput {+ date: string;+ platformIssues: BotRetroPlatformIssue[];+ selfMistakes: BotRetroSelfMistake[];+ summary: string;+}++/**+ * Reads the lessons back from the lessons document: every list item, in order.+ *+ * Before:+ * - "# Bot lessons\n\n...\n\n- Confirm the thread before replying\n- Never retry …"+ *+ * After:+ * - ["Confirm the thread before replying", "Never retry …"]+ */+export const parseBotLessons = (content: string | null | undefined): string[] =>+ (content ?? '').split('\n').flatMap((line) => {+ const match = LIST_ITEM.exec(line);+ return match ? [match[1]] : [];+ });++/** Renders the full lessons document from the merged lesson list. */+export const renderBotLessons = (lessons: string[]): string =>+ `${LESSONS_HEADER}\n${lessons.map((lesson) => `- ${lesson}`).join('\n')}\n`;++/** Whether the retro log already holds an entry for `date`; a second run for that day is skipped. */+export const hasBotRetroLogEntry = (content: string | null | undefined, date: string): boolean =>+ new RegExp(`^## ${date}\\s*$`, 'm').test(content ?? '');++/** Renders one dated retro entry. Empty sections are left out. */+export const renderBotRetroLogEntry = (entry: BotRetroLogEntryInput): string => {+ const lines = [`## ${entry.date}`, '', entry.summary.trim()];++ if (entry.platformIssues.length > 0) {+ lines.push('', '### Platform issues', '');+ for (const issue of entry.platformIssues) {+ lines.push(+ `- ${issue.vented ? '[vented]' : '[not vented]'} **${issue.title.trim()}** — ${issue.detail.trim()}`,+ );+ }+ }++ if (entry.selfMistakes.length > 0) {+ lines.push('', '### My mistakes', '');+ for (const mistake of entry.selfMistakes) {+ lines.push(`- ${mistake.what.trim()} → next time: ${mistake.lesson.trim()}`);+ }+ }++ return lines.join('\n');+};++/**+ * Puts a new entry at the top of the retro log and drops entries past+ * {@link BOT_RETRO_LOG_MAX_ENTRIES}. Anything the owner wrote above the first entry is kept.+ */+export const prependBotRetroLogEntry = (+ content: string | null | undefined,+ entry: string,+ maxEntries = BOT_RETRO_LOG_MAX_ENTRIES,+): string => {+ const existing = content?.trim() ? content : LOG_HEADER;+ const firstEntry = existing.search(ENTRY_HEADING);+ const head = (firstEntry === -1 ? existing : existing.slice(0, firstEntry)).trimEnd();+ const body = firstEntry === -1 ? '' : existing.slice(firstEntry);++ const entries = body+ .split(/^(?=## \d{4}-\d{2}-\d{2}\s*$)/m)+ .map((part) => part.trim())+ .filter(Boolean);++ return `${[head, entry.trim(), ...entries].slice(0, maxEntries + 1).join('\n\n')}\n`;+};diff --git a/apps/server/src/services/agentSignal/services/botRetro/index.ts b/apps/server/src/services/agentSignal/services/botRetro/index.tsnew file mode 100644index 00000000000..3b24a15b48a--- /dev/null+++ b/apps/server/src/services/agentSignal/services/botRetro/index.ts@@ -0,0 +1,287 @@+import { PolicyLoad } from '@lobechat/agent-templates';+import { DEFAULT_SYSTEM_AGENT_ITEM, TRACING_SCENARIOS } from '@lobechat/const';+import {+ BOT_RETRO_JSON_SCHEMA,+ BOT_RETRO_PROMPT_VERSION,+ type BotRetroVentInput,+ chainBotRetro,+} from '@lobechat/prompts';+import { RequestTrigger } from '@lobechat/types';+import debug from 'debug';+import { z } from 'zod';++import { AgentBotRetroModel, type BotRetroVentRow } from '@/database/models/agentSignal/botRetro';+import type { LobeChatDatabase } from '@/database/type';+import { AgentDocumentsService } from '@/server/services/agentDocuments';+import { AgentDocumentVfsError } from '@/server/services/agentDocumentVfs/errors';+import { AiGenerationService } from '@/server/services/aiGeneration';++import {+ BOT_LESSONS_FILENAME,+ BOT_REFLECTION_FOLDER,+ BOT_RETRO_LOG_FILENAME,+ hasBotRetroLogEntry,+ parseBotLessons,+ prependBotRetroLogEntry,+ renderBotLessons,+ renderBotRetroLogEntry,+} from './documents';++export * from './documents';++const log = debug('lobe-server:agent-signal:bot-retro');++/** Bounds on how much of one day the retro reads. */+const MAX_TOPICS = 30;+const MAX_VENTS = 20;+const MAX_WAKE_MARKS = 30;++const BotRetroResultSchema = z.object({+ lessons: z.array(z.string().trim().min(1)).max(15),+ platformIssues: z+ .array(+ z.object({+ detail: z.string(),+ title: z.string().trim().min(1),+ ventId: z.string().nullable(),+ }),+ )+ .max(10),+ selfMistakes: z+ .array(+ z.object({+ lesson: z.string().trim().min(1),+ topicId: z.string().nullable(),+ what: z.string().trim().min(1),+ }),+ )+ .max(10),+ summary: z.string(),+});++export type BotRetroResult = z.infer<typeof BotRetroResultSchema>;++export interface RunBotRetroInput {+ agentId: string;+ /** Local review date, `YYYY-MM-DD`; also the retro log heading. */+ localDate: string;+ windowEnd: Date;+ windowStart: Date;+}++export type RunBotRetroOutcome =+ | { reason: 'already_reviewed' | 'no_bot_activity'; status: 'skipped' }+ | {+ lessonCount: number;+ platformIssueCount: number;+ selfMistakeCount: number;+ status: 'written';+ };++const readString = (value: unknown) =>+ typeof value === 'string' && value.trim() ? value.trim() : undefined;++/**+ * Normalizes one vent tool call into prompt input.+ *+ * Before:+ * - { arguments: '{"category":"platform_bug","summary":"…"}', state: { recorded: true } }+ *+ * After:+ * - { category: 'platform_bug', id: '<messageId>', recorded: true, summary: '…' }+ */+export const toBotRetroVent = (row: BotRetroVentRow): BotRetroVentInput => {+ let args: Record<string, unknown> = {};+ try {+ const parsed: unknown = JSON.parse(row.arguments ?? '{}');+ if (parsed && typeof parsed === 'object') args = parsed as Record<string, unknown>;+ } catch {+ // A malformed call still counts as a vent the agent tried to file.+ }++ return {+ category: readString(args.category),+ details: readString(args.details)?.slice(0, 500),+ id: row.messageId,+ recorded: row.state?.recorded !== false,+ severity: readString(args.severity),+ summary: readString(args.summary)?.slice(0, 200),+ topicId: row.topicId,+ };+};++/**+ * Nightly retro of a bot-connected agent over one local day of chat-platform conversations.+ *+ * Writes two agent documents: {@link BOT_LESSONS_FILENAME} (the merged lessons, loaded into every+ * future run) and {@link BOT_RETRO_LOG_FILENAME} (the dated entry: platform issues marked vented+ * or not, and the agent's own mistakes).+ */+export class BotRetroService {+ private readonly db: LobeChatDatabase;+ private readonly model: AgentBotRetroModel;+ private readonly userId: string;++ constructor(db: LobeChatDatabase, userId: string) {+ this.db = db;+ this.userId = userId;+ this.model = new AgentBotRetroModel(db, userId);+ }++ /** Agents that worked in a bot topic during the window, busiest first. */+ listTargets = (options: { limit: number; windowEnd: Date; windowStart: Date }) =>+ this.model.listBotActiveAgents(options);++ /**+ * Runs one agent's retro for one day.+ *+ * Idempotent per day: a log that already has the day's heading is left alone, so the hourly+ * scheduler can tick twice inside the night window.+ */+ runForAgent = async (input: RunBotRetroInput): Promise<RunBotRetroOutcome> => {+ const { agentId, localDate, windowEnd, windowStart } = input;+ const documents = new AgentDocumentsService(this.db, this.userId);++ const logDoc = await documents.getDocumentByFilename(agentId, BOT_RETRO_LOG_FILENAME);+ if (hasBotRetroLogEntry(logDoc?.content, localDate)) {+ return { reason: 'already_reviewed', status: 'skipped' };+ }++ const window = { agentId, windowEnd, windowStart };+ const [topics, ventRows, wakeMarks, agent, lessonsDoc] = await Promise.all([+ this.model.listBotTopics({ ...window, limit: MAX_TOPICS }),+ this.model.listVents({ ...window, limit: MAX_VENTS }),+ this.model.listOwnerWakeMarks({ ...window, limit: MAX_WAKE_MARKS }),+ this.model.getAgentMeta(agentId),+ documents.getDocumentByFilename(agentId, BOT_LESSONS_FILENAME),+ ]);++ if (topics.length === 0) return { reason: 'no_bot_activity', status: 'skipped' };++ const vents = ventRows.map(toBotRetroVent);+ const existingLessons = parseBotLessons(lessonsDoc?.content);++ const ai = new AiGenerationService(this.db, this.userId);+ const result = BotRetroResultSchema.parse(+ await ai.generateObject(+ {+ ...chainBotRetro({+ agent: { description: agent?.description, title: agent?.title },+ date: localDate,+ lessons: existingLessons,+ topics,+ vents,+ wakeMarks,+ }),+ model: DEFAULT_SYSTEM_AGENT_ITEM.model,+ provider: DEFAULT_SYSTEM_AGENT_ITEM.provider,+ schema: BOT_RETRO_JSON_SCHEMA,+ },+ {+ metadata: { trigger: RequestTrigger.AgentSignal },+ tracing: {+ agentId,+ metadata: { localDate },+ promptVersion: BOT_RETRO_PROMPT_VERSION,+ scenario: TRACING_SCENARIOS.BotRetro,+ schemaName: BOT_RETRO_JSON_SCHEMA.name,+ },+ },+ ),+ );++ // The folder is created on the first new document only, so a skipped day never leaves an+ // empty folder behind, and documents that already exist are updated wherever the owner keeps them.+ let folderId: string | null | undefined;+ const ensureFolder = async () => {+ if (folderId !== undefined) return folderId;+ try {+ folderId = (await documents.createFolder(agentId, BOT_REFLECTION_FOLDER)).folder.documentId;+ } catch (error) {+ // An ordinary document already holds the folder's name: keep the retro at the top level.+ if (!(error instanceof AgentDocumentVfsError && error.code === 'CONFLICT')) throw error;+ log('agent=%s folder name %s is taken by a document', agentId, BOT_REFLECTION_FOLDER);+ folderId = null;+ }+ return folderId;+ };+ const createInFolder = async (+ params: Parameters<AgentDocumentsService['upsertDocument']>[0],+ ) => {+ const created = await documents.upsertDocument(params);+ const parentId = await ensureFolder();+ if (!parentId) return;++ const [moved] = await documents.moveDocuments(agentId, [created.id], parentId);+ if (moved?.status === 'failed')+ log('agent=%s kept %s at the top level: %s', agentId, params.filename, moved.error);+ };++ // A vent id the model names but the agent never filed is a slip, not a vent.+ const ventIds = new Set(vents.map((vent) => vent.id));+ const platformIssues = result.platformIssues.map((issue) => ({+ detail: issue.detail,+ title: issue.title,+ vented: issue.ventId !== null && ventIds.has(issue.ventId),+ }));++ // An empty list from the model on a quiet day must not wipe the lessons the agent already has.+ const lessons = result.lessons.length > 0 ? result.lessons : existingLessons;+ if (lessons.length > 0 && lessons.join('\n') !== existingLessons.join('\n')) {+ if (lessonsDoc) {+ await documents.upsertDocumentByFilename({+ agentId,+ content: renderBotLessons(lessons),+ filename: BOT_LESSONS_FILENAME,+ });+ } else {+ await createInFolder({+ agentId,+ content: renderBotLessons(lessons),+ filename: BOT_LESSONS_FILENAME,+ policyLoad: PolicyLoad.ALWAYS,+ });+ }+ }++ const logContent = prependBotRetroLogEntry(+ logDoc?.content,+ renderBotRetroLogEntry({+ date: localDate,+ platformIssues,+ selfMistakes: result.selfMistakes,+ summary: result.summary,+ }),+ );+ if (logDoc) {+ await documents.upsertDocumentByFilename({+ agentId,+ content: logContent,+ filename: BOT_RETRO_LOG_FILENAME,+ });+ } else {+ await createInFolder({+ agentId,+ content: logContent,+ filename: BOT_RETRO_LOG_FILENAME,+ policyLoad: PolicyLoad.DISABLED,+ });+ }++ log(+ 'agent=%s date=%s issues=%d mistakes=%d lessons=%d',+ agentId,+ localDate,+ platformIssues.length,+ result.selfMistakes.length,+ lessons.length,+ );++ return {+ lessonCount: lessons.length,+ platformIssueCount: platformIssues.length,+ selfMistakeCount: result.selfMistakes.length,+ status: 'written',+ };+ };+}diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/schedule.test.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/schedule.test.tsindex 60a819150c8..2fb86e4060a 100644--- a/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/schedule.test.ts+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/schedule.test.ts@@ -238,6 +238,33 @@ describe('nightlyReviewScheduleService', () => {});});+ it('filters the bot-retro job to its own 04:00-06:00 local window', async () => {+ const deps = createDeps();+ const createdAt = new Date('2026-01-01T00:00:00.000Z');+ // At 2026-05-03T20:30Z: Shanghai is 04:30 (in), Tokyo is 05:30 (in), Bangkok is 03:30 (out).+ deps.listEligibleUsers.mockResolvedValue([+ { createdAt, id: 'shanghai', timezone: 'Asia/Shanghai' },+ { createdAt, id: 'tokyo', timezone: 'Asia/Tokyo' },+ { createdAt, id: 'bangkok', timezone: 'Asia/Bangkok' },+ ]);+ const service = createSelfReviewScheduleService(deps);+ const requestedAt = new Date('2026-05-03T20:30:00.000Z');++ const page = await service.listEligibleUsersPage({+ job: 'bot-retro',+ limit: 50,+ requestedAt,+ });++ expect(deps.listEligibleUsers).toHaveBeenCalledWith({+ activeSince: new Date('2026-05-02T14:30:00.000Z'),+ limit: 50,+ localHourWindow: { at: requestedAt, endHourExclusive: 7, startHour: 3 },+ requestedAt,+ });+ expect(page.users.map((user) => user.id)).toEqual(['shanghai', 'tokyo']);+ });+/*** ROOT CAUSE:*diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/schedule.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/schedule.tsindex e96c3de4847..54c223d57ef 100644--- a/apps/server/src/services/agentSignal/services/selfIteration/review/schedule.ts+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/schedule.ts@@ -16,17 +16,28 @@ dayjs.extend(utc);dayjs.extend(timezonePlugin);const FALLBACK_TIMEZONE = 'UTC';-const NIGHT_WINDOW_START_HOUR = 2;-const NIGHT_WINDOW_END_HOUR_EXCLUSIVE = 4;++/**+ * Nightly jobs that share the scheduler: the Agent Signal self-review, and the retro a bot agent+ * writes about its day on chat platforms. Each reviews the previous local day.+ */+export type NightlyJob = 'bot-retro' | 'self-review';++/** Local hours (start inclusive, end exclusive) in which each nightly job runs. */+export const NIGHT_WINDOW_HOURS: Record<NightlyJob, { endExclusive: number; start: number }> = {+ 'bot-retro': { endExclusive: 6, start: 4 },+ 'self-review': { endExclusive: 4, start: 2 },+};/*** How far back the candidate scan looks for user activity.** A user is dispatched only if their local previous day had activity, and that day can start- * at most `NIGHT_WINDOW_END_HOUR_EXCLUSIVE + 24` hours before the cron instant. Rounding up- * keeps the floor a strict superset of every per-user window regardless of timezone.+ * at most `endExclusive + 24` hours before the cron instant. Taking the latest window keeps the+ * floor a strict superset of every per-user window of every job regardless of timezone.*/-const ACTIVITY_LOOKBACK_HOURS = 30;+const ACTIVITY_LOOKBACK_HOURS =+ Math.max(...Object.values(NIGHT_WINDOW_HOURS).map((window) => window.endExclusive)) + 24;const HOUR_IN_MS = 60 * 60 * 1000;@@ -123,6 +134,12 @@ export interface NightlyReviewScheduleAdapters {/** Options for listing exactly one page of nightly review user candidates. */export interface ListNightlyReviewEligibleUsersPageOptions extends ListNightlyReviewEligibleUsersInput {+ /**+ * Job whose local night window the page is filtered to.+ *+ * @default 'self-review'+ */+ job?: NightlyJob;/** Maximum eligible users returned by this page. */limit: number;/** UTC instant shared by the whole pagination tree, used to narrow the candidate scan. */@@ -198,7 +215,8 @@ export interface NightlyReviewScheduleService {) => Promise<NightlyReviewEligibleUsersPage>;}-interface LocalNightWindow {+/** One user's review day and whether their local clock is inside a job's night window. */+export interface LocalNightWindow {localDate: string;reviewWindowEnd: Date;reviewWindowStart: Date;@@ -219,7 +237,17 @@ const resolveTimezone = (timezone: string | null | undefined): string => {}};-const getLocalNightWindow = (now: Date, timezone: string | null | undefined): LocalNightWindow => {+/**+ * Resolves the previous local day under review and whether `now` falls in the job's night window.+ *+ * Invalid or missing timezones fall back to UTC.+ */+export const getLocalNightWindow = (+ now: Date,+ timezone: string | null | undefined,+ job: NightlyJob = 'self-review',+): LocalNightWindow => {+ const hours = NIGHT_WINDOW_HOURS[job];const resolvedTimezone = resolveTimezone(timezone);const localNow = dayjs(now).tz(resolvedTimezone);const reviewDate = localNow.subtract(1, 'day').format('YYYY-MM-DD');@@ -231,8 +259,7 @@ const getLocalNightWindow = (now: Date, timezone: string | null | undefined): LoreviewWindowEnd: localDayStart.toDate(),reviewWindowStart: localDayStart.subtract(1, 'day').toDate(),timezone: resolvedTimezone,- withinWindow:- localHour >= NIGHT_WINDOW_START_HOUR && localHour < NIGHT_WINDOW_END_HOUR_EXCLUSIVE,+ withinWindow: localHour >= hours.start && localHour < hours.endExclusive,};};@@ -341,9 +368,11 @@ export const createSelfReviewScheduleService = (},async (span) => {try {+ const { job = 'self-review', ...listOptions } = options;const { requestedAt } = options;+ const hours = NIGHT_WINDOW_HOURS[job];const scannedUsers = await adapters.listEligibleUsers({- ...options,+ ...listOptions,// Without `requestedAt` the caller is a test or a legacy path; fall back to the// unnarrowed scan rather than inventing a floor from wall-clock time....(requestedAt@@ -353,8 +382,8 @@ export const createSelfReviewScheduleService = (),localHourWindow: {at: requestedAt,- endHourExclusive: NIGHT_WINDOW_END_HOUR_EXCLUSIVE + SQL_PREFILTER_SLACK_HOURS,- startHour: NIGHT_WINDOW_START_HOUR - SQL_PREFILTER_SLACK_HOURS,+ endHourExclusive: hours.endExclusive + SQL_PREFILTER_SLACK_HOURS,+ startHour: hours.start - SQL_PREFILTER_SLACK_HOURS,},}: {}),@@ -369,7 +398,7 @@ export const createSelfReviewScheduleService = (const users = requestedAt? scannedUsers.filter(- (user) => getLocalNightWindow(requestedAt, user.timezone).withinWindow,+ (user) => getLocalNightWindow(requestedAt, user.timezone, job).withinWindow,): scannedUsers;diff --git a/apps/server/src/workflows/agentSignal/nightlyReview.ts b/apps/server/src/workflows/agentSignal/nightlyReview.tsindex 20b4488ca72..cb9773efd33 100644--- a/apps/server/src/workflows/agentSignal/nightlyReview.ts+++ b/apps/server/src/workflows/agentSignal/nightlyReview.ts@@ -4,6 +4,7 @@ import debug from 'debug';import { appEnv } from '@/envs/app';import { injectActiveTraceHeaders } from '@/libs/observability/traceparent';import { qstashClient, workflowClient } from '@/libs/qstash';+import type { NightlyJob } from '@/server/services/agentSignal/services';const log = debug('lobe-server:workflows:agent-signal:nightly-review');@@ -74,6 +75,12 @@ export interface NightlyReviewWorkflowUser {export interface PaginateNightlyReviewUsersPayload {/** Cursor from the previous page; absent for the first page or a fan-out chunk. */cursor?: NightlyReviewWorkflowCursor;+ /**+ * Nightly job this pagination tree schedules.+ *+ * @default 'self-review'+ */+ job?: NightlyJob;/** Number of users read from the database in one page. */pageSize: number;/** UTC instant shared by the complete pagination tree. */@@ -88,6 +95,12 @@ export interface PaginateNightlyReviewUsersPayload {/** Payload for a workflow that processes exactly one nightly-review user. */export interface ExecuteNightlyReviewUserPayload {+ /**+ * Nightly job to run for this user.+ *+ * @default 'self-review'+ */+ job?: NightlyJob;/** UTC instant shared by the complete pagination tree. */requestedAt: string;/** Maximum active agents dispatched for this user. */@@ -177,6 +190,7 @@ export class AgentSignalNightlyReviewWorkflow {*/static publishPaginateUsersEntry(payload: PaginateNightlyReviewUsersPayload) {log('Publishing nightly review cron entry payload=%O', {+ job: payload.job ?? 'self-review',pageSize: payload.pageSize,whitelist: payload.whitelist?.length ?? 0,});@@ -219,7 +233,11 @@ export class AgentSignalNightlyReviewWorkflow {/** Triggers one workflow that processes exactly one user. */static triggerExecuteUser(payload: ExecuteNightlyReviewUserPayload) {- log('Triggering nightly review execution userId=%s', payload.user.id);+ log(+ 'Triggering nightly review execution job=%s userId=%s',+ payload.job ?? 'self-review',+ payload.user.id,+ );return withPublishTimeout(workflowClient.trigger({diff --git a/packages/const/src/llmGenerationTracing.ts b/packages/const/src/llmGenerationTracing.tsindex b40d88ded07..c785dbfd292 100644--- a/packages/const/src/llmGenerationTracing.ts+++ b/packages/const/src/llmGenerationTracing.ts@@ -10,6 +10,7 @@ export const TRACING_SCENARIOS = {AgentSignal: 'agent_signal',AgentWelcome: 'agent_welcome',BotReplyOpener: 'bot_reply_opener',+ BotRetro: 'bot_retro',BotWakeClassifier: 'bot_wake_classifier',BuilderSuggestion: 'builder_suggestion',ChannelRouting: 'channel_routing',diff --git a/packages/database/src/models/agentSignal/__tests__/botRetro.test.ts b/packages/database/src/models/agentSignal/__tests__/botRetro.test.tsnew file mode 100644index 00000000000..101fe3b29c1--- /dev/null+++ b/packages/database/src/models/agentSignal/__tests__/botRetro.test.ts@@ -0,0 +1,335 @@+// @vitest-environment node+import { beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import {+ agents,+ messagePlugins,+ messages,+ signalDecisionLabels,+ signalDecisions,+ signals,+ topics,+ users,+} from '../../../schemas';+import type { LobeChatDatabase } from '../../../type';+import { AgentBotRetroModel } from '../botRetro';++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'bot-retro-user';+const otherUserId = 'bot-retro-other-user';+const agentId = 'bot-retro-agent';+const quietAgentId = 'bot-retro-quiet-agent';+const botTopicId = 'bot-retro-bot-topic';+const chatTopicId = 'bot-retro-chat-topic';++const windowStart = new Date('2026-11-01T00:00:00.000Z');+const windowEnd = new Date('2026-11-02T00:00:00.000Z');+const inWindow = new Date('2026-11-01T12:00:00.000Z');+const beforeWindow = new Date('2026-10-31T12:00:00.000Z');+const window = { agentId, limit: 10, windowEnd, windowStart };++const seedBase = async () => {+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);+ await serverDB.insert(agents).values([+ { description: 'Answers on Discord', id: agentId, title: 'Shadow', userId },+ { id: quietAgentId, title: 'Quiet', userId },+ ]);+ await serverDB.insert(topics).values([+ {+ agentId,+ historySummary: 'Helped with deploy questions',+ id: botTopicId,+ metadata: { bot: { platform: 'discord' } } as never,+ title: 'deploy thread',+ trigger: 'bot',+ userId,+ },+ { agentId: quietAgentId, id: chatTopicId, title: 'in-app chat', userId },+ ]);+};++describe('AgentBotRetroModel', () => {+ beforeEach(async () => {+ await serverDB.delete(users);+ });++ it('lists only agents with bot-topic messages inside the window', async () => {+ await seedBase();+ await serverDB.insert(messages).values([+ {+ agentId,+ content: 'hi',+ createdAt: inWindow,+ id: 'm-bot',+ role: 'user',+ topicId: botTopicId,+ userId,+ },+ {+ agentId: quietAgentId,+ content: 'in app',+ createdAt: inWindow,+ id: 'm-chat',+ role: 'user',+ topicId: chatTopicId,+ userId,+ },+ ]);++ const model = new AgentBotRetroModel(serverDB, userId);++ await expect(model.listBotActiveAgents({ limit: 10, windowEnd, windowStart })).resolves.toEqual(+ [agentId],+ );+ // A reused bot thread with no messages today is not activity.+ await expect(+ model.listBotActiveAgents({ limit: 10, windowEnd: windowStart, windowStart: beforeWindow }),+ ).resolves.toEqual([]);+ await expect(+ new AgentBotRetroModel(serverDB, otherUserId).listBotActiveAgents({+ limit: 10,+ windowEnd,+ windowStart,+ }),+ ).resolves.toEqual([]);+ });++ it('summarizes bot topics with replies, failed tools and failed messages of the window', async () => {+ await seedBase();+ await serverDB.insert(messages).values([+ {+ agentId,+ content: 'q',+ createdAt: inWindow,+ id: 'm-1',+ role: 'user',+ topicId: botTopicId,+ userId,+ },+ {+ agentId,+ content: 'a',+ createdAt: inWindow,+ id: 'm-2',+ role: 'assistant',+ topicId: botTopicId,+ userId,+ },+ {+ agentId,+ content: '',+ createdAt: inWindow,+ error: { message: 'provider overloaded' },+ id: 'm-3',+ role: 'assistant',+ topicId: botTopicId,+ userId,+ },+ {+ agentId,+ content: 'tool',+ createdAt: inWindow,+ id: 'm-4',+ role: 'tool',+ topicId: botTopicId,+ userId,+ },+ {+ agentId,+ content: 'old',+ createdAt: beforeWindow,+ id: 'm-old',+ role: 'assistant',+ topicId: botTopicId,+ userId,+ },+ ]);+ await serverDB.insert(messagePlugins).values({+ apiName: 'search',+ error: { message: 'timeout' },+ id: 'm-4',+ identifier: 'web-search',+ toolCallId: 'call-1',+ userId,+ });++ const [topic] = await new AgentBotRetroModel(serverDB, userId).listBotTopics(window);++ expect(topic).toMatchObject({+ assistantMessageCount: 2,+ messageCount: 4,+ platform: 'discord',+ summary: 'Helped with deploy questions',+ title: 'deploy thread',+ topicId: botTopicId,+ });+ expect(topic.failedToolCalls).toEqual([+ {+ apiName: 'search',+ errorSummary: expect.stringContaining('timeout'),+ identifier: 'web-search',+ },+ ]);+ expect(topic.failedMessages).toEqual([expect.stringContaining('provider overloaded')]);+ });++ it('lists the vent tool calls of the window, rejected ones included', async () => {+ await seedBase();+ await serverDB.insert(messages).values([+ {+ agentId,+ content: '',+ createdAt: inWindow,+ id: 'v-1',+ role: 'tool',+ topicId: botTopicId,+ userId,+ },+ {+ agentId,+ content: '',+ createdAt: inWindow,+ id: 'v-2',+ role: 'tool',+ topicId: botTopicId,+ userId,+ },+ {+ agentId,+ content: '',+ createdAt: beforeWindow,+ id: 'v-old',+ role: 'tool',+ topicId: botTopicId,+ userId,+ },+ {+ agentId,+ content: '',+ createdAt: inWindow,+ id: 'not-vent',+ role: 'tool',+ topicId: botTopicId,+ userId,+ },+ ]);+ await serverDB.insert(messagePlugins).values([+ {+ apiName: 'vent',+ arguments: '{"category":"platform_bug","summary":"search 500s"}',+ id: 'v-1',+ identifier: 'lobe-agent',+ state: { recorded: true, ventId: 'v-1' },+ userId,+ },+ {+ apiName: 'vent',+ arguments: '{}',+ id: 'v-2',+ identifier: 'lobe-agent',+ state: { recorded: false },+ userId,+ },+ { apiName: 'vent', arguments: '{}', id: 'v-old', identifier: 'lobe-agent', userId },+ {+ apiName: 'callSubAgent',+ arguments: '{}',+ id: 'not-vent',+ identifier: 'lobe-agent',+ userId,+ },+ ]);++ const vents = await new AgentBotRetroModel(serverDB, userId).listVents(window);++ expect(vents.map((vent) => vent.messageId).sort()).toEqual(['v-1', 'v-2']);+ expect(vents.find((vent) => vent.messageId === 'v-2')?.state).toEqual({ recorded: false });+ });++ it('keeps only decisions whose latest owner mark says the wake was wrong', async () => {+ await seedBase();+ const [signal] = await serverDB+ .insert(signals)+ .values({+ externalId: 'app:thread:1',+ payload: {},+ scopeKey: 'discord:app',+ source: 'bot:discord',+ type: 'bot.message.merged',+ userId,+ })+ .returning();+ const decisionRow = (id: string, createdAt: Date) => ({+ agentId,+ createdAt,+ id,+ outcome: 'wake' as const,+ pipelineVersion: `v-${id}`,+ scopeKey: 'discord:app',+ signalId: signal.id,+ topicId: botTopicId,+ userId,+ });+ const falseWake = '00000000-0000-4000-8000-000000000001';+ const clearedMark = '00000000-0000-4000-8000-000000000002';+ const agentOnly = '00000000-0000-4000-8000-000000000003';+ const oldMark = '00000000-0000-4000-8000-000000000004';+ await serverDB+ .insert(signalDecisions)+ .values([+ decisionRow(falseWake, inWindow),+ decisionRow(clearedMark, inWindow),+ decisionRow(agentOnly, inWindow),+ decisionRow(oldMark, beforeWindow),+ ]);+ await serverDB.insert(signalDecisionLabels).values([+ {+ createdAt: new Date('2026-11-01T13:00:00.000Z'),+ decisionId: falseWake,+ label: 'false_wake',+ metadata: { rationale: 'was talking to a human' },+ source: 'user',+ },+ {+ createdAt: new Date('2026-11-01T13:00:00.000Z'),+ decisionId: clearedMark,+ label: 'false_wake',+ source: 'user',+ },+ {+ createdAt: new Date('2026-11-01T14:00:00.000Z'),+ decisionId: clearedMark,+ label: 'cleared',+ source: 'user',+ },+ { decisionId: agentOnly, label: 'false_wake', source: 'agent:no_reply' },+ { decisionId: oldMark, label: 'missed_wake', source: 'user' },+ ]);++ const marks = await new AgentBotRetroModel(serverDB, userId).listOwnerWakeMarks(window);++ expect(marks).toEqual([+ expect.objectContaining({+ decisionId: falseWake,+ label: 'false_wake',+ outcome: 'wake',+ reason: 'was talking to a human',+ topicId: botTopicId,+ }),+ ]);+ });++ it('reads the agent meta only for the owning user', async () => {+ await seedBase();++ await expect(new AgentBotRetroModel(serverDB, userId).getAgentMeta(agentId)).resolves.toEqual({+ description: 'Answers on Discord',+ title: 'Shadow',+ });+ await expect(+ new AgentBotRetroModel(serverDB, otherUserId).getAgentMeta(agentId),+ ).resolves.toBeUndefined();+ });+});diff --git a/packages/database/src/models/agentSignal/botRetro.ts b/packages/database/src/models/agentSignal/botRetro.tsnew file mode 100644index 00000000000..bc2f77df750--- /dev/null+++ b/packages/database/src/models/agentSignal/botRetro.ts@@ -0,0 +1,283 @@+import { and, asc, count, desc, eq, gte, isNull, lt, notInArray, sql } from 'drizzle-orm';++import {+ agents,+ messagePlugins,+ messages,+ signalDecisionLabels,+ signalDecisions,+ topics,+} from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import { notTrashed } from '../../utils/softDelete';++/** `topics.trigger` of a topic an external bot platform (Discord, Slack, …) started. */+export const BOT_TOPIC_TRIGGER = 'bot';++/** Identifier and api name of the `lobe-agent` vent tool call; the call row is the vent record. */+const VENT_IDENTIFIER = 'lobe-agent';+const VENT_API_NAME = 'vent';++/** `signal_decision_labels.source` of the owner's own mark on a wake decision. */+const OWNER_LABEL_SOURCE = 'user';++const parseAggregateTimestamp = (value: Date | string) =>+ value instanceof Date ? value : new Date(value);++/** One review window: UTC instants of the user's local review day, end exclusive. */+export interface BotRetroWindow {+ windowEnd: Date;+ windowStart: Date;+}++export interface ListBotRetroAgentsOptions extends BotRetroWindow {+ limit: number;+}++export interface ListBotRetroEvidenceOptions extends BotRetroWindow {+ agentId: string;+ limit: number;+}++export interface BotRetroFailedToolCall {+ apiName: string | null;+ errorSummary: string | null;+ identifier: string | null;+}++export interface BotRetroTopicRow {+ /** Assistant replies the bot posted in this topic during the window. */+ assistantMessageCount: number;+ /** Message-level errors (provider failures, aborted runs) during the window. */+ failedMessages: string[];+ failedToolCalls: BotRetroFailedToolCall[];+ lastActivityAt: Date;+ messageCount: number;+ /** Bot platform from `topics.metadata.bot.platform`, e.g. `discord`. */+ platform: string | null;+ summary: string;+ title: string | null;+ topicId: string;+}++export interface BotRetroVentRow {+ /** Raw vent arguments (category, severity, summary, details) as the agent sent them. */+ arguments: string | null;+ createdAt: Date;+ messageId: string;+ /** Tool result state; `recorded: false` means the runtime rejected the vent. */+ state: Record<string, unknown> | null;+ topicId: string | null;+}++export interface BotRetroWakeMarkRow {+ createdAt: Date;+ decisionId: string;+ finalReason: string | null;+ /** The owner's latest mark, e.g. `false_wake`, `missed_wake`, `bad_reply`. */+ label: string;+ outcome: string;+ reason: string | null;+ topicId: string | null;+}++/**+ * Reads what a bot-connected agent went through on one day, for its nightly retro.+ *+ * Scope is the user's personal space, matching the Agent Signal nightly review: workspace+ * agents are not reviewed. Everything is bounded by the caller's `limit`.+ */+export class AgentBotRetroModel {+ private readonly db: LobeChatDatabase;+ private readonly userId: string;++ constructor(db: LobeChatDatabase, userId: string) {+ this.db = db;+ this.userId = userId;+ }++ /** Reads the title and description the retro prompt introduces the agent with. */+ getAgentMeta = async (agentId: string) => {+ const [row] = await this.db+ .select({ description: agents.description, title: agents.title })+ .from(agents)+ .where(and(eq(agents.id, agentId), eq(agents.userId, this.userId)))+ .limit(1);++ return row;+ };++ /**+ * Lists agents that worked in at least one bot topic during the window, busiest first.+ *+ * Bot topics are reused per platform thread, so activity is read from message time rather+ * than topic creation time.+ */+ listBotActiveAgents = async (options: ListBotRetroAgentsOptions): Promise<string[]> => {+ const rows = await this.db+ .select({ agentId: topics.agentId, messageCount: count(messages.id) })+ .from(messages)+ .innerJoin(topics, eq(topics.id, messages.topicId))+ .innerJoin(+ agents,+ and(+ eq(agents.id, topics.agentId),+ isNull(agents.workspaceId),+ notTrashed(agents.isDeleted),+ ),+ )+ .where(+ and(+ eq(messages.userId, this.userId),+ isNull(messages.workspaceId),+ notTrashed(messages.isDeleted),+ eq(topics.trigger, BOT_TOPIC_TRIGGER),+ notTrashed(topics.isDeleted),+ gte(messages.createdAt, options.windowStart),+ lt(messages.createdAt, options.windowEnd),+ ),+ )+ .groupBy(topics.agentId)+ .orderBy(desc(count(messages.id)), asc(topics.agentId))+ .limit(options.limit);++ return rows.flatMap((row) => (row.agentId ? [row.agentId] : []));+ };++ /** Lists the agent's bot topics active in the window with their failures, latest first. */+ listBotTopics = (options: ListBotRetroEvidenceOptions): Promise<BotRetroTopicRow[]> => {+ return this.db+ .select({+ assistantMessageCount:+ sql<number>`COUNT(${messages.id}) FILTER (WHERE ${messages.role} = 'assistant')`.mapWith(+ Number,+ ),+ failedMessages: sql<string[]>`+ COALESCE(+ array_agg(DISTINCT left(${messages.error}::text, 300))+ FILTER (WHERE ${messages.error} IS NOT NULL),+ ARRAY[]::text[]+ )+ `,+ failedToolCalls: sql<BotRetroFailedToolCall[]>`+ COALESCE(+ jsonb_agg(+ DISTINCT jsonb_build_object(+ 'apiName', ${messagePlugins.apiName},+ 'errorSummary', left(${messagePlugins.error}::text, 300),+ 'identifier', ${messagePlugins.identifier}+ )+ ) FILTER (WHERE ${messagePlugins.error} IS NOT NULL),+ '[]'::jsonb+ )+ `,+ lastActivityAt: sql<Date>`MAX(${messages.createdAt})`.mapWith(parseAggregateTimestamp),+ messageCount: count(messages.id),+ platform: sql<string | null>`${topics.metadata}->'bot'->>'platform'`,+ summary: sql<string>`COALESCE(${topics.historySummary}, ${topics.description}, '')`,+ title: topics.title,+ topicId: topics.id,+ })+ .from(messages)+ .innerJoin(topics, eq(topics.id, messages.topicId))+ .leftJoin(messagePlugins, eq(messagePlugins.id, messages.id))+ .where(+ and(+ eq(messages.userId, this.userId),+ isNull(messages.workspaceId),+ notTrashed(messages.isDeleted),+ eq(topics.agentId, options.agentId),+ eq(topics.trigger, BOT_TOPIC_TRIGGER),+ notTrashed(topics.isDeleted),+ gte(messages.createdAt, options.windowStart),+ lt(messages.createdAt, options.windowEnd),+ ),+ )+ .groupBy(topics.id, topics.title, topics.historySummary, topics.description, topics.metadata)+ .orderBy(desc(sql`MAX(${messages.createdAt})`))+ .limit(options.limit);+ };++ /**+ * Lists the agent's vent calls during the window, in any topic: a platform problem the bot+ * hit is worth knowing about wherever it was reported.+ */+ listVents = (options: ListBotRetroEvidenceOptions): Promise<BotRetroVentRow[]> => {+ return this.db+ .select({+ arguments: messagePlugins.arguments,+ createdAt: messages.createdAt,+ messageId: messages.id,+ state: sql<Record<string, unknown> | null>`${messagePlugins.state}`,+ topicId: messages.topicId,+ })+ .from(messagePlugins)+ .innerJoin(messages, eq(messages.id, messagePlugins.id))+ .leftJoin(topics, eq(topics.id, messages.topicId))+ .where(+ and(+ eq(messagePlugins.userId, this.userId),+ eq(messagePlugins.identifier, VENT_IDENTIFIER),+ eq(messagePlugins.apiName, VENT_API_NAME),+ isNull(messages.workspaceId),+ notTrashed(messages.isDeleted),+ eq(sql`COALESCE(${messages.agentId}, ${topics.agentId})`, options.agentId),+ gte(messages.createdAt, options.windowStart),+ lt(messages.createdAt, options.windowEnd),+ ),+ )+ .orderBy(asc(messages.createdAt))+ .limit(options.limit);+ };++ /**+ * Lists wake decisions of the window the owner marked as wrong (`false_wake`, `missed_wake`,+ * `bad_reply`, …).+ *+ * Only the owner's latest mark counts; a mark withdrawn with `cleared` or confirmed `correct`+ * drops the decision out.+ */+ listOwnerWakeMarks = async (+ options: ListBotRetroEvidenceOptions,+ ): Promise<BotRetroWakeMarkRow[]> => {+ const latestMarks = this.db+ .selectDistinctOn([signalDecisionLabels.decisionId], {+ decisionId: signalDecisionLabels.decisionId,+ label: signalDecisionLabels.label,+ reason: sql<string | null>`COALESCE(+ ${signalDecisionLabels.metadata}->>'rationale',+ ${signalDecisionLabels.metadata}->>'reason'+ )`.as('reason'),+ })+ .from(signalDecisionLabels)+ .where(eq(signalDecisionLabels.source, OWNER_LABEL_SOURCE))+ .orderBy(signalDecisionLabels.decisionId, desc(signalDecisionLabels.createdAt))+ .as('bot_retro_owner_marks');++ const rows = await this.db+ .select({+ createdAt: signalDecisions.createdAt,+ decisionId: signalDecisions.id,+ finalReason: signalDecisions.finalReason,+ label: latestMarks.label,+ outcome: signalDecisions.outcome,+ reason: latestMarks.reason,+ topicId: signalDecisions.topicId,+ })+ .from(signalDecisions)+ .innerJoin(latestMarks, eq(latestMarks.decisionId, signalDecisions.id))+ .where(+ and(+ eq(signalDecisions.userId, this.userId),+ eq(signalDecisions.agentId, options.agentId),+ gte(signalDecisions.createdAt, options.windowStart),+ lt(signalDecisions.createdAt, options.windowEnd),+ notInArray(latestMarks.label, ['correct', 'cleared']),+ ),+ )+ .orderBy(asc(signalDecisions.createdAt))+ .limit(options.limit);++ return rows;+ };+}diff --git a/packages/prompts/src/chains/__tests__/botRetro.test.ts b/packages/prompts/src/chains/__tests__/botRetro.test.tsnew file mode 100644index 00000000000..4582a7b6961--- /dev/null+++ b/packages/prompts/src/chains/__tests__/botRetro.test.ts@@ -0,0 +1,78 @@+import { describe, expect, it } from 'vitest';++import { BOT_RETRO_JSON_SCHEMA, BOT_RETRO_PROMPT_VERSION, chainBotRetro } from '../botRetro';++const input = {+ agent: { description: 'Answers on Discord', title: 'Shadow' },+ date: '2026-11-01',+ lessons: ['Confirm the thread first'],+ topics: [+ {+ assistantMessageCount: 2,+ failedMessages: ['provider overloaded'],+ failedToolCalls: [{ apiName: 'search', errorSummary: '500', identifier: 'web-search' }],+ messageCount: 5,+ platform: 'discord',+ summary: 'deploy help',+ title: 'deploy thread',+ topicId: 'tpc-1',+ },+ ],+ vents: [+ {+ category: 'platform_bug',+ id: 'msg-vent',+ recorded: false,+ severity: 'high',+ summary: 'search 500s',+ topicId: 'tpc-1',+ },+ ],+ wakeMarks: [+ { label: 'missed_wake', outcome: 'skip', reason: 'was asked by name', topicId: null },+ ],+};++describe('chainBotRetro', () => {+ it('separates platform issues from own mistakes and treats owner marks as own mistakes', () => {+ const [system] = chainBotRetro(input).messages;++ expect(system.content).toContain('platformIssues');+ expect(system.content).toContain('selfMistakes');+ expect(system.content).toContain('Do not blame the platform for your own mistakes');+ expect(system.content).toContain('Each owner mark is your mistake');+ expect(system.content).toContain('15 or fewer');+ });++ it('hands the model the day: existing lessons, topics, vents with ids, and owner marks', () => {+ const user = chainBotRetro(input).messages[1].content as string;++ expect(user).toContain('You are Shadow — Answers on Discord. Day under review: 2026-11-01.');+ expect(user).toContain('- Confirm the thread first');+ expect(user).toContain('topicId tpc-1 · discord · deploy thread · 5 messages, 2 of them yours');+ expect(user).toContain('failed tool web-search/search: 500');+ expect(user).toContain('failed reply: provider overloaded');+ expect(user).toContain(+ 'ventId msg-vent · platform_bug/high · rejected by the runtime as a repeat',+ );+ expect(user).toContain('- missed_wake (you stayed silent) · topicId -: was asked by name');+ });++ it('says so when a section is empty instead of leaving it blank', () => {+ const user = chainBotRetro({ ...input, lessons: [], vents: [], wakeMarks: [] }).messages[1]+ .content as string;++ expect(user).toContain('Your existing lessons:\n(none yet)');+ expect(user).toContain('Vents you filed today:\n(none)');+ });++ it('keeps the schema and prompt version aligned with the prompt fields', () => {+ expect(BOT_RETRO_PROMPT_VERSION).toBe('v1');+ expect(BOT_RETRO_JSON_SCHEMA.schema.required).toEqual([+ 'lessons',+ 'platformIssues',+ 'selfMistakes',+ 'summary',+ ]);+ });+});diff --git a/packages/prompts/src/chains/botRetro.ts b/packages/prompts/src/chains/botRetro.tsnew file mode 100644index 00000000000..224be355d25--- /dev/null+++ b/packages/prompts/src/chains/botRetro.ts@@ -0,0 +1,163 @@+import type { OpenAIChatMessage } from '@lobechat/types';++interface BotRetroGenerateObjectSchema {+ name: string;+ schema: {+ additionalProperties: false;+ properties: Record<string, unknown>;+ required: string[];+ type: 'object';+ };+}++export const BOT_RETRO_PROMPT_VERSION = 'v1';++/**+ * A bot agent's nightly retro over one day of platform conversations: what got in the way, split+ * into the platform's problems (already vented, or not) and the agent's own mistakes, plus the+ * merged list of lessons it keeps in front of itself from now on.+ */+export const BOT_RETRO_JSON_SCHEMA = {+ name: 'bot_retro',+ schema: {+ additionalProperties: false,+ properties: {+ lessons: {+ items: { maxLength: 200, type: 'string' },+ maxItems: 15,+ type: 'array',+ },+ platformIssues: {+ items: {+ additionalProperties: false,+ properties: {+ detail: { maxLength: 400, type: 'string' },+ title: { maxLength: 120, type: 'string' },+ ventId: { type: ['string', 'null'] },+ },+ required: ['detail', 'title', 'ventId'],+ type: 'object',+ },+ maxItems: 10,+ type: 'array',+ },+ selfMistakes: {+ items: {+ additionalProperties: false,+ properties: {+ lesson: { maxLength: 200, type: 'string' },+ topicId: { type: ['string', 'null'] },+ what: { maxLength: 400, type: 'string' },+ },+ required: ['lesson', 'topicId', 'what'],+ type: 'object',+ },+ maxItems: 10,+ type: 'array',+ },+ summary: { maxLength: 400, type: 'string' },+ },+ required: ['lessons', 'platformIssues', 'selfMistakes', 'summary'],+ type: 'object',+ },+} as const satisfies BotRetroGenerateObjectSchema;++const BOT_RETRO_SYSTEM_PROMPT = `You are an AI agent that answers people on chat platforms (Discord, Slack, Telegram, …) as a bot. It is the end of your day. Look back over what happened in your bot conversations and reflect honestly, the way a careful professional writes a short private retro.++Sort every problem into exactly one of two kinds:+- platformIssues: the platform got in your way — a tool was missing or broken, a schema disagreed with its docs, an environment or network limit, a provider error you could not have avoided. If one of the vents you filed covers it, set ventId to that vent's id; otherwise ventId is null. List each vent you filed that still stands as an issue, even if the conversation evidence about it is thin.+- selfMistakes: you could have done better — you replied when you were not addressed, stayed silent when you were, misread the thread, called a tool with wrong arguments, gave a wrong or careless answer, retried the same failing call instead of changing approach, or ignored an instruction. "what" says what happened, concretely; "lesson" is the habit that would have prevented it, as one imperative sentence. topicId is the conversation it happened in, when there is one.++Owner marks are the strongest evidence: the person who runs you said a wake was wrong (false_wake: you should not have replied; missed_wake: you should have; bad_reply: your reply was poor). Each owner mark is your mistake unless the evidence clearly shows the platform caused it.++Do not blame the platform for your own mistakes, and do not take the blame for the platform's. Never invent problems: an ordinary day with nothing wrong gets empty lists and a one-line summary.++lessons is the complete list you will keep in front of you from tomorrow on: start from your existing lessons, add the new ones, merge duplicates, rewrite a lesson when today showed it was incomplete, and drop one only when it is clearly obsolete. Keep it at 15 or fewer, most important first. Each lesson must be general enough to apply to future conversations — no user names, server names or one-off details.++summary is one or two sentences on how the day went.++Never copy secrets, credentials or other people's private details into any field. Write every field in the language most of the conversations use; if unclear, use the language of your existing lessons.`;++export interface BotRetroTopicInput {+ assistantMessageCount: number;+ failedMessages: string[];+ failedToolCalls: {+ apiName: string | null;+ errorSummary: string | null;+ identifier: string | null;+ }[];+ messageCount: number;+ platform: string | null;+ summary: string;+ title: string | null;+ topicId: string;+}++export interface BotRetroVentInput {+ category?: string;+ details?: string;+ id: string;+ recorded: boolean;+ severity?: string;+ summary?: string;+ topicId: string | null;+}++export interface BotRetroWakeMarkInput {+ label: string;+ outcome: string;+ reason: string | null;+ topicId: string | null;+}++export interface BotRetroChainInput {+ agent: { description?: string | null; title?: string | null };+ date: string;+ lessons: string[];+ topics: BotRetroTopicInput[];+ vents: BotRetroVentInput[];+ wakeMarks: BotRetroWakeMarkInput[];+}++const formatList = <T>(items: T[], empty: string, format: (item: T) => string) =>+ items.length > 0 ? items.map(format).join('\n') : empty;++const formatTopic = (topic: BotRetroTopicInput) => {+ const lines = [+ `- topicId ${topic.topicId} · ${topic.platform ?? 'bot'} · ${topic.title || 'untitled'} · ${topic.messageCount} messages, ${topic.assistantMessageCount} of them yours`,+ ];+ if (topic.summary.trim()) lines.push(` summary: ${topic.summary.trim()}`);+ for (const call of topic.failedToolCalls) {+ lines.push(+ ` failed tool ${call.identifier ?? '?'}/${call.apiName ?? '?'}: ${call.errorSummary ?? ''}`,+ );+ }+ for (const error of topic.failedMessages) lines.push(` failed reply: ${error}`);+ return lines.join('\n');+};++export const chainBotRetro = (input: BotRetroChainInput): { messages: OpenAIChatMessage[] } => ({+ messages: [+ { content: BOT_RETRO_SYSTEM_PROMPT, role: 'system' },+ {+ content: [+ `You are ${input.agent.title || 'an assistant'}${input.agent.description ? ` — ${input.agent.description}` : ''}. Day under review: ${input.date}.`,+ `Your existing lessons:\n${formatList(input.lessons, '(none yet)', (lesson) => `- ${lesson}`)}`,+ `Bot conversations today:\n${formatList(input.topics, '(none)', formatTopic)}`,+ `Vents you filed today:\n${formatList(+ input.vents,+ '(none)',+ (vent) =>+ `- ventId ${vent.id} · ${vent.category ?? 'other'}/${vent.severity ?? '?'}${vent.recorded ? '' : ' · rejected by the runtime as a repeat'} · topicId ${vent.topicId ?? '-'}: ${vent.summary ?? ''}${vent.details ? ` — ${vent.details}` : ''}`,+ )}`,+ `Owner marks on your wake decisions today:\n${formatList(+ input.wakeMarks,+ '(none)',+ (mark) =>+ `- ${mark.label} (you ${mark.outcome === 'skip' ? 'stayed silent' : 'woke'}) · topicId ${mark.topicId ?? '-'}${mark.reason ? `: ${mark.reason}` : ''}`,+ )}`,+ ].join('\n\n'),+ role: 'user',+ },+ ],+});diff --git a/packages/prompts/src/chains/index.ts b/packages/prompts/src/chains/index.tsindex fe3daa2785f..406f159d914 100644--- a/packages/prompts/src/chains/index.ts+++ b/packages/prompts/src/chains/index.ts@@ -2,6 +2,7 @@ export * from './abstractChunk';export * from './agentSignal/analyzeIntent';export * from './answerWithContext';export * from './botReplyOpener';+export * from './botRetro';export * from './botWakeClassifier';export * from './builderSuggestion';export * from './channelRouting';