🤯 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(agent-signal,database,app,server): agent signal activities during nightly self-reflection will now push to briefs (#14437)
Nekoc744eab116d7
diff --git a/locales/ar/setting.json b/locales/ar/setting.jsonindex 63050c2ab9c..91519f8a546 100644--- a/locales/ar/setting.json+++ b/locales/ar/setting.json@@ -532,6 +532,9 @@"settingChat.inputTemplate.desc": "سيتم ملء أحدث رسالة للمستخدم في هذا القالب","settingChat.inputTemplate.placeholder": "سيتم استبدال قالب المعالجة المسبقة {{text}} بمعلومات الإدخال الفعلية","settingChat.inputTemplate.title": "معالجة مسبقة لإدخال المستخدم",+ "settingChat.selfIteration.enabled.desc": "Allow this assistant to review recent signals and improve its own skills when the lab workflow runs",+ "settingChat.selfIteration.enabled.title": "Enable Self-Iteration",+ "settingChat.selfIteration.title": "Advanced Labs","settingChat.submit": "تحديث تفضيلات الدردشة","settingChat.title": "إعدادات الدردشة","settingChatAppearance.autoScrollOnStreaming.desc": "التمرير تلقائيًا إلى الأسفل عند توليد الذكاء الاصطناعي للاستجابة",diff --git a/locales/bg-BG/setting.json b/locales/bg-BG/setting.jsonindex 0cd8357c88d..ba23cd5d056 100644--- a/locales/bg-BG/setting.json+++ b/locales/bg-BG/setting.json@@ -532,6 +532,9 @@"settingChat.inputTemplate.desc": "Последното съобщение на потребителя ще бъде вмъкнато в този шаблон","settingChat.inputTemplate.placeholder": "Шаблон за предварителна обработка {{text}} ще бъде заменен с реално въведена информация","settingChat.inputTemplate.title": "Предварителна обработка на входа",+ "settingChat.selfIteration.enabled.desc": "Allow this assistant to review recent signals and improve its own skills when the lab workflow runs",+ "settingChat.selfIteration.enabled.title": "Enable Self-Iteration",+ "settingChat.selfIteration.title": "Advanced Labs","settingChat.submit": "Актуализирай предпочитанията за чат","settingChat.title": "Настройки на чата","settingChatAppearance.autoScrollOnStreaming.desc": "Автоматично превъртане до дъното, когато ИИ генерира отговор",diff --git a/locales/de-DE/setting.json b/locales/de-DE/setting.jsonindex 39b2a015bbb..1b2083d66e9 100644--- a/locales/de-DE/setting.json+++ b/locales/de-DE/setting.json@@ -532,6 +532,9 @@"settingChat.inputTemplate.desc": "Die neueste Nachricht des Benutzers wird in diese Vorlage eingefügt","settingChat.inputTemplate.placeholder": "Vorverarbeitungsvorlage {{text}} wird durch Echtzeiteingabe ersetzt","settingChat.inputTemplate.title": "Benutzereingabe-Vorverarbeitung",+ "settingChat.selfIteration.enabled.desc": "Allow this assistant to review recent signals and improve its own skills when the lab workflow runs",+ "settingChat.selfIteration.enabled.title": "Enable Self-Iteration",+ "settingChat.selfIteration.title": "Advanced Labs","settingChat.submit": "Chat-Einstellungen aktualisieren","settingChat.title": "Chat-Einstellungen","settingChatAppearance.autoScrollOnStreaming.desc": "Automatisch nach unten scrollen, wenn die KI eine Antwort generiert",diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex 859ed216ead..92ca8921de9 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -532,6 +532,9 @@"settingChat.inputTemplate.desc": "The user's latest message will be filled into this template","settingChat.inputTemplate.placeholder": "Preprocessing template {{text}} will be replaced with real-time input information","settingChat.inputTemplate.title": "User Input Preprocessing",+ "settingChat.selfIteration.enabled.desc": "Allow this assistant to review recent signals and improve its own skills when the lab workflow runs",+ "settingChat.selfIteration.enabled.title": "Enable Self-Iteration",+ "settingChat.selfIteration.title": "Advanced Labs","settingChat.submit": "Update Chat Preferences","settingChat.title": "Chat Settings","settingChatAppearance.autoScrollOnStreaming.desc": "Automatically scroll to bottom when AI is generating response",diff --git a/locales/es-ES/setting.json b/locales/es-ES/setting.jsonindex 865b7edbc5d..64541b5ab3f 100644--- a/locales/es-ES/setting.json+++ b/locales/es-ES/setting.json@@ -532,6 +532,9 @@"settingChat.inputTemplate.desc": "El último mensaje del usuario se insertará en esta plantilla","settingChat.inputTemplate.placeholder": "La plantilla de preprocesamiento {{text}} se reemplazará con la entrada en tiempo real","settingChat.inputTemplate.title": "Preprocesamiento de Entrada del Usuario",+ "settingChat.selfIteration.enabled.desc": "Allow this assistant to review recent signals and improve its own skills when the lab workflow runs",+ "settingChat.selfIteration.enabled.title": "Enable Self-Iteration",+ "settingChat.selfIteration.title": "Advanced Labs","settingChat.submit": "Actualizar Preferencias de Chat","settingChat.title": "Configuración de Chat","settingChatAppearance.autoScrollOnStreaming.desc": "Desplazar automáticamente hacia abajo cuando la IA esté generando una respuesta",diff --git a/locales/fa-IR/setting.json b/locales/fa-IR/setting.jsonindex a8fea5932af..e5c3e9f0149 100644--- a/locales/fa-IR/setting.json+++ b/locales/fa-IR/setting.json@@ -532,6 +532,9 @@"settingChat.inputTemplate.desc": "آخرین پیام کاربر در این قالب قرار میگیرد","settingChat.inputTemplate.placeholder": "قالب پیشپردازش {{text}} با ورودی واقعی جایگزین میشود","settingChat.inputTemplate.title": "پیشپردازش ورودی کاربر",+ "settingChat.selfIteration.enabled.desc": "Allow this assistant to review recent signals and improve its own skills when the lab workflow runs",+ "settingChat.selfIteration.enabled.title": "Enable Self-Iteration",+ "settingChat.selfIteration.title": "Advanced Labs","settingChat.submit": "بهروزرسانی تنظیمات گفتگو","settingChat.title": "تنظیمات گفتگو","settingChatAppearance.autoScrollOnStreaming.desc": "پیمایش خودکار به پایین هنگام تولید پاسخ توسط هوش مصنوعی",diff --git a/locales/fr-FR/setting.json b/locales/fr-FR/setting.jsonindex 2d19c1a110a..45f1622fef9 100644--- a/locales/fr-FR/setting.json+++ b/locales/fr-FR/setting.json@@ -532,6 +532,9 @@"settingChat.inputTemplate.desc": "Le dernier message de l’utilisateur sera inséré dans ce modèle","settingChat.inputTemplate.placeholder": "Le modèle {{text}} sera remplacé par l’entrée en temps réel","settingChat.inputTemplate.title": "Prétraitement de l’entrée utilisateur",+ "settingChat.selfIteration.enabled.desc": "Allow this assistant to review recent signals and improve its own skills when the lab workflow runs",+ "settingChat.selfIteration.enabled.title": "Enable Self-Iteration",+ "settingChat.selfIteration.title": "Advanced Labs","settingChat.submit": "Mettre à jour les préférences de chat","settingChat.title": "Paramètres de chat","settingChatAppearance.autoScrollOnStreaming.desc": "Faire défiler automatiquement vers le bas lorsque l'IA génère une réponse",diff --git a/locales/it-IT/setting.json b/locales/it-IT/setting.jsonindex 6a9429b6faf..cfab9598ed5 100644--- a/locales/it-IT/setting.json+++ b/locales/it-IT/setting.json@@ -532,6 +532,9 @@"settingChat.inputTemplate.desc": "L'ultimo messaggio dell'utente verrà inserito in questo modello","settingChat.inputTemplate.placeholder": "Il modello di pre-elaborazione {{text}} sarà sostituito con l'input in tempo reale","settingChat.inputTemplate.title": "Pre-elaborazione Input Utente",+ "settingChat.selfIteration.enabled.desc": "Allow this assistant to review recent signals and improve its own skills when the lab workflow runs",+ "settingChat.selfIteration.enabled.title": "Enable Self-Iteration",+ "settingChat.selfIteration.title": "Advanced Labs","settingChat.submit": "Aggiorna Preferenze Chat","settingChat.title": "Impostazioni Chat","settingChatAppearance.autoScrollOnStreaming.desc": "Scorri automaticamente in fondo quando l'IA sta generando una risposta",diff --git a/locales/ja-JP/setting.json b/locales/ja-JP/setting.jsonindex e05813c0c62..a3e1e941061 100644--- a/locales/ja-JP/setting.json+++ b/locales/ja-JP/setting.json@@ -532,6 +532,9 @@"settingChat.inputTemplate.desc": "ユーザーの最新メッセージがこのテンプレートに埋め込まれます","settingChat.inputTemplate.placeholder": "入力テンプレート {{text}} はリアルタイムの入力情報に置き換えられます","settingChat.inputTemplate.title": "ユーザー入力のプリプロセス",+ "settingChat.selfIteration.enabled.desc": "Allow this assistant to review recent signals and improve its own skills when the lab workflow runs",+ "settingChat.selfIteration.enabled.title": "Enable Self-Iteration",+ "settingChat.selfIteration.title": "Advanced Labs","settingChat.submit": "チャットの好みを更新","settingChat.title": "チャット設定","settingChatAppearance.autoScrollOnStreaming.desc": "AIが応答を生成している間、自動的に最下部までスクロールします",diff --git a/locales/ko-KR/setting.json b/locales/ko-KR/setting.jsonindex 9febe84df3e..b69d3b079c8 100644--- a/locales/ko-KR/setting.json+++ b/locales/ko-KR/setting.json@@ -532,6 +532,9 @@"settingChat.inputTemplate.desc": "사용자의 최신 메시지가이 템플릿에 채워집니다","settingChat.inputTemplate.placeholder": "입력 템플릿 {{text}}은 실시간 입력 정보로 대체됩니다","settingChat.inputTemplate.title": "사용자 입력 전처리",+ "settingChat.selfIteration.enabled.desc": "Allow this assistant to review recent signals and improve its own skills when the lab workflow runs",+ "settingChat.selfIteration.enabled.title": "Enable Self-Iteration",+ "settingChat.selfIteration.title": "Advanced Labs","settingChat.submit": "채팅 선호도 업데이트","settingChat.title": "채팅 설정","settingChatAppearance.autoScrollOnStreaming.desc": "AI가 응답을 생성할 때 자동으로 맨 아래로 스크롤합니다",diff --git a/locales/nl-NL/setting.json b/locales/nl-NL/setting.jsonindex c9731b24fab..ee083ad4f2b 100644--- a/locales/nl-NL/setting.json+++ b/locales/nl-NL/setting.json@@ -532,6 +532,9 @@"settingChat.inputTemplate.desc": "Het laatste bericht van de gebruiker wordt in deze sjabloon geplaatst","settingChat.inputTemplate.placeholder": "Voorverwerkingssaboon {{text}} wordt vervangen door realtime invoer","settingChat.inputTemplate.title": "Voorverwerking gebruikersinvoer",+ "settingChat.selfIteration.enabled.desc": "Allow this assistant to review recent signals and improve its own skills when the lab workflow runs",+ "settingChat.selfIteration.enabled.title": "Enable Self-Iteration",+ "settingChat.selfIteration.title": "Advanced Labs","settingChat.submit": "Chatvoorkeuren bijwerken","settingChat.title": "Chatinstellingen","settingChatAppearance.autoScrollOnStreaming.desc": "Scroll automatisch naar beneden wanneer AI een reactie genereert",diff --git a/locales/pl-PL/setting.json b/locales/pl-PL/setting.jsonindex f2cfd4e823b..9488f5053f9 100644--- a/locales/pl-PL/setting.json+++ b/locales/pl-PL/setting.json@@ -532,6 +532,9 @@"settingChat.inputTemplate.desc": "Ostatnia wiadomość użytkownika zostanie wstawiona do tego szablonu","settingChat.inputTemplate.placeholder": "Szablon przetwarzania wstępnego {{text}} zostanie zastąpiony bieżącym wejściem","settingChat.inputTemplate.title": "Przetwarzanie wejścia użytkownika",+ "settingChat.selfIteration.enabled.desc": "Allow this assistant to review recent signals and improve its own skills when the lab workflow runs",+ "settingChat.selfIteration.enabled.title": "Enable Self-Iteration",+ "settingChat.selfIteration.title": "Advanced Labs","settingChat.submit": "Zaktualizuj preferencje czatu","settingChat.title": "Ustawienia czatu","settingChatAppearance.autoScrollOnStreaming.desc": "Automatycznie przewijaj do dołu, gdy AI generuje odpowiedź",diff --git a/locales/pt-BR/setting.json b/locales/pt-BR/setting.jsonindex 26a32107f8b..308d07292ce 100644--- a/locales/pt-BR/setting.json+++ b/locales/pt-BR/setting.json@@ -532,6 +532,9 @@"settingChat.inputTemplate.desc": "A última mensagem do usuário será inserida neste modelo","settingChat.inputTemplate.placeholder": "O modelo de pré-processamento {{text}} será substituído pela entrada em tempo real","settingChat.inputTemplate.title": "Pré-processamento da Entrada do Usuário",+ "settingChat.selfIteration.enabled.desc": "Allow this assistant to review recent signals and improve its own skills when the lab workflow runs",+ "settingChat.selfIteration.enabled.title": "Enable Self-Iteration",+ "settingChat.selfIteration.title": "Advanced Labs","settingChat.submit": "Atualizar Preferências de Chat","settingChat.title": "Configurações de Chat","settingChatAppearance.autoScrollOnStreaming.desc": "Rolar automaticamente até o final quando a IA estiver gerando uma resposta",diff --git a/locales/ru-RU/setting.json b/locales/ru-RU/setting.jsonindex 0bdfc87bb89..942aa028b74 100644--- a/locales/ru-RU/setting.json+++ b/locales/ru-RU/setting.json@@ -532,6 +532,9 @@"settingChat.inputTemplate.desc": "Последнее сообщение пользователя будет вставлено в этот шаблон","settingChat.inputTemplate.placeholder": "Шаблон предварительной обработки {{text}} будет заменён на ввод в реальном времени","settingChat.inputTemplate.title": "Предобработка ввода пользователя",+ "settingChat.selfIteration.enabled.desc": "Allow this assistant to review recent signals and improve its own skills when the lab workflow runs",+ "settingChat.selfIteration.enabled.title": "Enable Self-Iteration",+ "settingChat.selfIteration.title": "Advanced Labs","settingChat.submit": "Обновить настройки чата","settingChat.title": "Настройки чата","settingChatAppearance.autoScrollOnStreaming.desc": "Автоматически прокручивать вниз при генерации ответа ИИ",diff --git a/locales/tr-TR/setting.json b/locales/tr-TR/setting.jsonindex 3970d20cdd6..8a394c3d0ff 100644--- a/locales/tr-TR/setting.json+++ b/locales/tr-TR/setting.json@@ -532,6 +532,9 @@"settingChat.inputTemplate.desc": "Kullanıcının son mesajı bu şablona yerleştirilecektir","settingChat.inputTemplate.placeholder": "Ön işleme şablonu {{text}} gerçek zamanlı girişle değiştirilecektir","settingChat.inputTemplate.title": "Kullanıcı Girişi Ön İşleme",+ "settingChat.selfIteration.enabled.desc": "Allow this assistant to review recent signals and improve its own skills when the lab workflow runs",+ "settingChat.selfIteration.enabled.title": "Enable Self-Iteration",+ "settingChat.selfIteration.title": "Advanced Labs","settingChat.submit": "Sohbet Tercihlerini Güncelle","settingChat.title": "Sohbet Ayarları","settingChatAppearance.autoScrollOnStreaming.desc": "Yapay zeka yanıt oluştururken otomatik olarak en alta kaydır",diff --git a/locales/vi-VN/setting.json b/locales/vi-VN/setting.jsonindex 795e0f710da..e79791332b4 100644--- a/locales/vi-VN/setting.json+++ b/locales/vi-VN/setting.json@@ -532,6 +532,9 @@"settingChat.inputTemplate.desc": "Tin nhắn mới nhất của người dùng sẽ được chèn vào mẫu này","settingChat.inputTemplate.placeholder": "Mẫu tiền xử lý {{text}} sẽ được thay thế bằng thông tin nhập thời gian thực","settingChat.inputTemplate.title": "Tiền xử lý đầu vào người dùng",+ "settingChat.selfIteration.enabled.desc": "Allow this assistant to review recent signals and improve its own skills when the lab workflow runs",+ "settingChat.selfIteration.enabled.title": "Enable Self-Iteration",+ "settingChat.selfIteration.title": "Advanced Labs","settingChat.submit": "Cập nhật tùy chọn trò chuyện","settingChat.title": "Cài đặt trò chuyện","settingChatAppearance.autoScrollOnStreaming.desc": "Tự động cuộn xuống cuối khi AI đang tạo phản hồi",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex 5c472cb4663..0fc3ed2dd3f 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -532,6 +532,9 @@"settingChat.inputTemplate.desc": "用户最新的一条消息会填充到此模板","settingChat.inputTemplate.placeholder": "预处理模版 {{text}} 将替换为实时输入信息","settingChat.inputTemplate.title": "用户输入预处理",+ "settingChat.selfIteration.enabled.desc": "允许该助手在实验性工作流运行时回顾近期信号并改进自己的技能",+ "settingChat.selfIteration.enabled.title": "启用自迭代",+ "settingChat.selfIteration.title": "高级实验","settingChat.submit": "更新聊天偏好","settingChat.title": "聊天设置","settingChatAppearance.autoScrollOnStreaming.desc": "当 AI 正在生成回复时,自动滚动到底部",diff --git a/locales/zh-TW/setting.json b/locales/zh-TW/setting.jsonindex 7a41bb86fc5..c801446fc69 100644--- a/locales/zh-TW/setting.json+++ b/locales/zh-TW/setting.json@@ -532,6 +532,9 @@"settingChat.inputTemplate.desc": "使用者最新的一條訊息會填充到此模板","settingChat.inputTemplate.placeholder": "預處理模板 {{text}} 將替換為實時輸入資訊","settingChat.inputTemplate.title": "使用者輸入預處理",+ "settingChat.selfIteration.enabled.desc": "允許該助手在實驗性工作流程執行時回顧近期訊號並改進自己的技能",+ "settingChat.selfIteration.enabled.title": "啟用自我迭代",+ "settingChat.selfIteration.title": "進階實驗","settingChat.submit": "更新聊天偏好","settingChat.title": "聊天設定","settingChatAppearance.autoScrollOnStreaming.desc": "當 AI 產生回應時自動捲動至底部",diff --git a/package.json b/package.jsonindex baf73d81c85..43057121f05 100644--- a/package.json+++ b/package.json@@ -228,6 +228,7 @@"@lobechat/builtin-tool-notebook": "workspace:*","@lobechat/builtin-tool-page-agent": "workspace:*","@lobechat/builtin-tool-remote-device": "workspace:*",+ "@lobechat/builtin-tool-self-iteration": "workspace:*","@lobechat/builtin-tool-skill-maintainer": "workspace:*","@lobechat/builtin-tool-skill-store": "workspace:*","@lobechat/builtin-tool-skills": "workspace:*",diff --git a/packages/agent-signal/src/source/scopeKey.ts b/packages/agent-signal/src/source/scopeKey.tsindex d59901e4299..72e7d37a980 100644--- a/packages/agent-signal/src/source/scopeKey.ts+++ b/packages/agent-signal/src/source/scopeKey.ts@@ -16,14 +16,20 @@ export interface AgentSignalBotScopeKeyInput {* Producer metadata used to derive a stable source-event scope key.*/export interface AgentSignalProducerScopeInput {+ /** Optional assistant or agent identifier for broad agent-user scoped events. */+ agentId?: string;/** Optional external application identifier for bot-originated events. */applicationId?: string;/** Optional external platform identifier for bot-originated events. */platform?: string;/** Optional external thread identifier for bot-originated events. */platformThreadId?: string;- /** Optional LobeChat topic identifier. Takes precedence over bot-thread metadata. */+ /** Optional task identifier. Used when no topic is available. */+ taskId?: string;+ /** Optional LobeChat topic identifier. Takes precedence over task and bot-thread metadata. */topicId?: string;+ /** Optional user identifier for broad authenticated scopes. */+ userId?: string;}/**@@ -91,6 +97,7 @@ export const AgentSignalScopeKey = {forUser: (input: AgentSignalUserScopeKeyInput) => joinScopeKey('user', input.userId),fromProducerInput: (input: AgentSignalProducerScopeInput) => {if (input.topicId) return AgentSignalScopeKey.forTopic({ topicId: input.topicId });+ if (input.taskId) return AgentSignalScopeKey.forTask({ taskId: input.taskId });if (input.platform && input.applicationId && input.platformThreadId) {return AgentSignalScopeKey.forBotThread({@@ -100,6 +107,12 @@ export const AgentSignalScopeKey = {});}+ if (input.agentId && input.userId) {+ return AgentSignalScopeKey.forAgentUser({ agentId: input.agentId, userId: input.userId });+ }++ if (input.userId) return AgentSignalScopeKey.forUser({ userId: input.userId });+return 'fallback:global';},fromRuntimeScope: (scope: AgentSignalScope) => {@@ -125,9 +138,12 @@ export const AgentSignalScopeKey = {*/export const getSourceEventScopeKey = (input: Record<string, unknown>) => {return AgentSignalScopeKey.fromProducerInput({+ agentId: pickString(input, 'agentId'),applicationId: pickString(input, 'applicationId'),platform: pickString(input, 'platform'),platformThreadId: pickString(input, 'platformThreadId'),+ taskId: pickString(input, 'taskId'),topicId: pickString(input, 'topicId'),+ userId: pickString(input, 'userId'),});};diff --git a/packages/agent-signal/src/source/sourceEvent.test.ts b/packages/agent-signal/src/source/sourceEvent.test.tsindex c4e7eeb9dd6..7494545b475 100644--- a/packages/agent-signal/src/source/sourceEvent.test.ts+++ b/packages/agent-signal/src/source/sourceEvent.test.ts@@ -1,6 +1,16 @@import { describe, expect, it } from 'vitest';-import { AGENT_SIGNAL_SOURCE_TYPES, createSourceEvent, getSourceEventScopeKey } from './index';+import {+ AGENT_SIGNAL_SOURCE_TYPES,+ createSourceEvent,+ getSourceEventScopeKey,+ isAgentUserMessageSource,+ isClientRuntimeStartSource,+ isNightlyReviewSource,+ isSelfIterationIntentSource,+ isSelfReflectionSource,+ isToolOutcomeSource,+} from './index';describe('AgentSignal source events', () => {/**@@ -49,4 +59,180 @@ describe('AgentSignal source events', () => {}),).toBe('topic:topic-1');});++ /**+ * @example+ * createSourceEvent({ sourceType: 'agent.nightly_review.requested', sourceId, payload })+ * returns an agent-user scoped nightly review event.+ */+ it('creates a nightly review event with explicit agent-user scope', () => {+ const event = createSourceEvent({+ payload: {+ agentId: 'agent-1',+ localDate: '2026-05-04',+ requestedAt: '2026-05-04T14:30:00.000Z',+ reviewWindowEnd: '2026-05-04T14:30:00.000Z',+ reviewWindowStart: '2026-05-03T16:00:00.000Z',+ timezone: 'Asia/Shanghai',+ userId: 'user-1',+ },+ sourceId: 'nightly-review:user-1:agent-1:2026-05-04',+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentNightlyReviewRequested,+ timestamp: 123,+ });++ expect(event).toEqual({+ payload: {+ agentId: 'agent-1',+ localDate: '2026-05-04',+ requestedAt: '2026-05-04T14:30:00.000Z',+ reviewWindowEnd: '2026-05-04T14:30:00.000Z',+ reviewWindowStart: '2026-05-03T16:00:00.000Z',+ timezone: 'Asia/Shanghai',+ userId: 'user-1',+ },+ scopeKey: 'agent:agent-1:user:user-1',+ sourceId: 'nightly-review:user-1:agent-1:2026-05-04',+ sourceType: 'agent.nightly_review.requested',+ timestamp: 123,+ });+ });++ /**+ * @example+ * getSourceEventScopeKey({ taskId: 'task-1' }) returns 'task:task-1'.+ */+ it('derives task scope for self-reflection payloads before agent-user fallback', () => {+ const event = createSourceEvent({+ payload: {+ agentId: 'agent-1',+ reason: 'failed_tool_count',+ scopeId: 'task-1',+ scopeType: 'task',+ taskId: 'task-1',+ userId: 'user-1',+ windowEnd: '2026-05-04T14:30:00.000Z',+ windowStart: '2026-05-04T14:00:00.000Z',+ },+ sourceId:+ 'self-reflection:user-1:agent-1:task:task-1:failed_tool_count:2026-05-04T14:00:00.000Z:2026-05-04T14:30:00.000Z',+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentSelfReflectionRequested,+ timestamp: 456,+ });++ expect(event.scopeKey).toBe('task:task-1');+ expect(event.sourceType).toBe('agent.self_reflection.requested');+ });++ /**+ * @example+ * createSourceEvent({ sourceType: 'agent.self_iteration_intent.declared', sourceId, payload })+ * returns a topic scoped tool-declared source event.+ */+ it('creates a self-iteration intent event in the current topic scope', () => {+ const event = createSourceEvent({+ payload: {+ action: 'refine',+ agentId: 'agent-1',+ confidence: 0.92,+ kind: 'skill',+ reason: 'The running agent noticed a reusable workflow correction.',+ summary: 'Refine the release note skill with the corrected checklist.',+ toolCallId: 'tool-call-1',+ topicId: 'topic-1',+ userId: 'user-1',+ },+ sourceId: 'self-iteration-intent:user-1:agent-1:topic:topic-1:tool-call-1',+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentSelfIterationIntentDeclared,+ timestamp: 789,+ });++ expect(event.scopeKey).toBe('topic:topic-1');+ expect(event.sourceType).toBe('agent.self_iteration_intent.declared');+ });++ /**+ * @example+ * isToolOutcomeSource(createSourceEvent({ sourceType: 'tool.outcome.failed', ... })) returns true.+ */+ it('narrows source events with source package guards', () => {+ const clientRuntimeStart = createSourceEvent({+ payload: {+ operationId: 'operation-1',+ parentMessageId: 'message-1',+ parentMessageType: 'user',+ },+ sourceId: 'source-client-runtime-start',+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeStart,+ timestamp: 123,+ });+ const agentUserMessage = createSourceEvent({+ payload: {+ message: 'hello',+ messageId: 'message-1',+ },+ sourceId: 'source-agent-user-message',+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentUserMessage,+ timestamp: 123,+ });+ const nightlyReview = createSourceEvent({+ payload: {+ agentId: 'agent-1',+ localDate: '2026-05-04',+ requestedAt: '2026-05-04T14:30:00.000Z',+ reviewWindowEnd: '2026-05-04T14:30:00.000Z',+ reviewWindowStart: '2026-05-03T16:00:00.000Z',+ timezone: 'Asia/Shanghai',+ userId: 'user-1',+ },+ sourceId: 'nightly-review:user-1:agent-1:2026-05-04',+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentNightlyReviewRequested,+ timestamp: 123,+ });+ const selfReflection = createSourceEvent({+ payload: {+ agentId: 'agent-1',+ reason: 'failed_tool_count',+ scopeId: 'task-1',+ scopeType: 'task',+ userId: 'user-1',+ windowEnd: '2026-05-04T14:30:00.000Z',+ windowStart: '2026-05-04T14:00:00.000Z',+ },+ sourceId: 'self-reflection:user-1:agent-1:task:task-1:failed_tool_count:start:end',+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentSelfReflectionRequested,+ timestamp: 123,+ });+ const selfIterationIntent = createSourceEvent({+ payload: {+ action: 'refine',+ agentId: 'agent-1',+ confidence: 0.92,+ kind: 'skill',+ reason: 'Reusable correction.',+ summary: 'Refine skill.',+ userId: 'user-1',+ },+ sourceId: 'self-iteration-intent:user-1:agent-1:topic:topic-1:tool-call-1',+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentSelfIterationIntentDeclared,+ timestamp: 123,+ });+ const failedToolOutcome = createSourceEvent({+ payload: {+ outcome: { status: 'failed' },+ tool: { identifier: 'tool-1' },+ },+ sourceId: 'source-tool-outcome-failed',+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.toolOutcomeFailed,+ timestamp: 123,+ });++ expect(isClientRuntimeStartSource(clientRuntimeStart)).toBe(true);+ expect(isAgentUserMessageSource(agentUserMessage)).toBe(true);+ expect(isNightlyReviewSource(nightlyReview)).toBe(true);+ expect(isSelfReflectionSource(selfReflection)).toBe(true);+ expect(isSelfIterationIntentSource(selfIterationIntent)).toBe(true);+ expect(isToolOutcomeSource(failedToolOutcome)).toBe(true);+ expect(isToolOutcomeSource(agentUserMessage)).toBe(false);+ });});diff --git a/packages/agent-signal/src/source/sourceTypes.ts b/packages/agent-signal/src/source/sourceTypes.tsindex b2f45c4cb0e..3f691e0a1d2 100644--- a/packages/agent-signal/src/source/sourceTypes.ts+++ b/packages/agent-signal/src/source/sourceTypes.ts@@ -1,9 +1,13 @@import type { AgentSignalSource, BaseSource } from '../base/types';+import type { AgentSignalSourceEvent } from './sourceEvent';/** AgentSignal source type identifiers shared by browser producers and server executors. */export const AGENT_SIGNAL_SOURCE_TYPES = {agentExecutionCompleted: 'agent.execution.completed',agentExecutionFailed: 'agent.execution.failed',+ agentNightlyReviewRequested: 'agent.nightly_review.requested',+ agentSelfIterationIntentDeclared: 'agent.self_iteration_intent.declared',+ agentSelfReflectionRequested: 'agent.self_reflection.requested',agentUserMessage: 'agent.user.message',botMessageMerged: 'bot.message.merged',clientGatewayError: 'client.gateway.error',@@ -42,6 +46,42 @@ export interface AgentSignalSourcePayloadMap {topicId?: string;turnCount?: number;};+ [AGENT_SIGNAL_SOURCE_TYPES.agentNightlyReviewRequested]: {+ agentId: string;+ localDate: string;+ requestedAt: string;+ reviewWindowEnd: string;+ reviewWindowStart: string;+ timezone: string;+ userId: string;+ };+ [AGENT_SIGNAL_SOURCE_TYPES.agentSelfIterationIntentDeclared]: {+ action: 'write' | 'create' | 'refine' | 'consolidate' | 'proposal';+ agentId: string;+ confidence: number;+ evidenceRefs?: Array<{ id: string; summary?: string; type: string }>;+ kind: 'memory' | 'skill' | 'gap';+ memoryId?: string;+ operationId?: string;+ reason: string;+ skillId?: string;+ summary: string;+ toolCallId?: string;+ topicId?: string;+ userId: string;+ };+ [AGENT_SIGNAL_SOURCE_TYPES.agentSelfReflectionRequested]: {+ agentId: string;+ operationId?: string;+ reason: string;+ scopeId: string;+ scopeType: 'topic' | 'task' | 'operation';+ taskId?: string;+ topicId?: string;+ userId: string;+ windowEnd: string;+ windowStart: string;+ };[AGENT_SIGNAL_SOURCE_TYPES.agentUserMessage]: {agentId?: string;documentPayload?: Record<string, unknown>;@@ -186,6 +226,18 @@ export type SourceAgentExecutionCompleted = AgentSignalSourceVariant<'agent.exec/** Agent execution-failed source variant. */export type SourceAgentExecutionFailed = AgentSignalSourceVariant<'agent.execution.failed'>;+/** Agent nightly-review requested source variant. */+export type SourceAgentNightlyReviewRequested =+ AgentSignalSourceVariant<'agent.nightly_review.requested'>;++/** Agent self-reflection requested source variant. */+export type SourceAgentSelfReflectionRequested =+ AgentSignalSourceVariant<'agent.self_reflection.requested'>;++/** Agent-declared self-iteration intent source variant. */+export type SourceAgentSelfIterationIntentDeclared =+ AgentSignalSourceVariant<'agent.self_iteration_intent.declared'>;+/** Runtime before-step source variant. */export type SourceRuntimeBeforeStep = AgentSignalSourceVariant<'runtime.before_step'>;@@ -221,6 +273,29 @@ export type SourceToolOutcomeCompleted = AgentSignalSourceVariant<'tool.outcome./** Tool outcome-failed source variant. */export type SourceToolOutcomeFailed = AgentSignalSourceVariant<'tool.outcome.failed'>;+/** Normalized client runtime-start source event. */+export type SourceEventClientRuntimeStart = AgentSignalSourceEvent<'client.runtime.start'>;++/** Normalized agent user-message source event. */+export type SourceEventAgentUserMessage = AgentSignalSourceEvent<'agent.user.message'>;++/** Normalized agent nightly-review requested source event. */+export type SourceEventAgentNightlyReviewRequested =+ AgentSignalSourceEvent<'agent.nightly_review.requested'>;++/** Normalized agent self-reflection requested source event. */+export type SourceEventAgentSelfReflectionRequested =+ AgentSignalSourceEvent<'agent.self_reflection.requested'>;++/** Normalized agent-declared self-iteration intent source event. */+export type SourceEventAgentSelfIterationIntentDeclared =+ AgentSignalSourceEvent<'agent.self_iteration_intent.declared'>;++/** Normalized tool outcome source event. */+export type SourceEventToolOutcome =+ | AgentSignalSourceEvent<'tool.outcome.completed'>+ | AgentSignalSourceEvent<'tool.outcome.failed'>;+/** Source types accepted by browser producers through the authenticated edge. */export const AGENT_SIGNAL_CLIENT_SOURCE_TYPES = [AGENT_SIGNAL_SOURCE_TYPES.clientGatewayError,@@ -251,3 +326,128 @@ export const isAgentSignalKnownSource = (source.sourceType as AgentSignalSourceType,);};++/**+ * Narrows a source event or source variant to `client.runtime.start`.+ *+ * Use when:+ * - Workflow ingress needs to bridge client runtime starts into server-owned sources+ * - Callers need source-type-specific payload typing+ *+ * Expects:+ * - `source.sourceType` follows the AgentSignal source catalog+ *+ * Returns:+ * - Whether the source is a client runtime-start source+ */+export function isClientRuntimeStartSource(+ source: AgentSignalSourceEvent,+): source is SourceEventClientRuntimeStart;+export function isClientRuntimeStartSource(+ source: AgentSignalSourceVariants,+): source is SourceClientRuntimeStart;+export function isClientRuntimeStartSource(+ source: AgentSignalSourceEvent | AgentSignalSourceVariants,+) {+ return source.sourceType === AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeStart;+}++/**+ * Narrows a source event or source variant to `agent.user.message`.+ *+ * Use when:+ * - Feedback classifiers only process direct user-message sources+ * - Workflow normalization needs user-message payload typing+ *+ * Expects:+ * - `source.sourceType` follows the AgentSignal source catalog+ *+ * Returns:+ * - Whether the source is an agent user-message source+ */+export function isAgentUserMessageSource(+ source: AgentSignalSourceEvent,+): source is SourceEventAgentUserMessage;+export function isAgentUserMessageSource(+ source: AgentSignalSourceVariants,+): source is SourceAgentUserMessage;+export function isAgentUserMessageSource(+ source: AgentSignalSourceEvent | AgentSignalSourceVariants,+) {+ return source.sourceType === AGENT_SIGNAL_SOURCE_TYPES.agentUserMessage;+}++/**+ * Narrows a source event to `agent.nightly_review.requested`.+ *+ * Use when:+ * - Workflow policy composition needs nightly-review dependencies only for nightly sources+ *+ * Expects:+ * - `source.sourceType` follows the AgentSignal source catalog+ *+ * Returns:+ * - Whether the source is a nightly-review request source+ */+export const isNightlyReviewSource = (+ source: AgentSignalSourceEvent,+): source is SourceEventAgentNightlyReviewRequested => {+ return source.sourceType === AGENT_SIGNAL_SOURCE_TYPES.agentNightlyReviewRequested;+};++/**+ * Narrows a source event to `agent.self_reflection.requested`.+ *+ * Use when:+ * - Workflow policy composition needs self-reflection dependencies only for reflection sources+ *+ * Expects:+ * - `source.sourceType` follows the AgentSignal source catalog+ *+ * Returns:+ * - Whether the source is a self-reflection request source+ */+export const isSelfReflectionSource = (+ source: AgentSignalSourceEvent,+): source is SourceEventAgentSelfReflectionRequested => {+ return source.sourceType === AGENT_SIGNAL_SOURCE_TYPES.agentSelfReflectionRequested;+};++/**+ * Narrows a source event to `agent.self_iteration_intent.declared`.+ *+ * Use when:+ * - Workflow policy composition needs self-iteration intent dependencies only for declared intents+ *+ * Expects:+ * - `source.sourceType` follows the AgentSignal source catalog+ *+ * Returns:+ * - Whether the source is an agent-declared self-iteration intent source+ */+export const isSelfIterationIntentSource = (+ source: AgentSignalSourceEvent,+): source is SourceEventAgentSelfIterationIntentDeclared => {+ return source.sourceType === AGENT_SIGNAL_SOURCE_TYPES.agentSelfIterationIntentDeclared;+};++/**+ * Narrows a source event to tool outcome sources.+ *+ * Use when:+ * - Workflow policy composition needs procedure dependencies for completed or failed tool outcomes+ *+ * Expects:+ * - `source.sourceType` follows the AgentSignal source catalog+ *+ * Returns:+ * - Whether the source is a completed or failed tool outcome source+ */+export const isToolOutcomeSource = (+ source: AgentSignalSourceEvent,+): source is SourceEventToolOutcome => {+ return (+ source.sourceType === AGENT_SIGNAL_SOURCE_TYPES.toolOutcomeCompleted ||+ source.sourceType === AGENT_SIGNAL_SOURCE_TYPES.toolOutcomeFailed+ );+};diff --git a/packages/builtin-tool-self-iteration/package.json b/packages/builtin-tool-self-iteration/package.jsonnew file mode 100644index 00000000000..657b4b55625--- /dev/null+++ b/packages/builtin-tool-self-iteration/package.json@@ -0,0 +1,14 @@+{+ "name": "@lobechat/builtin-tool-self-iteration",+ "version": "1.0.0",+ "private": true,+ "type": "module",+ "exports": {+ ".": "./src/index.ts"+ },+ "main": "./src/index.ts",+ "devDependencies": {+ "@lobechat/context-engine": "workspace:*",+ "@lobechat/types": "workspace:*"+ }+}diff --git a/packages/builtin-tool-self-iteration/src/index.test.ts b/packages/builtin-tool-self-iteration/src/index.test.tsnew file mode 100644index 00000000000..29948ab9ca7--- /dev/null+++ b/packages/builtin-tool-self-iteration/src/index.test.ts@@ -0,0 +1,158 @@+import type { LobeToolManifest, OperationToolSet, ToolSource } from '@lobechat/context-engine';+import { describe, expect, it } from 'vitest';++import {+ injectSelfIterationIntentTool,+ SELF_ITERATION_INTENT_API_NAME,+ SELF_ITERATION_INTENT_IDENTIFIER,+ SELF_ITERATION_INTENT_TOOL_NAME,+ selfIterationIntentManifest,+ shouldExposeSelfIterationIntentTool,+} from './index';++interface ToolSetParts {+ enabledToolIds: string[];+ manifestMap: Record<string, LobeToolManifest>;+ sourceMap: Record<string, ToolSource>;+ tools: OperationToolSet['tools'];+}++const createToolSetParts = (): ToolSetParts => ({+ enabledToolIds: [],+ manifestMap: {},+ sourceMap: {},+ tools: [],+});++describe('selfIterationIntentTool', () => {+ describe('shouldExposeSelfIterationIntentTool', () => {+ /**+ * @example+ * Runtime injection is visible only when the feature/user and agent-level gates pass.+ */+ it('is visible only when all gates pass', () => {+ expect(+ shouldExposeSelfIterationIntentTool({+ agentSelfIterationEnabled: true,+ featureUserEnabled: true,+ }),+ ).toBe(true);++ expect(+ shouldExposeSelfIterationIntentTool({+ agentSelfIterationEnabled: false,+ featureUserEnabled: true,+ }),+ ).toBe(false);+ expect(+ shouldExposeSelfIterationIntentTool({+ agentSelfIterationEnabled: true,+ featureUserEnabled: false,+ }),+ ).toBe(false);+ });++ /**+ * @example+ * Explicit disable flags hide the tool from reviewer or no-tool runtime paths.+ */+ it('is hidden when disabled or reviewer role is set', () => {+ expect(+ shouldExposeSelfIterationIntentTool({+ agentSelfIterationEnabled: true,+ disabled: true,+ featureUserEnabled: true,+ }),+ ).toBe(false);+ expect(+ shouldExposeSelfIterationIntentTool({+ agentSelfIterationEnabled: true,+ disableSelfIterationIntentTool: true,+ featureUserEnabled: true,+ }),+ ).toBe(false);+ expect(+ shouldExposeSelfIterationIntentTool({+ agentSelfIterationEnabled: true,+ featureUserEnabled: true,+ reviewerRole: true,+ }),+ ).toBe(false);+ });+ });++ describe('selfIterationIntentManifest', () => {+ /**+ * @example+ * The declaration schema exposes every field accepted by DeclareSelfIterationIntentPayload.+ */+ it('declares the expected input schema fields', () => {+ const api = selfIterationIntentManifest.api[0];+ const properties = api.parameters.properties;++ expect(selfIterationIntentManifest.identifier).toBe(SELF_ITERATION_INTENT_IDENTIFIER);+ expect(api.name).toBe(SELF_ITERATION_INTENT_API_NAME);+ expect(Object.keys(properties)).toEqual([+ 'action',+ 'kind',+ 'confidence',+ 'summary',+ 'reason',+ 'evidenceRefs',+ 'memoryId',+ 'skillId',+ ]);+ expect(api.description).toContain('does not mutate memory or skills');+ expect(api.parameters.required).toEqual([+ 'action',+ 'kind',+ 'confidence',+ 'summary',+ 'reason',+ ]);+ });+ });++ describe('injectSelfIterationIntentTool', () => {+ /**+ * @example+ * The helper injects a builtin manifest, generated LLM tool, and enabled id.+ */+ it('injects the builtin tool parts with the generated tool name', () => {+ const toolSetParts = createToolSetParts();++ const injected = injectSelfIterationIntentTool(toolSetParts);++ expect(injected).toBe(true);+ expect(toolSetParts.enabledToolIds).toContain(SELF_ITERATION_INTENT_IDENTIFIER);+ expect(toolSetParts.sourceMap[SELF_ITERATION_INTENT_IDENTIFIER]).toBe('builtin');+ expect(toolSetParts.manifestMap[SELF_ITERATION_INTENT_IDENTIFIER]).toBe(+ selfIterationIntentManifest,+ );+ expect(toolSetParts.tools).toContainEqual(+ expect.objectContaining({+ function: expect.objectContaining({ name: SELF_ITERATION_INTENT_TOOL_NAME }),+ type: 'function',+ }),+ );+ });++ /**+ * @example+ * Calling injection twice keeps one enabled id and one LLM-visible function.+ */+ it('does not duplicate tool parts when called twice', () => {+ const toolSetParts = createToolSetParts();++ expect(injectSelfIterationIntentTool(toolSetParts)).toBe(true);+ expect(injectSelfIterationIntentTool(toolSetParts)).toBe(false);++ expect(+ toolSetParts.enabledToolIds.filter((id) => id === SELF_ITERATION_INTENT_IDENTIFIER),+ ).toHaveLength(1);+ expect(+ toolSetParts.tools.filter((tool) => tool.function.name === SELF_ITERATION_INTENT_TOOL_NAME),+ ).toHaveLength(1);+ });+ });+});diff --git a/packages/builtin-tool-self-iteration/src/index.ts b/packages/builtin-tool-self-iteration/src/index.tsnew file mode 100644index 00000000000..b0328748ca3--- /dev/null+++ b/packages/builtin-tool-self-iteration/src/index.ts@@ -0,0 +1,12 @@+export {+ injectSelfIterationIntentTool,+ type SelfIterationIntentToolSetParts,+ shouldExposeSelfIterationIntentTool,+} from './inject';+export { selfIterationIntentManifest } from './manifest';+export {+ SELF_ITERATION_INTENT_API_NAME,+ SELF_ITERATION_INTENT_IDENTIFIER,+ SELF_ITERATION_INTENT_TOOL_NAME,+ type ShouldExposeSelfIterationIntentToolOptions,+} from './types';diff --git a/packages/builtin-tool-self-iteration/src/inject.ts b/packages/builtin-tool-self-iteration/src/inject.tsnew file mode 100644index 00000000000..4852167bdf9--- /dev/null+++ b/packages/builtin-tool-self-iteration/src/inject.ts@@ -0,0 +1,84 @@+import type { LobeToolManifest, OperationToolSet, ToolSource } from '@lobechat/context-engine';++import { selfIterationIntentManifest } from './manifest';+import type { ShouldExposeSelfIterationIntentToolOptions } from './types';+import { SELF_ITERATION_INTENT_IDENTIFIER, SELF_ITERATION_INTENT_TOOL_NAME } from './types';++/** Mutable operation tool-set parts that can receive the injected builtin tool. */+export interface SelfIterationIntentToolSetParts {+ /** Enabled tool identifiers persisted with the operation. */+ enabledToolIds: string[];+ /** Manifest map persisted with the operation. */+ manifestMap: Record<string, LobeToolManifest>;+ /** Source map persisted with the operation. */+ sourceMap: Record<string, ToolSource>;+ /** LLM-visible function tools for the operation. */+ tools: OperationToolSet['tools'];+}++const createSelfIterationIntentTool = () =>+ selfIterationIntentManifest.api.map((api) => ({+ function: {+ description: api.description,+ name: SELF_ITERATION_INTENT_TOOL_NAME,+ parameters: api.parameters,+ },+ type: 'function' as const,+ }));++/**+ * Decides whether the self-iteration intent declaration tool should be visible.+ *+ * Use when:+ * - Tests need a pure visibility predicate+ * - Runtime injection needs to combine feature, agent, and caller gates+ *+ * Expects:+ * - `featureUserEnabled` already includes server/user Labs eligibility+ *+ * Returns:+ * - `true` only for ordinary running agents with all gates enabled+ */+export const shouldExposeSelfIterationIntentTool = (+ options: ShouldExposeSelfIterationIntentToolOptions,+) => {+ if (!options.featureUserEnabled || !options.agentSelfIterationEnabled) return false;+ if (options.disabled || options.disableSelfIterationIntentTool || options.reviewerRole) {+ return false;+ }++ return true;+};++/**+ * Injects the self-iteration intent manifest and LLM tool into a tool set.+ *+ * Use when:+ * - `execAgent` has already built the normal model/tool path+ * - The operation should expose advisory self-iteration intent as a builtin server tool+ *+ * Expects:+ * - Caller has already checked visibility gates+ *+ * Returns:+ * - `true` when this call added the tool, otherwise `false` when it was already present+ */+export const injectSelfIterationIntentTool = (toolSetParts: SelfIterationIntentToolSetParts) => {+ const wasAlreadyEnabled = toolSetParts.enabledToolIds.includes(SELF_ITERATION_INTENT_IDENTIFIER);+ const wasAlreadyVisible = toolSetParts.tools.some(+ (tool) => tool.function.name === SELF_ITERATION_INTENT_TOOL_NAME,+ );++ toolSetParts.manifestMap[SELF_ITERATION_INTENT_IDENTIFIER] = selfIterationIntentManifest;+ toolSetParts.sourceMap[SELF_ITERATION_INTENT_IDENTIFIER] = 'builtin';++ if (!wasAlreadyEnabled) {+ toolSetParts.enabledToolIds.push(SELF_ITERATION_INTENT_IDENTIFIER);+ }++ if (!wasAlreadyVisible) {+ toolSetParts.tools.push(...createSelfIterationIntentTool());+ }++ return !wasAlreadyEnabled || !wasAlreadyVisible;+};diff --git a/packages/builtin-tool-self-iteration/src/manifest.ts b/packages/builtin-tool-self-iteration/src/manifest.tsnew file mode 100644index 00000000000..f622913c741--- /dev/null+++ b/packages/builtin-tool-self-iteration/src/manifest.ts@@ -0,0 +1,91 @@+import type { BuiltinToolManifest } from '@lobechat/types';++import { SELF_ITERATION_INTENT_API_NAME, SELF_ITERATION_INTENT_IDENTIFIER } from './types';++/**+ * Self-iteration intent builtin tool manifest.+ *+ * Use when:+ * - A running agent may declare advisory maintenance intent+ * - The runtime must expose a source-event boundary without direct resource mutation+ *+ * Expects:+ * - Downstream handlers own all memory and skill review or mutation decisions+ *+ * Returns:+ * - A manifest that can be registered as a hidden builtin tool+ */+export const selfIterationIntentManifest = {+ api: [+ {+ description:+ 'Declare advisory maintenance intent for future review. This only records intent and does not mutate memory or skills.',+ name: SELF_ITERATION_INTENT_API_NAME,+ parameters: {+ additionalProperties: false,+ properties: {+ action: {+ description: 'Maintenance action the agent believes may be useful.',+ enum: ['write', 'create', 'refine', 'consolidate', 'proposal'],+ type: 'string',+ },+ kind: {+ description: 'Maintenance target category for the declaration.',+ enum: ['memory', 'skill', 'gap'],+ type: 'string',+ },+ confidence: {+ description: 'Agent confidence from 0 to 1.',+ maximum: 1,+ minimum: 0,+ type: 'number',+ },+ summary: {+ description: 'Short summary of the maintenance intent.',+ type: 'string',+ },+ reason: {+ description: 'Rationale for why this maintenance intent may be useful.',+ type: 'string',+ },+ evidenceRefs: {+ description: 'Optional references that justify the declaration.',+ items: {+ additionalProperties: false,+ properties: {+ id: { description: 'Stable evidence identifier.', type: 'string' },+ type: {+ description: 'Evidence object type.',+ enum: ['message', 'tool_call', 'receipt', 'document', 'custom'],+ type: 'string',+ },+ },+ required: ['id', 'type'],+ type: 'object',+ },+ type: 'array',+ },+ memoryId: {+ description: 'Existing memory id when the declaration targets a known memory.',+ type: 'string',+ },+ skillId: {+ description: 'Existing skill id when the declaration targets a known skill.',+ type: 'string',+ },+ },+ required: ['action', 'kind', 'confidence', 'summary', 'reason'],+ type: 'object',+ },+ },+ ],+ identifier: SELF_ITERATION_INTENT_IDENTIFIER,+ meta: {+ description:+ 'Let a running agent declare advisory self-iteration intent without mutating memory or skills directly.',+ title: 'Self Iteration Intent',+ },+ systemRole:+ 'Declare advisory self-iteration intent only when a future maintenance review may improve memory or skills. This tool records intent and must not claim that it directly mutates resources.',+ type: 'builtin',+} as const satisfies BuiltinToolManifest;diff --git a/packages/builtin-tool-self-iteration/src/types.ts b/packages/builtin-tool-self-iteration/src/types.tsnew file mode 100644index 00000000000..343ffb5d706--- /dev/null+++ b/packages/builtin-tool-self-iteration/src/types.ts@@ -0,0 +1,22 @@+/** Builtin identifier used to route self-iteration intent declarations. */+export const SELF_ITERATION_INTENT_IDENTIFIER = 'lobe-self-iteration-intent';++/** Runtime API name used by the injected self-iteration intent tool. */+export const SELF_ITERATION_INTENT_API_NAME = 'declareSelfIterationIntent';++/** LLM-visible tool name generated from identifier and API name. */+export const SELF_ITERATION_INTENT_TOOL_NAME = `${SELF_ITERATION_INTENT_IDENTIFIER}____${SELF_ITERATION_INTENT_API_NAME}`;++/** Gate input used to decide whether the declaration tool may be exposed. */+export interface ShouldExposeSelfIterationIntentToolOptions {+ /** Agent-level self-iteration chat config gate. */+ agentSelfIterationEnabled: boolean;+ /** Generic tool disable flag for this execution path. */+ disabled?: boolean;+ /** Explicit future-facing disable flag for reviewer/runtime callers. */+ disableSelfIterationIntentTool?: boolean;+ /** Server/user feature gate result, including user Labs eligibility. */+ featureUserEnabled: boolean;+ /** Reviewer paths must not receive the running-agent declaration tool. */+ reviewerRole?: boolean;+}diff --git a/packages/builtin-tool-self-iteration/vitest.config.mts b/packages/builtin-tool-self-iteration/vitest.config.mtsnew file mode 100644index 00000000000..4ac6027d578--- /dev/null+++ b/packages/builtin-tool-self-iteration/vitest.config.mts@@ -0,0 +1,7 @@+import { defineConfig } from 'vitest/config';++export default defineConfig({+ test: {+ environment: 'node',+ },+});diff --git a/packages/builtin-tools/package.json b/packages/builtin-tools/package.jsonindex 33003ea429e..7d88440c2d7 100644--- a/packages/builtin-tools/package.json+++ b/packages/builtin-tools/package.json@@ -38,6 +38,7 @@"@lobechat/builtin-tool-notebook": "workspace:*","@lobechat/builtin-tool-page-agent": "workspace:*","@lobechat/builtin-tool-remote-device": "workspace:*",+ "@lobechat/builtin-tool-self-iteration": "workspace:*","@lobechat/builtin-tool-skill-maintainer": "workspace:*","@lobechat/builtin-tool-skill-store": "workspace:*","@lobechat/builtin-tool-skills": "workspace:*",diff --git a/packages/builtin-tools/src/identifiers.ts b/packages/builtin-tools/src/identifiers.tsindex 963d394e814..7d6a39b08e3 100644--- a/packages/builtin-tools/src/identifiers.ts+++ b/packages/builtin-tools/src/identifiers.ts@@ -15,6 +15,7 @@ import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';import { MemoryManifest } from '@lobechat/builtin-tool-memory';import { NotebookManifest } from '@lobechat/builtin-tool-notebook';import { PageAgentManifest } from '@lobechat/builtin-tool-page-agent';+import { selfIterationIntentManifest } from '@lobechat/builtin-tool-self-iteration';import { SkillStoreManifest } from '@lobechat/builtin-tool-skill-store';import { SkillsManifest } from '@lobechat/builtin-tool-skills';import { TopicReferenceManifest } from '@lobechat/builtin-tool-topic-reference';@@ -38,6 +39,7 @@ export const builtinToolIdentifiers: string[] = [MemoryManifest.identifier,NotebookManifest.identifier,PageAgentManifest.identifier,+ selfIterationIntentManifest.identifier,SkillsManifest.identifier,SkillStoreManifest.identifier,TopicReferenceManifest.identifier,diff --git a/packages/builtin-tools/src/index.ts b/packages/builtin-tools/src/index.tsindex bb66947e511..9972093517e 100644--- a/packages/builtin-tools/src/index.ts+++ b/packages/builtin-tools/src/index.ts@@ -18,6 +18,7 @@ import { MemoryManifest } from '@lobechat/builtin-tool-memory';import { MessageManifest } from '@lobechat/builtin-tool-message';import { PageAgentManifest } from '@lobechat/builtin-tool-page-agent';import { RemoteDeviceManifest } from '@lobechat/builtin-tool-remote-device';+import { selfIterationIntentManifest } from '@lobechat/builtin-tool-self-iteration';import { SkillMaintainerManifest } from '@lobechat/builtin-tool-skill-maintainer';import { SkillStoreManifest } from '@lobechat/builtin-tool-skill-store';import { SkillsManifest } from '@lobechat/builtin-tool-skills';@@ -121,6 +122,13 @@ export const builtinTools: LobeBuiltinTool[] = [manifest: SkillMaintainerManifest,type: 'builtin',},+ {+ discoverable: false,+ hidden: true,+ identifier: selfIterationIntentManifest.identifier,+ manifest: selfIterationIntentManifest,+ type: 'builtin',+ },{discoverable: isDesktop,hidden: true,diff --git a/packages/database/src/models/agentSignal/__tests__/nightlyReview.test.ts b/packages/database/src/models/agentSignal/__tests__/nightlyReview.test.tsnew file mode 100644index 00000000000..e1e104f73a6--- /dev/null+++ b/packages/database/src/models/agentSignal/__tests__/nightlyReview.test.ts@@ -0,0 +1,305 @@+// @vitest-environment node+import { beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { agents, messagePlugins, messages, topics, users, userSettings } from '../../../schemas';+import type { LobeChatDatabase } from '../../../type';+import { AgentSignalNightlyReviewModel } from '../nightlyReview';++const serverDB: LobeChatDatabase = await getTestDB();++const enabledUserId = 'nightly-review-enabled-user';+const enabledUserWithoutTimezoneId = 'nightly-review-enabled-user-utc';+const disabledUserId = 'nightly-review-disabled-user';+const otherUserId = 'nightly-review-other-user';++beforeEach(async () => {+ await serverDB.delete(users);+});++describe('AgentSignalNightlyReviewModel', () => {+ describe('listEligibleUsers', () => {+ it('lists only users with AgentSignal self-iteration enabled', async () => {+ await serverDB.insert(users).values([+ {+ createdAt: new Date('2026-05-01T00:00:00.000Z'),+ id: enabledUserId,+ preference: { lab: { enableAgentSelfIteration: true } },+ },+ {+ createdAt: new Date('2026-05-02T00:00:00.000Z'),+ id: enabledUserWithoutTimezoneId,+ preference: { lab: { enableAgentSelfIteration: true } },+ },+ {+ createdAt: new Date('2026-05-03T00:00:00.000Z'),+ id: disabledUserId,+ preference: { lab: { enableAgentSelfIteration: false } },+ },+ ]);+ await serverDB.insert(userSettings).values({+ general: { timezone: 'Asia/Shanghai' },+ id: enabledUserId,+ });++ const model = new AgentSignalNightlyReviewModel(serverDB);++ const result = await model.listEligibleUsers();++ expect(result).toEqual([+ {+ createdAt: new Date('2026-05-01T00:00:00.000Z'),+ id: enabledUserId,+ timezone: 'Asia/Shanghai',+ },+ {+ createdAt: new Date('2026-05-02T00:00:00.000Z'),+ id: enabledUserWithoutTimezoneId,+ timezone: 'UTC',+ },+ ]);+ });++ it('uses cursor and whitelist filters for targeted scheduling pages', async () => {+ await serverDB.insert(users).values([+ {+ createdAt: new Date('2026-05-01T00:00:00.000Z'),+ id: enabledUserId,+ preference: { lab: { enableAgentSelfIteration: true } },+ },+ {+ createdAt: new Date('2026-05-02T00:00:00.000Z'),+ id: enabledUserWithoutTimezoneId,+ preference: { lab: { enableAgentSelfIteration: true } },+ },+ ]);++ const model = new AgentSignalNightlyReviewModel(serverDB);++ const result = await model.listEligibleUsers({+ cursor: { createdAt: new Date('2026-05-01T00:00:00.000Z'), id: enabledUserId },+ limit: 1,+ whitelist: [enabledUserWithoutTimezoneId],+ });++ expect(result).toEqual([+ {+ createdAt: new Date('2026-05-02T00:00:00.000Z'),+ id: enabledUserWithoutTimezoneId,+ timezone: 'UTC',+ },+ ]);+ });+ });++ describe('listActiveAgentTargets', () => {+ it('returns non-virtual agents with activity and failure counts inside the review window', async () => {+ await serverDB.insert(users).values([{ id: enabledUserId }, { id: otherUserId }]);+ await serverDB.insert(userSettings).values({+ general: { timezone: 'America/New_York' },+ id: enabledUserId,+ });++ const [activeAgent, legacyAgent, inactiveAgent, disabledAgent, virtualAgent, otherUserAgent] =+ await serverDB+ .insert(agents)+ .values([+ {+ chatConfig: { autoCreateTopicThreshold: 2, selfIteration: { enabled: true } },+ id: 'nightly-active-agent',+ title: 'Active agent',+ userId: enabledUserId,+ },+ {+ chatConfig: { autoCreateTopicThreshold: 2, selfIteration: { enabled: true } },+ id: 'nightly-legacy-agent',+ title: 'Legacy agent',+ userId: enabledUserId,+ },+ {+ chatConfig: { autoCreateTopicThreshold: 2, selfIteration: { enabled: true } },+ id: 'nightly-inactive-agent',+ title: 'Inactive agent',+ userId: enabledUserId,+ },+ {+ chatConfig: { autoCreateTopicThreshold: 2, selfIteration: { enabled: false } },+ id: 'nightly-disabled-agent',+ title: 'Disabled agent',+ userId: enabledUserId,+ },+ {+ chatConfig: { autoCreateTopicThreshold: 2, selfIteration: { enabled: true } },+ id: 'nightly-virtual-agent',+ title: 'Virtual agent',+ userId: enabledUserId,+ virtual: true,+ },+ {+ chatConfig: { autoCreateTopicThreshold: 2, selfIteration: { enabled: true } },+ id: 'nightly-other-user-agent',+ title: 'Other user',+ userId: otherUserId,+ },+ ])+ .returning();++ await serverDB.insert(topics).values([+ {+ agentId: activeAgent.id,+ id: 'nightly-topic-active',+ title: 'Active',+ userId: enabledUserId,+ },+ {+ agentId: legacyAgent.id,+ id: 'nightly-topic-legacy',+ title: 'Legacy',+ userId: enabledUserId,+ },+ {+ agentId: disabledAgent.id,+ id: 'nightly-topic-disabled',+ title: 'Disabled',+ userId: enabledUserId,+ },+ {+ agentId: virtualAgent.id,+ id: 'nightly-topic-virtual',+ title: 'Virtual',+ userId: enabledUserId,+ },+ {+ agentId: otherUserAgent.id,+ id: 'nightly-topic-other-user',+ title: 'Other',+ userId: otherUserId,+ },+ ]);++ await serverDB.insert(messages).values([+ {+ agentId: activeAgent.id,+ content: 'inside first',+ createdAt: new Date('2026-05-03T12:00:00.000Z'),+ id: 'nightly-message-active-1',+ role: 'user',+ topicId: 'nightly-topic-active',+ userId: enabledUserId,+ },+ {+ agentId: activeAgent.id,+ content: 'failed tool result',+ createdAt: new Date('2026-05-03T13:00:00.000Z'),+ id: 'nightly-message-active-2',+ role: 'assistant',+ topicId: 'nightly-topic-active',+ userId: enabledUserId,+ },+ {+ content: 'legacy message uses topic agent',+ createdAt: new Date('2026-05-03T14:00:00.000Z'),+ id: 'nightly-message-legacy',+ role: 'user',+ topicId: 'nightly-topic-legacy',+ userId: enabledUserId,+ },+ {+ agentId: activeAgent.id,+ content: 'outside window',+ createdAt: new Date('2026-05-02T23:59:59.000Z'),+ id: 'nightly-message-outside',+ role: 'user',+ topicId: 'nightly-topic-active',+ userId: enabledUserId,+ },+ {+ agentId: disabledAgent.id,+ content: 'disabled agent should not schedule',+ createdAt: new Date('2026-05-03T14:30:00.000Z'),+ id: 'nightly-message-disabled',+ role: 'user',+ topicId: 'nightly-topic-disabled',+ userId: enabledUserId,+ },+ {+ agentId: virtualAgent.id,+ content: 'virtual should not schedule',+ createdAt: new Date('2026-05-03T15:00:00.000Z'),+ id: 'nightly-message-virtual',+ role: 'user',+ topicId: 'nightly-topic-virtual',+ userId: enabledUserId,+ },+ {+ agentId: otherUserAgent.id,+ content: 'other user should not leak',+ createdAt: new Date('2026-05-03T16:00:00.000Z'),+ id: 'nightly-message-other-user',+ role: 'user',+ topicId: 'nightly-topic-other-user',+ userId: otherUserId,+ },+ ]);+ await serverDB.insert(messagePlugins).values({+ error: { message: 'tool failed' },+ id: 'nightly-message-active-2',+ userId: enabledUserId,+ });++ const model = new AgentSignalNightlyReviewModel(serverDB);++ const result = await model.listActiveAgentTargets(enabledUserId, {+ windowEnd: new Date('2026-05-03T23:59:59.999Z'),+ windowStart: new Date('2026-05-03T00:00:00.000Z'),+ });++ expect(result).toEqual([+ {+ agentId: legacyAgent.id,+ failedToolCallCount: 0,+ firstActivityAt: new Date('2026-05-03T14:00:00.000Z'),+ lastActivityAt: new Date('2026-05-03T14:00:00.000Z'),+ messageCount: 1,+ timezone: 'America/New_York',+ title: 'Legacy agent',+ topicCount: 1,+ },+ {+ agentId: activeAgent.id,+ failedToolCallCount: 1,+ firstActivityAt: new Date('2026-05-03T12:00:00.000Z'),+ lastActivityAt: new Date('2026-05-03T13:00:00.000Z'),+ messageCount: 2,+ timezone: 'America/New_York',+ title: 'Active agent',+ topicCount: 1,+ },+ ]);+ expect(result.map((item) => item.agentId)).not.toContain(inactiveAgent.id);+ expect(result.map((item) => item.agentId)).not.toContain(disabledAgent.id);+ expect(result.map((item) => item.agentId)).not.toContain(virtualAgent.id);+ expect(result.map((item) => item.agentId)).not.toContain(otherUserAgent.id);++ const targetedResult = await model.listActiveAgentTargets(enabledUserId, {+ agentId: activeAgent.id,+ limit: 1,+ windowEnd: new Date('2026-05-03T23:59:59.999Z'),+ windowStart: new Date('2026-05-03T00:00:00.000Z'),+ });++ expect(targetedResult).toEqual([+ {+ agentId: activeAgent.id,+ failedToolCallCount: 1,+ firstActivityAt: new Date('2026-05-03T12:00:00.000Z'),+ lastActivityAt: new Date('2026-05-03T13:00:00.000Z'),+ messageCount: 2,+ timezone: 'America/New_York',+ title: 'Active agent',+ topicCount: 1,+ },+ ]);+ });+ });+});diff --git a/packages/database/src/models/agentSignal/nightlyReview.ts b/packages/database/src/models/agentSignal/nightlyReview.tsnew file mode 100644index 00000000000..031cf996a5a--- /dev/null+++ b/packages/database/src/models/agentSignal/nightlyReview.ts@@ -0,0 +1,215 @@+import {+ and,+ asc,+ count,+ countDistinct,+ eq,+ gt,+ gte,+ inArray,+ isNull,+ lte,+ or,+ sql,+} from 'drizzle-orm';++import { agents, messagePlugins, messages, topics, users, userSettings } from '../../schemas';+import type { LobeChatDatabase } from '../../type';++/**+ * Normalizes database aggregate timestamps.+ *+ * Before:+ * - "2026-05-03 14:00:00+00"+ *+ * After:+ * - Date("2026-05-03T14:00:00.000Z")+ */+const parseAggregateTimestamp = (value: Date | string) =>+ value instanceof Date ? value : new Date(value);++/** Cursor for stable user pagination in AgentSignal nightly review scheduling. */+export interface ListAgentSignalNightlyReviewUsersCursor {+ /** User creation time used as the primary cursor key. */+ createdAt: Date;+ /** User id used as the tie-break cursor key. */+ id: string;+}++/** Options for listing users eligible for AgentSignal nightly review scheduling. */+export interface ListAgentSignalNightlyReviewUsersOptions {+ /** Cursor returned by the previous page. */+ cursor?: ListAgentSignalNightlyReviewUsersCursor;+ /** Maximum users to return. */+ limit?: number;+ /** Optional user allowlist for backfills, tests, and targeted runs. */+ whitelist?: string[];+}++/** One user candidate for AgentSignal nightly review scheduling. */+export interface AgentSignalNightlyReviewUserCandidate {+ /** Creation time used for cursor pagination. */+ createdAt: Date;+ /** Stable user id. */+ id: string;+ /** IANA timezone from user general settings, defaulting to UTC when missing. */+ timezone: string;+}++/** Options for listing active agent review targets for one user and one review window. */+export interface ListAgentSignalNightlyReviewTargetsOptions {+ /** Optional single-agent filter for handler-side source validation. */+ agentId?: string;+ /** Maximum active agents to return. */+ limit?: number;+ /** Review window end in UTC. */+ windowEnd: Date;+ /** Review window start in UTC. */+ windowStart: Date;+}++/** One active agent target that should receive a nightly review request. */+export interface AgentSignalNightlyReviewTarget {+ /** Agent id receiving the nightly source event. */+ agentId: string;+ /** Number of failed tool call records observed in the review window. */+ failedToolCallCount: number;+ /** First message activity timestamp in the review window. */+ firstActivityAt: Date;+ /** Last message activity timestamp in the review window. */+ lastActivityAt: Date;+ /** Number of messages observed in the review window. */+ messageCount: number;+ /** IANA timezone from user general settings, defaulting to UTC when missing. */+ timezone: string;+ /** Agent title for brief/debug context. */+ title: string | null;+ /** Number of distinct topics touched in the review window. */+ topicCount: number;+}++/**+ * Queries the database surface needed by AgentSignal nightly self-reflection.+ *+ * Use when:+ * - Cron dispatch needs stable user pagination+ * - Nightly review needs active agent targets for a local-day window+ *+ * Expects:+ * - User-level AgentSignal lab preference is stored on `users.preference.lab`+ * - Agent-level opt-in is stored on `agents.chatConfig.selfIteration.enabled`+ *+ * Returns:+ * - Candidate users and active agent targets without emitting source events+ */+export class AgentSignalNightlyReviewModel {+ private db: LobeChatDatabase;++ constructor(db: LobeChatDatabase) {+ this.db = db;+ }++ /**+ * Lists users who opted into AgentSignal self-iteration and have a timezone.+ *+ * Use when:+ * - The nightly scheduler needs a stable cursor over possible users+ * - Backfills need to restrict scheduling to a user allowlist+ *+ * Expects:+ * - Global feature gates are checked by the service layer+ * - Missing user timezone falls back to UTC+ *+ * Returns:+ * - Users sorted by `createdAt, id` for deterministic pagination+ */+ listEligibleUsers = (options: ListAgentSignalNightlyReviewUsersOptions = {}) => {+ const cursorCondition = options.cursor+ ? or(+ gt(users.createdAt, options.cursor.createdAt),+ and(eq(users.createdAt, options.cursor.createdAt), gt(users.id, options.cursor.id)),+ )+ : undefined;++ const whitelistCondition =+ options.whitelist && options.whitelist.length > 0+ ? inArray(users.id, options.whitelist)+ : undefined;++ const selfIterationEnabledCondition = sql`+ COALESCE((${users.preference}->'lab'->>'enableAgentSelfIteration')::boolean, false) = true+ `;++ const query = this.db+ .select({+ createdAt: users.createdAt,+ id: users.id,+ timezone: sql<string>`COALESCE(${userSettings.general}->>'timezone', 'UTC')`,+ })+ .from(users)+ .leftJoin(userSettings, eq(users.id, userSettings.id))+ .where(and(cursorCondition, whitelistCondition, selfIterationEnabledCondition))+ .orderBy(asc(users.createdAt), asc(users.id));++ return options.limit !== undefined ? query.limit(options.limit) : query;+ };++ /**+ * Lists active non-virtual agents for one user's review window.+ *+ * Use when:+ * - The scheduler must avoid running inactive agents+ * - The collector needs coarse activity counts before building digests+ *+ * Expects:+ * - `windowStart` and `windowEnd` are UTC instants for the user's local review date+ * - Message `agentId` wins when present; topic `agentId` covers legacy messages+ *+ * Returns:+ * - Non-virtual agent targets with message/topic/failure counts+ */+ listActiveAgentTargets = (+ userId: string,+ options: ListAgentSignalNightlyReviewTargetsOptions,+ ) => {+ const effectiveAgentId = sql<string>`COALESCE(${messages.agentId}, ${topics.agentId})`;+ const agentFilter = options.agentId ? eq(agents.id, options.agentId) : undefined;++ const query = this.db+ .select({+ agentId: agents.id,+ failedToolCallCount:+ sql<number>`COUNT(${messagePlugins.id}) FILTER (WHERE ${messagePlugins.error} IS NOT NULL)`.mapWith(+ Number,+ ),+ firstActivityAt: sql<Date>`MIN(${messages.createdAt})`.mapWith(parseAggregateTimestamp),+ lastActivityAt: sql<Date>`MAX(${messages.createdAt})`.mapWith(parseAggregateTimestamp),+ messageCount: count(messages.id),+ timezone: sql<string>`COALESCE(${userSettings.general}->>'timezone', 'UTC')`,+ title: agents.title,+ topicCount: countDistinct(messages.topicId),+ })+ .from(messages)+ .leftJoin(topics, and(eq(topics.id, messages.topicId), eq(topics.userId, userId)))+ .innerJoin(agents, and(eq(agents.id, effectiveAgentId), eq(agents.userId, userId)))+ .leftJoin(userSettings, eq(userSettings.id, userId))+ .leftJoin(+ messagePlugins,+ and(eq(messagePlugins.id, messages.id), eq(messagePlugins.userId, userId)),+ )+ .where(+ and(+ eq(messages.userId, userId),+ agentFilter,+ gte(messages.createdAt, options.windowStart),+ lte(messages.createdAt, options.windowEnd),+ or(eq(agents.virtual, false), isNull(agents.virtual)),+ sql`COALESCE((${agents.chatConfig}->'selfIteration'->>'enabled')::boolean, false) = true`,+ ),+ )+ .groupBy(agents.id, agents.title, userSettings.general)+ .orderBy(sql`MAX(${messages.createdAt}) DESC`);++ return options.limit !== undefined ? query.limit(options.limit) : query;+ };+}diff --git a/packages/database/src/models/agentSignal/reviewContext.ts b/packages/database/src/models/agentSignal/reviewContext.tsnew file mode 100644index 00000000000..835f75c2ba2--- /dev/null+++ b/packages/database/src/models/agentSignal/reviewContext.ts@@ -0,0 +1,160 @@+import { and, count, desc, eq, gte, isNull, lte, or, sql } from 'drizzle-orm';++import { agents, messagePlugins, messages, topics, userMemories } from '../../schemas';+import type { LobeChatDatabase } from '../../type';++const parseAggregateTimestamp = (value: Date | string) =>+ value instanceof Date ? value : new Date(value);++export interface ListAgentSignalTopicActivityOptions {+ agentId: string;+ limit: number;+ windowEnd: Date;+ windowStart: Date;+}++export interface ListAgentSignalSelfReflectionTopicOptions {+ agentId: string;+ topicId: string;+ windowEnd: Date;+ windowStart: Date;+}++export interface ListAgentSignalRelevantMemoriesOptions {+ limit: number;+}++export interface AgentSignalTopicActivityRow {+ failedToolCount: number;+ failureCount: number;+ lastActivityAt: Date | null;+ messageCount: number;+ summary: string;+ title: string | null;+ topicId: string | null;+}++export interface AgentSignalRelevantMemoryRow {+ content: string;+ id: string;+ updatedAt: Date;+}++/** Database-backed context queries for Agent Signal self-review policies. */+export class AgentSignalReviewContextModel {+ private readonly db: LobeChatDatabase;+ private readonly userId: string;++ constructor(db: LobeChatDatabase, userId: string) {+ this.db = db;+ this.userId = userId;+ }++ /** Checks agent ownership, virtual status, and self-iteration opt-in. */+ canAgentRunSelfIteration = async (agentId: string) => {+ const [agent] = await this.db+ .select({ id: agents.id })+ .from(agents)+ .where(+ and(+ eq(agents.id, agentId),+ eq(agents.userId, this.userId),+ or(eq(agents.virtual, false), isNull(agents.virtual)),+ sql`COALESCE((${agents.chatConfig}->'selfIteration'->>'enabled')::boolean, false) = true`,+ ),+ )+ .limit(1);++ return Boolean(agent);+ };++ /** Lists recent memory summaries for review context. */+ listRelevantMemories = (options: ListAgentSignalRelevantMemoriesOptions) => {+ return this.db+ .select({+ content: sql<string>`COALESCE(${userMemories.summary}, ${userMemories.title}, ${userMemories.details}, '')`,+ id: userMemories.id,+ updatedAt: userMemories.updatedAt,+ })+ .from(userMemories)+ .where(eq(userMemories.userId, this.userId))+ .orderBy(desc(userMemories.updatedAt))+ .limit(options.limit);+ };++ /** Lists bounded topic activity for nightly review context. */+ listTopicActivity = (options: ListAgentSignalTopicActivityOptions) => {+ const effectiveAgentId = sql<string>`COALESCE(${messages.agentId}, ${topics.agentId})`;++ return this.db+ .select({+ failedToolCount:+ sql<number>`COUNT(${messagePlugins.id}) FILTER (WHERE ${messagePlugins.error} IS NOT NULL)`.mapWith(+ Number,+ ),+ failureCount:+ sql<number>`COUNT(${messages.id}) FILTER (WHERE ${messages.error} IS NOT NULL)`.mapWith(+ Number,+ ),+ lastActivityAt: sql<Date>`MAX(${messages.createdAt})`.mapWith(parseAggregateTimestamp),+ messageCount: count(messages.id),+ summary: sql<string>`COALESCE(${topics.historySummary}, ${topics.description}, ${topics.content}, '')`,+ title: topics.title,+ topicId: topics.id,+ })+ .from(messages)+ .leftJoin(topics, and(eq(topics.id, messages.topicId), eq(topics.userId, this.userId)))+ .leftJoin(+ messagePlugins,+ and(eq(messagePlugins.id, messages.id), eq(messagePlugins.userId, this.userId)),+ )+ .where(+ and(+ eq(messages.userId, this.userId),+ eq(effectiveAgentId, options.agentId),+ gte(messages.createdAt, options.windowStart),+ lte(messages.createdAt, options.windowEnd),+ ),+ )+ .groupBy(topics.id, topics.title, topics.historySummary, topics.description, topics.content)+ .orderBy(desc(sql`MAX(${messages.createdAt})`))+ .limit(options.limit);+ };++ /** Lists scoped topic activity for self-reflection review context. */+ listSelfReflectionTopicActivity = (options: ListAgentSignalSelfReflectionTopicOptions) => {+ return this.db+ .select({+ failedToolCount:+ sql<number>`COUNT(${messagePlugins.id}) FILTER (WHERE ${messagePlugins.error} IS NOT NULL)`.mapWith(+ Number,+ ),+ failureCount:+ sql<number>`COUNT(${messages.id}) FILTER (WHERE ${messages.error} IS NOT NULL)`.mapWith(+ Number,+ ),+ lastActivityAt: sql<Date>`MAX(${messages.createdAt})`.mapWith(parseAggregateTimestamp),+ messageCount: count(messages.id),+ summary: sql<string>`COALESCE(${topics.historySummary}, ${topics.description}, ${topics.content}, '')`,+ title: topics.title,+ topicId: topics.id,+ })+ .from(messages)+ .leftJoin(topics, and(eq(topics.id, messages.topicId), eq(topics.userId, this.userId)))+ .leftJoin(+ messagePlugins,+ and(eq(messagePlugins.id, messages.id), eq(messagePlugins.userId, this.userId)),+ )+ .where(+ and(+ eq(messages.userId, this.userId),+ eq(messages.agentId, options.agentId),+ gte(messages.createdAt, options.windowStart),+ lte(messages.createdAt, options.windowEnd),+ eq(messages.topicId, options.topicId),+ ),+ )+ .groupBy(topics.id, topics.title, topics.historySummary, topics.description, topics.content)+ .limit(1);+ };+}diff --git a/packages/prompts/src/prompts/agentSignal/index.ts b/packages/prompts/src/prompts/agentSignal/index.tsindex 41768e51471..719f435147d 100644--- a/packages/prompts/src/prompts/agentSignal/index.ts+++ b/packages/prompts/src/prompts/agentSignal/index.ts@@ -1 +1,2 @@export * from './analyzeIntent';+export * from './nightlyReview';diff --git a/packages/prompts/src/prompts/agentSignal/nightlyReview.test.ts b/packages/prompts/src/prompts/agentSignal/nightlyReview.test.tsnew file mode 100644index 00000000000..3848e876a6e--- /dev/null+++ b/packages/prompts/src/prompts/agentSignal/nightlyReview.test.ts@@ -0,0 +1,47 @@+import { describe, expect, it } from 'vitest';++import {+ AGENT_SIGNAL_NIGHTLY_REVIEW_SYSTEM_ROLE,+ createAgentSignalNightlyReviewMessages,+} from './nightlyReview';++describe('agent signal nightly review prompt', () => {+ /**+ * @example+ * The prompt keeps automatic mutations constrained to explicit low-risk maintenance.+ */+ it('documents the auto-apply boundary for nightly maintenance', () => {+ expect(AGENT_SIGNAL_NIGHTLY_REVIEW_SYSTEM_ROLE).toContain(+ 'Use noop for ordinary successful days',+ );+ expect(AGENT_SIGNAL_NIGHTLY_REVIEW_SYSTEM_ROLE).toContain(+ 'Auto-safe memory candidates must be explicit',+ );+ expect(AGENT_SIGNAL_NIGHTLY_REVIEW_SYSTEM_ROLE).toContain(+ 'Consolidation should stay proposal_only',+ );+ });++ /**+ * @example+ * A private-safe bounded digest is sent as the user message beside the stable system role.+ */+ it('builds structured generation messages from bounded review context', () => {+ const messages = createAgentSignalNightlyReviewMessages({+ agentId: 'agent-1',+ topics: [{ summary: 'User explicitly prefers concise PR summaries.' }],+ });++ expect(messages).toEqual([+ {+ content: AGENT_SIGNAL_NIGHTLY_REVIEW_SYSTEM_ROLE,+ role: 'system',+ },+ {+ content:+ '{"agentId":"agent-1","topics":[{"summary":"User explicitly prefers concise PR summaries."}]}',+ role: 'user',+ },+ ]);+ });+});diff --git a/packages/prompts/src/prompts/agentSignal/nightlyReview.ts b/packages/prompts/src/prompts/agentSignal/nightlyReview.tsnew file mode 100644index 00000000000..dc3c16357c2--- /dev/null+++ b/packages/prompts/src/prompts/agentSignal/nightlyReview.ts@@ -0,0 +1,31 @@+export const AGENT_SIGNAL_NIGHTLY_REVIEW_SYSTEM_ROLE = [+ 'Review the bounded daily digest for one assistant. Return only safe maintenance actions.',+ 'Use noop for ordinary successful days. Non-noop actions must cite evidenceRefs from the digest.',+ 'Attach policyHints for every non-noop action: evidenceStrength, userExplicitness, sensitivity, persistence, and mutationScope when skill-related.',+ 'Auto-safe memory candidates must be explicit, stable, normal-sensitivity preferences or durable facts; inferred, temporal, sensitive, third-party, or ambiguous memory candidates should be proposal_only or noop.',+ 'Skill creation/refinement should be proposal_only unless the evidence shows explicit maintenance intent and a small targeted change. Consolidation should stay proposal_only.',+].join(' ');++/**+ * Builds model messages for Agent Signal nightly maintenance review.+ *+ * Use when:+ * - A server reviewer asks the model to convert a bounded digest into maintenance drafts+ * - Tests need the stable prompt contract without importing server runtime code+ *+ * Expects:+ * - `context` is already private-safe and bounded by the caller+ *+ * Returns:+ * - A system/user message pair ready for structured object generation+ */+export const createAgentSignalNightlyReviewMessages = (context: unknown) => [+ {+ content: AGENT_SIGNAL_NIGHTLY_REVIEW_SYSTEM_ROLE,+ role: 'system' as const,+ },+ {+ content: JSON.stringify(context),+ role: 'user' as const,+ },+];diff --git a/packages/types/src/agent/chatConfig.ts b/packages/types/src/agent/chatConfig.tsindex 3f6d2b77773..cfa506de3eb 100644--- a/packages/types/src/agent/chatConfig.ts+++ b/packages/types/src/agent/chatConfig.ts@@ -18,7 +18,13 @@ export interface AgentMemoryChatConfig {};}-export interface LobeAgentChatConfig extends AgentMemoryChatConfig {+export interface AgentSelfIterationChatConfig {+ selfIteration?: {+ enabled?: boolean;+ };+}++export interface LobeAgentChatConfig extends AgentMemoryChatConfig, AgentSelfIterationChatConfig {autoCreateTopicThreshold: number;codexMaxReasoningEffort?: 'low' | 'medium' | 'high' | 'xhigh';/**@@ -177,6 +183,14 @@ export const MemoryChatConfigSchema = z.object({.optional(),});+export const SelfIterationChatConfigSchema = z.object({+ selfIteration: z+ .object({+ enabled: z.boolean().optional(),+ })+ .optional(),+});+export const AgentChatConfigSchema = z.object({autoCreateTopicThreshold: z.number().default(2),@@ -233,4 +247,5 @@ export const AgentChatConfigSchema = zurlContext: z.boolean().optional(),useModelBuiltinSearch: z.boolean().optional(),})- .merge(MemoryChatConfigSchema);+ .merge(MemoryChatConfigSchema)+ .merge(SelfIterationChatConfigSchema);diff --git a/src/features/AgentSetting/AgentChat/index.tsx b/src/features/AgentSetting/AgentChat/index.tsxindex 4608845f99d..824b226453f 100644--- a/src/features/AgentSetting/AgentChat/index.tsx+++ b/src/features/AgentSetting/AgentChat/index.tsx@@ -1,6 +1,6 @@'use client';-import { type FormGroupItemType } from '@lobehub/ui';+import type { FormGroupItemType } from '@lobehub/ui';import { Form, SliderWithInput } from '@lobehub/ui';import { Switch } from 'antd';import isEqual from 'fast-deep-equal';@@ -16,6 +16,13 @@ const AgentChat = memo(() => {const [form] = Form.useForm();const updateConfig = useStore((s) => s.setChatConfig);const config = useStore(selectors.currentChatConfig, isEqual);+ const initialValues = {+ ...config,+ selfIteration: {+ ...config.selfIteration,+ enabled: config.selfIteration?.enabled ?? false,+ },+ };const chat: FormGroupItemType = {children: [@@ -74,12 +81,27 @@ const AgentChat = memo(() => {title: t('settingChat.title'),};+ const selfIteration: FormGroupItemType = {+ children: [+ {+ children: <Switch />,+ desc: t('settingChat.selfIteration.enabled.desc'),+ label: t('settingChat.selfIteration.enabled.title'),+ layout: 'horizontal',+ minWidth: undefined,+ name: ['selfIteration', 'enabled'],+ valuePropName: 'checked',+ },+ ],+ title: t('settingChat.selfIteration.title'),+ };+return (<Formfooter={<Form.SubmitFooter />}form={form}- initialValues={config}- items={[chat]}+ initialValues={initialValues}+ items={[chat, selfIteration]}itemsType={'group'}variant={'borderless'}onFinish={updateConfig}diff --git a/src/features/AgentSetting/store/reducers/config.test.ts b/src/features/AgentSetting/store/reducers/config.test.tsnew file mode 100644index 00000000000..91ae31d33ba--- /dev/null+++ b/src/features/AgentSetting/store/reducers/config.test.ts@@ -0,0 +1,39 @@+import { describe, expect, it } from 'vitest';++import { DEFAULT_AGENT_CONFIG } from '@/const/settings';++import { configReducer } from './config';++describe('configReducer', () => {+ describe('update', () => {+ it('should deep merge self iteration chat config without dropping existing chat config fields', () => {+ const state = {+ ...DEFAULT_AGENT_CONFIG,+ chatConfig: {+ ...DEFAULT_AGENT_CONFIG.chatConfig,+ enableHistoryCount: true,+ historyCount: 12,+ },+ };++ const nextState = configReducer(state, {+ config: {+ chatConfig: {+ selfIteration: {+ enabled: true,+ },+ },+ },+ type: 'update',+ });++ expect(nextState.chatConfig).toMatchObject({+ enableHistoryCount: true,+ historyCount: 12,+ selfIteration: {+ enabled: true,+ },+ });+ });+ });+});diff --git a/src/features/AgentSetting/store/reducers/config.ts b/src/features/AgentSetting/store/reducers/config.tsindex d60057d7a0a..b0f8803c5e2 100644--- a/src/features/AgentSetting/store/reducers/config.ts+++ b/src/features/AgentSetting/store/reducers/config.ts@@ -1,11 +1,12 @@import { produce } from 'immer';+import type { PartialDeep } from 'type-fest';import { DEFAULT_AGENT_CONFIG } from '@/const/settings';-import { type LobeAgentConfig } from '@/types/agent';+import type { LobeAgentConfig } from '@/types/agent';import { merge } from '@/utils/merge';export type ConfigDispatch =- | { config: Partial<any>; type: 'update' }+ | { config: PartialDeep<LobeAgentConfig>; type: 'update' }| { pluginId: string; state?: boolean; type: 'togglePlugin' }| { type: 'reset' };diff --git a/src/locales/default/setting.ts b/src/locales/default/setting.tsindex a773d167eb2..0f0b1cf6a22 100644--- a/src/locales/default/setting.ts+++ b/src/locales/default/setting.ts@@ -596,6 +596,10 @@ export default {'settingChat.inputTemplate.placeholder':'Preprocessing template {{text}} will be replaced with real-time input information','settingChat.inputTemplate.title': 'User Input Preprocessing',+ 'settingChat.selfIteration.enabled.desc':+ 'Allow this assistant to review recent signals and improve its own skills when the lab workflow runs',+ 'settingChat.selfIteration.enabled.title': 'Enable Self-Iteration',+ 'settingChat.selfIteration.title': 'Advanced Labs','settingChat.submit': 'Update Chat Preferences','settingChat.title': 'Chat Settings','settingChatAppearance.autoScrollOnStreaming.desc':diff --git a/src/server/services/agentSignal/__tests__/orchestrator.test.ts b/src/server/services/agentSignal/__tests__/orchestrator.test.tsnew file mode 100644index 00000000000..aea0f3c431e--- /dev/null+++ b/src/server/services/agentSignal/__tests__/orchestrator.test.ts@@ -0,0 +1,133 @@+// @vitest-environment node+import { describe, expect, it, vi } from 'vitest';++import { BriefModel } from '@/database/models/brief';++import type { AgentSignalEmitOptions } from '../emitter';+import { withServerAgentSignalPolicyDefaults } from '../orchestrator';+import { createBriefMaintenanceService } from '../services/maintenance/brief';+import { MaintenanceActionStatus, ReviewRunStatus } from '../services/maintenance/types';++const createNightlyReviewOptions = (): NonNullable<+ NonNullable<AgentSignalEmitOptions['policyOptions']>['nightlyReview']+> => ({+ acquireReviewGuard: vi.fn(async () => true),+ canRunReview: vi.fn(async () => true),+ collectContext: vi.fn(async () => ({+ agentId: 'agent-1',+ managedSkills: [],+ relevantMemories: [],+ reviewWindowEnd: '2026-05-04T14:30:00.000Z',+ reviewWindowStart: '2026-05-03T16:00:00.000Z',+ topics: [],+ userId: 'user-1',+ })),+ executePlan: vi.fn(async () => ({+ actions: [],+ status: ReviewRunStatus.Completed,+ })),+ planReviewOutput: vi.fn((request) => ({+ actions: [],+ localDate: request.localDate,+ plannerVersion: 'test',+ reviewScope: request.reviewScope,+ summary: request.draft.summary,+ })),+ runMaintenanceReviewAgent: vi.fn(async () => ({+ actions: [],+ findings: [],+ summary: 'Quiet night.',+ })),+});++describe('Agent Signal orchestrator policy defaults', () => {+ /**+ * @example+ * expect(result).toBeUndefined().+ */+ it('does not install nightly brief writing for analyze-intent-only policy options', () => {+ expect(+ withServerAgentSignalPolicyDefaults(+ {+ skillManagement: {+ selfIterationEnabled: true,+ },+ },+ { db: {} as never, userId: 'user-1' },+ )?.nightlyReview,+ ).toBeUndefined();+ });++ /**+ * @example+ * expect(options.nightlyReview?.writeDailyBrief).toBeTypeOf('function').+ */+ it('adds a server BriefModel writer when nightly review deps omit one', async () => {+ const create = vi.spyOn(BriefModel.prototype, 'create').mockResolvedValue({+ agentId: 'agent-1',+ createdAt: new Date('2026-05-04T14:30:00.000Z'),+ id: 'brief-1',+ metadata: {},+ priority: 'info',+ summary: '1 maintenance update applied.',+ title: 'Agent self-review updated resources',+ trigger: 'agent-signal:nightly-review',+ type: 'insight',+ userId: 'user-1',+ } as Awaited<ReturnType<BriefModel['create']>>);+ const policyOptions = withServerAgentSignalPolicyDefaults(+ {+ nightlyReview: createNightlyReviewOptions(),+ },+ { db: {} as never, userId: 'user-1' },+ );+ const brief = createBriefMaintenanceService().projectNightlyReviewBrief({+ agentId: 'agent-1',+ localDate: '2026-05-04',+ result: {+ actions: [+ {+ idempotencyKey: 'source:write_memory:memory:concise',+ receiptId: 'receipt-1',+ status: MaintenanceActionStatus.Applied,+ summary: 'Saved concise PR summary preference.',+ },+ ],+ status: ReviewRunStatus.Completed,+ },+ reviewWindowEnd: '2026-05-04T14:30:00.000Z',+ reviewWindowStart: '2026-05-03T16:00:00.000Z',+ timezone: 'Asia/Shanghai',+ userId: 'user-1',+ });++ if (!brief) throw new Error('Expected projected brief');++ await expect(policyOptions?.nightlyReview?.writeDailyBrief?.(brief)).resolves.toMatchObject({+ id: 'brief-1',+ });+ expect(create).toHaveBeenCalledWith(brief);+ });++ /**+ * @example+ * expect(existingWriter).toHaveBeenCalled().+ */+ it('preserves an explicitly injected nightly brief writer', async () => {+ const writeDailyBrief = vi.fn(async () => ({ id: 'custom-brief' }));+ const policyOptions = withServerAgentSignalPolicyDefaults(+ {+ nightlyReview: {+ ...createNightlyReviewOptions(),+ writeDailyBrief,+ },+ },+ { db: {} as never, userId: 'user-1' },+ );++ await expect(policyOptions?.nightlyReview?.writeDailyBrief?.({} as never)).resolves.toEqual({+ id: 'custom-brief',+ });+ expect(writeDailyBrief).toHaveBeenCalled();+ });+});diff --git a/src/server/services/agentSignal/orchestrator.ts b/src/server/services/agentSignal/orchestrator.tsindex f3ec8f2cd59..ad1552c70bb 100644--- a/src/server/services/agentSignal/orchestrator.ts+++ b/src/server/services/agentSignal/orchestrator.ts@@ -7,19 +7,22 @@ import type {GeneratedSourceEventResult,SignalPlan,} from '@lobechat/agent-signal';-import { type AgentSignalSourceType, createSourceEvent } from '@lobechat/agent-signal/source';+import type { AgentSignalSourceType } from '@lobechat/agent-signal/source';+import { createSourceEvent } from '@lobechat/agent-signal/source';-import {- type AgentSignalEmitOptions,- type AgentSignalExecutionContext,- type AgentSignalSourceEventInput,+import type {+ AgentSignalEmitOptions,+ AgentSignalExecutionContext,+ AgentSignalSourceEventInput,} from './emitter';import { projectAgentSignalObservability } from './observability/projector';import { persistAgentSignalObservability } from './observability/store';+import type { CreateDefaultAgentSignalPoliciesOptions } from './policies';import { createDefaultAgentSignalPolicies } from './policies';import { createProcedurePolicyOptions } from './procedure';import type { RuntimeGuardBackend } from './runtime/AgentSignalRuntime';import { createAgentSignalRuntime } from './runtime/AgentSignalRuntime';+import { createServerMaintenanceBriefWriter } from './services/maintenance/brief';import { persistAgentSignalReceipts, projectAgentSignalReceipts } from './services/receiptService';import { emitSourceEvent } from './sources';import { redisPolicyStateStore } from './store/adapters/redis/policyStateStore';@@ -88,6 +91,80 @@ const buildRuntimeOrchestrationResult = (};};+/**+ * Adds server defaults to optional Agent Signal maintenance policy options.+ *+ * Use when:+ * - A caller already installed nightly review options but omitted the brief writer+ * - Nightly review outcomes should persist eligible Daily Brief rows in the server runtime+ *+ * Expects:+ * - Missing `nightlyReview` still means the nightly handler is intentionally not installed+ *+ * Returns:+ * - Policy options with a server `writeDailyBrief` fallback only for nightly review+ */+export const withServerAgentSignalPolicyDefaults = (+ policyOptions: AgentSignalEmitOptions['policyOptions'] | undefined,+ context: AgentSignalExecutionContext,+): AgentSignalEmitOptions['policyOptions'] => {+ if (!policyOptions?.nightlyReview || policyOptions.nightlyReview.writeDailyBrief) {+ return policyOptions;+ }++ const briefWriter = createServerMaintenanceBriefWriter(context.db, context.userId);++ return {+ ...policyOptions,+ nightlyReview: {+ ...policyOptions.nightlyReview,+ writeDailyBrief: briefWriter.writeDailyBrief,+ },+ };+};++const createPolicyOptions = (+ context: AgentSignalExecutionContext,+ options: ExecuteAgentSignalSourceEventOptions,+ procedurePolicyOptions: NonNullable<CreateDefaultAgentSignalPoliciesOptions['procedure']>,+): CreateDefaultAgentSignalPoliciesOptions => {+ const policyOptions = withServerAgentSignalPolicyDefaults(options.policyOptions, context);++ return {+ feedbackDomainJudge: {+ db: context.db,+ ...policyOptions?.feedbackDomainJudge,+ userId: context.userId,+ },+ feedbackSatisfactionJudge: {+ db: context.db,+ ...policyOptions?.feedbackSatisfactionJudge,+ userId: context.userId,+ },+ classifierDiagnostics: policyOptions?.classifierDiagnostics,+ nightlyReview: policyOptions?.nightlyReview,+ procedure: procedurePolicyOptions,+ selfIterationIntent: policyOptions?.selfIterationIntent,+ selfReflection: policyOptions?.selfReflection,+ userMemory: {+ db: context.db,+ ...policyOptions?.userMemory,+ userId: context.userId,+ },+ skillManagement: {+ db: context.db,+ ...policyOptions?.skillManagement,+ selfIterationEnabled: policyOptions?.skillManagement?.selfIterationEnabled ?? false,+ userId: context.userId,+ },+ skillIntentClassifier: {+ db: context.db,+ ...policyOptions?.skillIntentClassifier,+ userId: context.userId,+ },+ };+};+const executeAgentSignalSourceEventCore = async <TSourceType extends AgentSignalSourceType>(input: AgentSignalSourceEventInput<TSourceType>,context: AgentSignalExecutionContext,@@ -111,37 +188,9 @@ const executeAgentSignalSourceEventCore = async <TSourceType extends AgentSignalconst runtime = await createAgentSignalRuntime({guardBackend: options.runtimeGuardBackend,- policies: createDefaultAgentSignalPolicies({- feedbackDomainJudge: {- db: context.db,- ...options.policyOptions?.feedbackDomainJudge,- userId: context.userId,- },- feedbackSatisfactionJudge: {- db: context.db,- ...options.policyOptions?.feedbackSatisfactionJudge,- userId: context.userId,- },- classifierDiagnostics: options.policyOptions?.classifierDiagnostics,- procedure: procedurePolicyOptions,- userMemory: {- db: context.db,- ...options.policyOptions?.userMemory,- userId: context.userId,- },- skillManagement: {- db: context.db,- ...options.policyOptions?.skillManagement,- selfIterationEnabled:- options.policyOptions?.skillManagement?.selfIterationEnabled ?? false,- userId: context.userId,- },- skillIntentClassifier: {- db: context.db,- ...options.policyOptions?.skillIntentClassifier,- userId: context.userId,- },- }),+ policies: createDefaultAgentSignalPolicies(+ createPolicyOptions(context, options, procedurePolicyOptions),+ ),});const runtimeResult = await runtime.emitNormalized(emission.source);const orchestration = buildRuntimeOrchestrationResult(emission.source, runtimeResult);@@ -192,7 +241,7 @@ export const executeAgentSignalSourceEvent = async <TSourceType extends AgentSig* Emits one source event using an injected store for eval and test coverage.** Use when:- * - The caller needs the exact production orchestration path but with isolated in-memory dedupe state+ * - The caller needs the exact server orchestration path but with isolated in-memory dedupe state* - Eval or test code must avoid ambient Redis dependencies** Expects:diff --git a/src/server/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts b/src/server/services/agentSignal/policies/analyzeIntent/actions/skillManagement.tsindex 6abdff54f89..dd8dc3654d2 100644--- a/src/server/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts+++ b/src/server/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts@@ -55,6 +55,7 @@ import type {import type { RuntimeProcessorContext } from '../../../runtime/context';import { defineActionHandler } from '../../../runtime/middleware';+import { createSkillManagementService } from '../../../services/maintenance/skill';import { hasAppliedActionIdempotency, markAppliedActionIdempotency } from '../../actionIdempotency';import type { ActionSkillManagementHandle, AgentSignalFeedbackEvidence } from '../../types';import { AGENT_SIGNAL_POLICY_ACTION_TYPES } from '../../types';@@ -1244,6 +1245,7 @@ const runMaintainerWorkflow = async (};}+ const agentId = input.agentId;const targetSkillRefs = getSkillTargets(decision);const minimumTargets = decision.action === 'consolidate' ? 2 : 1;@@ -1256,7 +1258,7 @@ const runMaintainerWorkflow = async (}const service =- options.skillManagementServiceFactory?.({ agentId: input.agentId }) ??+ options.skillManagementServiceFactory?.({ agentId }) ??createDefaultSkillManagementService(options);const workflowRunner =options.skillMaintainerRunner ??@@ -1266,7 +1268,7 @@ const runMaintainerWorkflow = async (options.userId,options.skillDecisionModel,).run(workflowInput));- const targetSkills = await readTargetSkills(service, input.agentId, targetSkillRefs);+ const targetSkills = await readTargetSkills(service, agentId, targetSkillRefs);if (targetSkills.length < minimumTargets) {return {@@ -1304,25 +1306,83 @@ const runMaintainerWorkflow = async (let updatedSkill: SkillDetail | SkillSummary = canonical;try {- if (workflowResult.rename?.newName || workflowResult.rename?.newTitle) {- updatedSkill =- (await service.renameSkill({- agentDocumentId: canonical.bundle.agentDocumentId,- agentId: input.agentId,- newName: workflowResult.rename.newName,- newTitle: workflowResult.rename.newTitle,- updateReason: workflowResult.reason,- })) ?? updatedSkill;- }+ const skillMaintenanceService = createSkillManagementService({+ consolidateSkill: async () => {+ if (workflowResult.rename?.newName || workflowResult.rename?.newTitle) {+ updatedSkill =+ (await service.renameSkill({+ agentDocumentId: canonical.bundle.agentDocumentId,+ agentId,+ newName: workflowResult.rename.newName,+ newTitle: workflowResult.rename.newTitle,+ updateReason: workflowResult.reason,+ })) ?? updatedSkill;+ }++ updatedSkill =+ (await service.replaceSkillIndex({+ agentDocumentId: canonical.bundle.agentDocumentId,+ agentId,+ bodyMarkdown: workflowResult.bodyMarkdown,+ description: workflowResult.description,+ updateReason: workflowResult.reason,+ })) ?? updatedSkill;++ return {+ skillDocumentId: canonical.bundle.agentDocumentId,+ summary: workflowResult.reason,+ };+ },+ refineSkill: async () => {+ if (workflowResult.rename?.newName || workflowResult.rename?.newTitle) {+ updatedSkill =+ (await service.renameSkill({+ agentDocumentId: canonical.bundle.agentDocumentId,+ agentId,+ newName: workflowResult.rename.newName,+ newTitle: workflowResult.rename.newTitle,+ updateReason: workflowResult.reason,+ })) ?? updatedSkill;+ }++ updatedSkill =+ (await service.replaceSkillIndex({+ agentDocumentId: canonical.bundle.agentDocumentId,+ agentId,+ bodyMarkdown: workflowResult.bodyMarkdown,+ description: workflowResult.description,+ updateReason: workflowResult.reason,+ })) ?? updatedSkill;++ return {+ skillDocumentId: canonical.bundle.agentDocumentId,+ summary: workflowResult.reason,+ };+ },+ });- updatedSkill =- (await service.replaceSkillIndex({- agentDocumentId: canonical.bundle.agentDocumentId,- agentId: input.agentId,- bodyMarkdown: workflowResult.bodyMarkdown,- description: workflowResult.description,- updateReason: workflowResult.reason,- })) ?? updatedSkill;+ if (decision.action === 'consolidate') {+ await skillMaintenanceService.consolidateSkill({+ evidenceRefs: [],+ idempotencyKey: `same-turn-skill:${canonical.bundle.agentDocumentId}`,+ input: {+ approval: { source: 'same_turn_feedback' },+ canonicalSkillDocumentId: canonical.bundle.agentDocumentId,+ sourceSkillIds: targetSkillRefs,+ userId: options.userId,+ },+ });+ } else {+ await skillMaintenanceService.refineSkill({+ evidenceRefs: [],+ idempotencyKey: `same-turn-skill:${canonical.bundle.agentDocumentId}`,+ input: {+ patch: workflowResult.bodyMarkdown,+ skillDocumentId: canonical.bundle.agentDocumentId,+ userId: options.userId,+ },+ });+ }} catch (error) {return {decision,@@ -1374,6 +1434,7 @@ const runCreateWorkflow = async (};}+ const agentId = input.agentId;const source = await readCreateSourceDocument(input, options, decision);const createRunner =options.skillCreateRunner ??@@ -1394,24 +1455,46 @@ const runCreateWorkflow = async (),);const service =- options.skillManagementServiceFactory?.({ agentId: input.agentId }) ??+ options.skillManagementServiceFactory?.({ agentId }) ??createDefaultSkillManagementService(options);try {- const skill = await service.createSkill({- agentId: input.agentId,- bodyMarkdown: authored.bodyMarkdown,- description: authored.description,- name: authored.name,- sourceAgentDocumentId: source.sourceAgentDocumentId,- title: authored.title ?? authored.name,+ let createdSkill: SkillDetail | undefined;+ const skillMaintenanceService = createSkillManagementService({+ createSkill: async () => {+ const skill = await service.createSkill({+ agentId,+ bodyMarkdown: authored.bodyMarkdown,+ description: authored.description,+ name: authored.name,+ sourceAgentDocumentId: source.sourceAgentDocumentId,+ title: authored.title ?? authored.name,+ });+ createdSkill = skill;++ return {+ skillDocumentId: skill.bundle.agentDocumentId,+ summary: authored.reason,+ };+ },+ });+ await skillMaintenanceService.createSkill({+ evidenceRefs: [],+ idempotencyKey: `same-turn-skill:create:${authored.name}`,+ input: {+ bodyMarkdown: authored.bodyMarkdown,+ description: authored.description,+ name: authored.name,+ title: authored.title ?? authored.name,+ userId: options.userId,+ },});return {decision,detail: authored.reason ?? `Created skill ${authored.name}.`,status: 'applied',- target: toSkillActionTarget(skill),+ target: createdSkill ? toSkillActionTarget(createdSkill) : undefined,};} catch (error) {if (error instanceof Error && error.message.includes('already exists')) {diff --git a/src/server/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts b/src/server/services/agentSignal/policies/analyzeIntent/actions/userMemory.tsindex a270c9685fe..81566e097ea 100644--- a/src/server/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts+++ b/src/server/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts@@ -25,6 +25,10 @@ import { AgentService } from '@/server/services/agent';import type { RuntimeProcessorContext } from '../../../runtime/context';import { defineActionHandler } from '../../../runtime/middleware';+import {+ createMemoryMaintenanceService,+ MemoryMaintenanceActionError,+} from '../../../services/maintenance/memory';import { hasAppliedActionIdempotency, markAppliedActionIdempotency } from '../../actionIdempotency';import type {ActionUserMemoryHandle,@@ -205,7 +209,7 @@ const hasFailedMemoryWrite = (state: AgentState) => {);};-const runMemoryActionAgent = async (+export const runMemoryActionAgent = async (input: {agentId?: string;conflictPolicy?: AgentSignalFeedbackDomainConflictPolicy;@@ -392,16 +396,18 @@ export const handleUserMemoryAction = async (};}- const runner = options.memoryActionRunner ?? ((input) => runMemoryActionAgent(input, options));- const result = await runner({+ const feedbackHint =+ action.payload.feedbackHint === 'satisfied' || action.payload.feedbackHint === 'not_satisfied'+ ? action.payload.feedbackHint+ : undefined;+ const runnerInput = {agentId: typeof action.payload.agentId === 'string' ? action.payload.agentId : undefined,conflictPolicy:typeof action.payload.conflictPolicy === 'object' && action.payload.conflictPolicy? action.payload.conflictPolicy: undefined,evidence: Array.isArray(action.payload.evidence) ? action.payload.evidence : undefined,- feedbackHint:- action.payload.feedbackHint === 'satisfied' ? 'satisfied' : action.payload.feedbackHint,+ feedbackHint,message,reason: typeof action.payload.reason === 'string' ? action.payload.reason : undefined,serializedContext:@@ -413,8 +419,50 @@ export const handleUserMemoryAction = async (? action.payload.sourceHints: undefined,topicId: typeof action.payload.topicId === 'string' ? action.payload.topicId : undefined,+ };+ const runner = options.memoryActionRunner ?? ((input) => runMemoryActionAgent(input, options));+ const memoryService = createMemoryMaintenanceService({+ writeMemory: async () => {+ const result = await runner(runnerInput);++ if (result.status === 'applied') {+ return {+ memoryId: idempotencyKey ?? action.actionId,+ summary: result.detail,+ };+ }++ throw new MemoryMaintenanceActionError(+ result.detail ?? 'Memory action agent did not apply a durable memory write.',+ result.status,+ );+ },});+ const result = await memoryService+ .writeMemory({+ evidenceRefs: [],+ idempotencyKey: idempotencyKey ?? action.actionId,+ input: {+ content: message,+ userId: options.userId,+ },+ })+ .then<MemoryAgentActionResult>((writeResult) => ({+ detail: writeResult.summary,+ status: 'applied',+ }))+ .catch((error: unknown): MemoryAgentActionResult => {+ if (error instanceof MemoryMaintenanceActionError) {+ return {+ detail: error.message,+ status: error.status,+ };+ }++ throw error;+ });+if (result.status === 'applied') {await markAppliedActionIdempotency(context, idempotencyKey);diff --git a/src/server/services/agentSignal/policies/index.ts b/src/server/services/agentSignal/policies/index.tsindex bcbc84bbc34..de5282b6407 100644--- a/src/server/services/agentSignal/policies/index.ts+++ b/src/server/services/agentSignal/policies/index.ts@@ -7,6 +7,8 @@ import type {} from './analyzeIntent/actions';import type { CreateFeedbackDomainJudgePolicyOptions } from './analyzeIntent/feedbackDomain';import type { CreateFeedbackSatisfactionJudgePolicyOptions } from './analyzeIntent/feedbackSatisfaction';+import type { CreateReviewNightlyPolicyOptions } from './reviewNightly';+import { createReviewNightlyPolicy } from './reviewNightly';export * from './actionIdempotency';export * from './analyzeIntent';@@ -15,19 +17,52 @@ export * from './analyzeIntent/feedbackAction';export * from './analyzeIntent/feedbackDomain';export * from './analyzeIntent/feedbackDomainAgent';export * from './analyzeIntent/feedbackSatisfaction';+export * from './reviewNightly';export * from './types';export interface CreateDefaultAgentSignalPoliciesOptions extends CreateFeedbackDomainJudgePolicyOptions {classifierDiagnostics?: CreateAnalyzeIntentPolicyOptions['classifierDiagnostics'];feedbackSatisfactionJudge?: CreateFeedbackSatisfactionJudgePolicyOptions;+ nightlyReview?: CreateReviewNightlyPolicyOptions['nightlyReview'];procedure?: CreateAnalyzeIntentPolicyOptions['procedure'];+ selfIterationIntent?: CreateReviewNightlyPolicyOptions['selfIterationIntent'];+ selfReflection?: CreateReviewNightlyPolicyOptions['selfReflection'];skillIntentClassifier?: CreateAnalyzeIntentPolicyOptions['skillIntentClassifier'];skillManagement?: SkillManagementActionHandlerOptions;userMemory?: UserMemoryActionHandlerOptions;}+type DefaultAgentSignalPolicyFactory = (+ options: CreateDefaultAgentSignalPoliciesOptions,+) => AgentSignalMiddleware[];++const DEFAULT_AGENT_SIGNAL_POLICY_FACTORIES: DefaultAgentSignalPolicyFactory[] = [+ (options) => [createAnalyzeIntentPolicy(options)],+ (options) =>+ createReviewNightlyPolicy({+ nightlyReview: options.nightlyReview,+ selfIterationIntent: options.selfIterationIntent,+ selfReflection: options.selfReflection,+ }),+];++/**+ * Creates the default Agent Signal policy stack with optional maintenance source handlers.+ *+ * Use when:+ * - Runtime creation needs the standard analyze-intent policies+ * - Callers want to opt into nightly, self-reflection, or self-iteration maintenance handlers+ * with explicit handler options+ *+ * Expects:+ * - Optional maintenance options are complete bundles for their source handlers+ * - Missing optional options mean the corresponding source handler is not installed+ *+ * Returns:+ * - Middleware list that installs analyze-intent policies and enabled source handlers+ */export const createDefaultAgentSignalPolicies = (options: CreateDefaultAgentSignalPoliciesOptions = {},): AgentSignalMiddleware[] => {- return [createAnalyzeIntentPolicy(options)];+ return DEFAULT_AGENT_SIGNAL_POLICY_FACTORIES.flatMap((createPolicy) => createPolicy(options));};diff --git a/src/server/services/agentSignal/policies/reviewNightly/__tests__/nightlyReview.test.ts b/src/server/services/agentSignal/policies/reviewNightly/__tests__/nightlyReview.test.tsnew file mode 100644index 00000000000..79bef29b87d--- /dev/null+++ b/src/server/services/agentSignal/policies/reviewNightly/__tests__/nightlyReview.test.ts@@ -0,0 +1,481 @@+// @vitest-environment node+import { createSource } from '@lobechat/agent-signal';+import type { SourceAgentNightlyReviewRequested } from '@lobechat/agent-signal/source';+import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';+import { describe, expect, it, vi } from 'vitest';++import type {+ AgentSignalActionHandlerDefinition,+ AgentSignalSignalHandlerDefinition,+ AgentSignalSourceHandlerDefinition,+} from '../../../runtime/middleware';+import type { NightlyReviewContext } from '../../../services/maintenance/nightlyCollector';+import type {+ MaintenancePlan,+ MaintenancePlanDraft,+ MaintenanceReviewRunResult,+} from '../../../services/maintenance/types';+import {+ MaintenanceActionStatus,+ MaintenanceApplyMode,+ MaintenanceReviewScope,+ MaintenanceRisk,+ ReviewRunStatus,+} from '../../../services/maintenance/types';+import { createDefaultAgentSignalPolicies } from '../..';+import type { CreateNightlyReviewSourceHandlerDependencies } from '../nightlyReview';+import {+ createNightlyReviewSourceHandler,+ createNightlyReviewSourcePolicyHandler,+} from '../nightlyReview';++const reviewPayload = {+ agentId: 'agent-1',+ localDate: '2026-05-04',+ requestedAt: '2026-05-04T14:00:00.000Z',+ reviewWindowEnd: '2026-05-04T14:00:00.000Z',+ reviewWindowStart: '2026-05-03T14:00:00.000Z',+ timezone: 'Asia/Shanghai',+ userId: 'user-1',+};++const createReviewSource = (+ payload: Record<string, unknown> = reviewPayload,+ sourceType = AGENT_SIGNAL_SOURCE_TYPES.agentNightlyReviewRequested,+): SourceAgentNightlyReviewRequested =>+ createSource({+ payload,+ scope: { agentId: 'agent-1', userId: 'user-1' },+ scopeKey: 'agent:agent-1',+ sourceId: 'nightly-review:user-1:agent-1:2026-05-04',+ sourceType,+ timestamp: 100,+ }) as SourceAgentNightlyReviewRequested;++const reviewContext = {+ agentId: 'agent-1',+ managedSkills: [],+ relevantMemories: [],+ reviewWindowEnd: reviewPayload.reviewWindowEnd,+ reviewWindowStart: reviewPayload.reviewWindowStart,+ topics: [],+ userId: 'user-1',+} satisfies NightlyReviewContext;++const reviewDraft = {+ actions: [+ {+ actionType: 'noop',+ confidence: 0.9,+ evidenceRefs: [{ id: 'topic-1', type: 'topic' }],+ rationale: 'No maintenance needed.',+ },+ ],+ findings: [],+ summary: 'Quiet night.',+} satisfies MaintenancePlanDraft;++const reviewPlan = {+ actions: [+ {+ actionType: 'noop',+ applyMode: MaintenanceApplyMode.ProposalOnly,+ confidence: 0.9,+ dedupeKey: 'noop:quiet',+ evidenceRefs: [{ id: 'topic-1', type: 'topic' }],+ idempotencyKey: 'nightly-review:user-1:agent-1:2026-05-04:noop:quiet',+ rationale: 'No maintenance needed.',+ risk: MaintenanceRisk.Medium,+ },+ ],+ localDate: reviewPayload.localDate,+ plannerVersion: 'test-planner',+ reviewScope: MaintenanceReviewScope.Nightly,+ summary: 'Quiet night.',+} satisfies MaintenancePlan;++const executionResult = {+ actions: [+ {+ idempotencyKey: 'nightly-review:user-1:agent-1:2026-05-04:noop:quiet',+ status: MaintenanceActionStatus.Proposed,+ summary: 'No maintenance needed.',+ },+ ],+ status: ReviewRunStatus.Completed,+} satisfies MaintenanceReviewRunResult;++const createDependencies = (+ overrides: Partial<CreateNightlyReviewSourceHandlerDependencies> = {},+): CreateNightlyReviewSourceHandlerDependencies => ({+ acquireReviewGuard: vi.fn(async () => true),+ canRunReview: vi.fn(async () => true),+ collectContext: vi.fn(async () => reviewContext),+ executePlan: vi.fn(async () => executionResult),+ planReviewOutput: vi.fn(async () => reviewPlan),+ runMaintenanceReviewAgent: vi.fn(async () => reviewDraft),+ ...overrides,+});++describe('nightly review source handler', () => {+ /**+ * @example+ * expect(result.status).toBe('completed');+ */+ it('orchestrates collector reviewer planner and executor for a valid nightly source', async () => {+ const deps = createDependencies();+ const handler = createNightlyReviewSourceHandler(deps);++ const result = await handler.handle(createReviewSource());++ expect(deps.canRunReview).toHaveBeenCalledWith(+ expect.objectContaining({+ agentId: 'agent-1',+ guardKey: 'nightly-review:user-1:agent-1:2026-05-04',+ localDate: '2026-05-04',+ userId: 'user-1',+ }),+ );+ expect(deps.acquireReviewGuard).toHaveBeenCalledWith(+ expect.objectContaining({ guardKey: 'nightly-review:user-1:agent-1:2026-05-04' }),+ );+ expect(deps.collectContext).toHaveBeenCalledWith({+ agentId: 'agent-1',+ reviewWindowEnd: reviewPayload.reviewWindowEnd,+ reviewWindowStart: reviewPayload.reviewWindowStart,+ userId: 'user-1',+ });+ expect(deps.runMaintenanceReviewAgent).toHaveBeenCalledWith(reviewContext);+ expect(deps.planReviewOutput).toHaveBeenCalledWith({+ draft: reviewDraft,+ localDate: '2026-05-04',+ reviewScope: MaintenanceReviewScope.Nightly,+ sourceId: 'nightly-review:user-1:agent-1:2026-05-04',+ userId: 'user-1',+ });+ expect(deps.executePlan).toHaveBeenCalledWith(reviewPlan);+ expect(result).toEqual(+ expect.objectContaining({+ agentId: 'agent-1',+ execution: expect.objectContaining({ status: executionResult.status }),+ plannedActionCount: 1,+ planSummary: 'Quiet night.',+ sourceId: 'nightly-review:user-1:agent-1:2026-05-04',+ status: ReviewRunStatus.Completed,+ userId: 'user-1',+ }),+ );+ });++ /**+ * @example+ * expect(deps.writeReceipts).toHaveBeenCalledBefore(deps.writeDailyBrief).+ */+ it('writes review receipts before creating an eligible nightly brief', async () => {+ const calls: string[] = [];+ const deps = createDependencies({+ executePlan: vi.fn(async () => ({+ actions: [+ {+ idempotencyKey: 'nightly-review:user-1:agent-1:2026-05-04:noop:quiet',+ status: MaintenanceActionStatus.Proposed,+ summary: 'No maintenance needed.',+ },+ ],+ status: ReviewRunStatus.Completed,+ })),+ planReviewOutput: vi.fn(async () => {+ return {+ ...reviewPlan,+ actions: [+ {+ ...reviewPlan.actions[0],+ actionType: 'proposal_only',+ },+ ],+ } satisfies MaintenancePlan;+ }),+ writeDailyBrief: vi.fn(async () => {+ calls.push('brief');++ return { id: 'brief-1' };+ }),+ writeReceipts: vi.fn(async () => {+ calls.push('receipts');+ }),+ });+ const handler = createNightlyReviewSourceHandler(deps);++ const result = await handler.handle(createReviewSource());++ expect(calls).toEqual(['receipts', 'brief']);+ expect(deps.writeReceipts).toHaveBeenCalledWith([+ expect.objectContaining({ id: 'nightly-review:user-1:agent-1:2026-05-04:review-summary' }),+ expect.objectContaining({+ id: 'nightly-review:user-1:agent-1:2026-05-04:noop:quiet:action',+ }),+ ]);+ expect(deps.writeDailyBrief).toHaveBeenCalledWith(+ expect.objectContaining({+ agentId: 'agent-1',+ metadata: expect.objectContaining({+ evidenceRefs: [{ id: 'topic-1', type: 'topic' }],+ }),+ trigger: 'agent-signal:nightly-review',+ type: 'decision',+ }),+ );+ expect(result.execution).toEqual(+ expect.objectContaining({+ briefId: 'brief-1',+ summaryReceiptId: 'nightly-review:user-1:agent-1:2026-05-04:review-summary',+ }),+ );+ });++ /**+ * @example+ * expect(result.briefWriteFailed).toBe(true);+ */+ it('keeps nightly runs completed when brief creation fails after receipts', async () => {+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});+ const briefError = new Error('brief store unavailable');+ const deps = createDependencies({+ planReviewOutput: vi.fn(async () => {+ return {+ ...reviewPlan,+ actions: [+ {+ ...reviewPlan.actions[0],+ actionType: 'proposal_only',+ },+ ],+ } satisfies MaintenancePlan;+ }),+ writeDailyBrief: vi.fn(async () => {+ throw briefError;+ }),+ writeReceipts: vi.fn(async () => {}),+ });+ const handler = createNightlyReviewSourceHandler(deps);++ const result = await handler.handle(createReviewSource());++ expect(result).toEqual(+ expect.objectContaining({+ briefWriteFailed: true,+ status: ReviewRunStatus.Completed,+ }),+ );+ expect(consoleError).toHaveBeenCalledWith(+ '[AgentSignal] Failed to write nightly review brief:',+ briefError,+ );+ consoleError.mockRestore();+ });++ /**+ * @example+ * expect(result.status).toBe('deduped');+ */+ it('returns deduped without collecting when the review guard is already held', async () => {+ const deps = createDependencies({+ acquireReviewGuard: vi.fn(async () => false),+ });+ const handler = createNightlyReviewSourceHandler(deps);++ const result = await handler.handle(createReviewSource());++ expect(result).toEqual(+ expect.objectContaining({+ guardKey: 'nightly-review:user-1:agent-1:2026-05-04',+ status: ReviewRunStatus.Deduped,+ }),+ );+ expect(deps.collectContext).not.toHaveBeenCalled();+ expect(deps.runMaintenanceReviewAgent).not.toHaveBeenCalled();+ expect(deps.executePlan).not.toHaveBeenCalled();+ });++ /**+ * @example+ * expect(result.reason).toBe('gate_disabled');+ */+ it('returns skipped without acquiring the guard when gates reject the review', async () => {+ const deps = createDependencies({+ canRunReview: vi.fn(async () => false),+ });+ const handler = createNightlyReviewSourceHandler(deps);++ const result = await handler.handle(createReviewSource());++ expect(result).toEqual(+ expect.objectContaining({+ reason: 'gate_disabled',+ status: ReviewRunStatus.Skipped,+ }),+ );+ expect(deps.acquireReviewGuard).not.toHaveBeenCalled();+ expect(deps.collectContext).not.toHaveBeenCalled();+ });++ /**+ * @example+ * expect(result.reason).toBe('invalid_payload');+ */+ it('returns skipped invalid without throwing for invalid payloads', async () => {+ const deps = createDependencies();+ const handler = createNightlyReviewSourceHandler(deps);++ const result = await handler.handle(+ createReviewSource({ agentId: 'agent-1', userId: 'user-1' }),+ );++ expect(result).toEqual(+ expect.objectContaining({+ reason: 'invalid_payload',+ status: ReviewRunStatus.Skipped,+ }),+ );+ expect(deps.canRunReview).not.toHaveBeenCalled();+ expect(deps.acquireReviewGuard).not.toHaveBeenCalled();+ expect(deps.collectContext).not.toHaveBeenCalled();+ });++ /**+ * @example+ * expect(result.reason).toBe('invalid_payload');+ */+ it('returns skipped invalid when source id does not match the nightly guard key', async () => {+ const deps = createDependencies();+ const handler = createNightlyReviewSourceHandler(deps);++ const mismatchedSource = {+ ...createReviewSource(),+ sourceId: 'nightly-review:user-1:agent-1:wrong-date',+ } satisfies SourceAgentNightlyReviewRequested;+ const mismatchedResult = await handler.handle(mismatchedSource);++ expect(mismatchedResult).toEqual(+ expect.objectContaining({+ reason: 'invalid_payload',+ sourceId: 'nightly-review:user-1:agent-1:wrong-date',+ status: ReviewRunStatus.Skipped,+ }),+ );+ expect(deps.canRunReview).not.toHaveBeenCalled();+ expect(deps.acquireReviewGuard).not.toHaveBeenCalled();+ expect(deps.collectContext).not.toHaveBeenCalled();+ });++ /**+ * @example+ * expect(sourceHandlers[0].listen).toBe('agent.nightly_review.requested');+ */+ it('installs an optional nightly source policy through default policy composition', async () => {+ const sourceHandlers: AgentSignalSourceHandlerDefinition[] = [];+ const deps = createDependencies();+ const policies = createDefaultAgentSignalPolicies({+ feedbackSatisfactionJudge: {+ judge: {+ judgeSatisfaction: async () => ({+ confidence: 1,+ evidence: [],+ reason: 'No feedback in nightly registration test.',+ result: 'neutral',+ }),+ },+ },+ nightlyReview: deps,+ });++ for (const policy of policies) {+ await policy.install({+ handleAction(handler: AgentSignalActionHandlerDefinition) {+ expect(handler.type).toBe('action');+ },+ handleSignal(handler: AgentSignalSignalHandlerDefinition) {+ expect(handler.type).toBe('signal');+ },+ handleSource(handler) {+ sourceHandlers.push(handler);+ },+ });+ }++ const nightlyHandler = sourceHandlers.find(+ (handler) => handler.listen === AGENT_SIGNAL_SOURCE_TYPES.agentNightlyReviewRequested,+ );++ expect(nightlyHandler).toEqual(+ expect.objectContaining({+ id: `${AGENT_SIGNAL_SOURCE_TYPES.agentNightlyReviewRequested}:maintenance-review`,+ type: 'source',+ }),+ );++ const runtimeResult = await nightlyHandler?.handle(createReviewSource(), {+ now: () => 100,+ scopeKey: 'agent:agent-1',+ } as never);++ expect(runtimeResult).toEqual(+ expect.objectContaining({+ concluded: expect.objectContaining({ status: ReviewRunStatus.Completed }),+ status: 'conclude',+ }),+ );+ });++ /**+ * @example+ * expect(nightlyHandler).toBeUndefined();+ */+ it('does not install nightly source handlers without nightly review dependencies', async () => {+ const sourceHandlers: AgentSignalSourceHandlerDefinition[] = [];+ const policies = createDefaultAgentSignalPolicies({+ feedbackSatisfactionJudge: {+ judge: {+ judgeSatisfaction: async () => ({+ confidence: 1,+ evidence: [],+ reason: 'No feedback in nightly registration test.',+ result: 'neutral',+ }),+ },+ },+ });++ for (const policy of policies) {+ await policy.install({+ handleAction(handler: AgentSignalActionHandlerDefinition) {+ expect(handler.type).toBe('action');+ },+ handleSignal(handler: AgentSignalSignalHandlerDefinition) {+ expect(handler.type).toBe('signal');+ },+ handleSource(handler) {+ sourceHandlers.push(handler);+ },+ });+ }++ const nightlyHandler = sourceHandlers.find(+ (handler) => handler.listen === AGENT_SIGNAL_SOURCE_TYPES.agentNightlyReviewRequested,+ );++ expect(nightlyHandler).toBeUndefined();+ });+});++describe('nightly review source policy handler', () => {+ /**+ * @example+ * expect(handler.listen).toBe('agent.nightly_review.requested');+ */+ it('listens to the nightly review requested source type', () => {+ const handler = createNightlyReviewSourcePolicyHandler(createDependencies());++ expect(handler.listen).toBe(AGENT_SIGNAL_SOURCE_TYPES.agentNightlyReviewRequested);+ });+});diff --git a/src/server/services/agentSignal/policies/reviewNightly/__tests__/selfIterationIntent.test.ts b/src/server/services/agentSignal/policies/reviewNightly/__tests__/selfIterationIntent.test.tsnew file mode 100644index 00000000000..f423b5f4957--- /dev/null+++ b/src/server/services/agentSignal/policies/reviewNightly/__tests__/selfIterationIntent.test.ts@@ -0,0 +1,574 @@+// @vitest-environment node+import { createSource } from '@lobechat/agent-signal';+import type { SourceAgentSelfIterationIntentDeclared } from '@lobechat/agent-signal/source';+import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';+import { describe, expect, it, vi } from 'vitest';++import type { RuntimeProcessorContext } from '../../../runtime/context';+import type {+ AgentSignalActionHandlerDefinition,+ AgentSignalSignalHandlerDefinition,+ AgentSignalSourceHandlerDefinition,+} from '../../../runtime/middleware';+import { createMaintenancePlannerService } from '../../../services/maintenance/planner';+import type { EvidenceRef, MaintenancePlan } from '../../../services/maintenance/types';+import {+ MaintenanceActionStatus,+ MaintenanceApplyMode,+ MaintenanceReviewScope,+ ReviewRunStatus,+} from '../../../services/maintenance/types';+import { createDefaultAgentSignalPolicies } from '../..';+import type { CreateSelfIterationIntentSourceHandlerDependencies } from '../selfIterationIntent';+import {+ createSelfIterationIntentSourceHandler,+ createSelfIterationIntentSourcePolicyHandler,+} from '../selfIterationIntent';++const intentPayload = {+ action: 'write',+ agentId: 'agent-1',+ confidence: 0.94,+ evidenceRefs: [+ {+ id: 'msg-1',+ summary: 'User asked to remember concise release summaries.',+ type: 'message',+ },+ ],+ kind: 'memory',+ reason: 'The user gave a durable preference.',+ summary: 'User prefers concise release summaries.',+ toolCallId: 'tool-call-1',+ topicId: 'topic-1',+ userId: 'user-1',+} as const;++const intentSourceId = 'self-iteration-intent:user-1:agent-1:topic:topic-1:tool-call-1';++const topicEvidence = {+ id: 'topic-1',+ summary: 'Current topic context.',+ type: 'topic',+} satisfies EvidenceRef;++const conflictEvidence = {+ id: 'msg-stop',+ summary: 'User said do not remember this.',+ type: 'message',+} satisfies EvidenceRef;++const runtimeContext = {+ now: () => 100,+ runtimeState: {+ getGuardState: async () => ({}),+ touchGuardState: async () => ({}),+ },+ scopeKey: 'agent:agent-1',+} satisfies RuntimeProcessorContext;++const createIntentSource = (+ payload: Record<string, unknown> = intentPayload,+ sourceId = intentSourceId,+ sourceType = AGENT_SIGNAL_SOURCE_TYPES.agentSelfIterationIntentDeclared,+): SourceAgentSelfIterationIntentDeclared =>+ createSource({+ payload,+ scope: { agentId: 'agent-1', userId: 'user-1' },+ scopeKey: 'topic:topic-1',+ sourceId,+ sourceType,+ timestamp: 100,+ }) as SourceAgentSelfIterationIntentDeclared;++const createDependencies = (+ overrides: Partial<CreateSelfIterationIntentSourceHandlerDependencies> = {},+): CreateSelfIterationIntentSourceHandlerDependencies => {+ const planner = createMaintenancePlannerService({ plannerVersion: 'test-planner' });++ return {+ acquireReviewGuard: vi.fn(async () => true),+ canRunReview: vi.fn(async () => true),+ enrichEvidence: vi.fn(async () => ({+ evidenceRefs: [topicEvidence],+ })),+ executePlan: vi.fn(async (plan: MaintenancePlan) => ({+ actions: plan.actions.map((action) => ({+ idempotencyKey: action.idempotencyKey,+ status:+ action.applyMode === MaintenanceApplyMode.AutoApply+ ? MaintenanceActionStatus.Applied+ : action.applyMode === MaintenanceApplyMode.ProposalOnly+ ? MaintenanceActionStatus.Proposed+ : MaintenanceActionStatus.Skipped,+ summary: action.rationale,+ })),+ status: ReviewRunStatus.Completed,+ })),+ planReviewOutput: vi.fn((request) => planner.plan(request)),+ writeReceipt: vi.fn(async () => {}),+ ...overrides,+ };+};++describe('self-iteration intent source handler', () => {+ /**+ * @example+ * expect(executedPlan.actions[0].applyMode).toBe('auto_apply');+ */+ it('lets strong evidence memory intent become auto-apply through the planner', async () => {+ const deps = createDependencies();+ const handler = createSelfIterationIntentSourceHandler(deps);++ const result = await handler.handle(createIntentSource());++ expect(deps.enrichEvidence).toHaveBeenCalledWith({+ action: 'write',+ agentId: 'agent-1',+ kind: 'memory',+ operationId: undefined,+ scopeId: 'topic-1',+ scopeType: 'topic',+ toolCallId: 'tool-call-1',+ topicId: 'topic-1',+ userId: 'user-1',+ });+ expect(deps.planReviewOutput).toHaveBeenCalledWith({+ draft: {+ actions: [+ expect.objectContaining({+ actionType: 'write_memory',+ confidence: 0.94,+ evidenceRefs: [+ intentPayload.evidenceRefs[0],+ { id: 'topic-1', summary: 'Current topic context.', type: 'topic' },+ ],+ target: { topicIds: ['topic-1'] },+ value: {+ content: 'User prefers concise release summaries.',+ reason: 'The user gave a durable preference.',+ userId: 'user-1',+ },+ }),+ ],+ findings: [],+ summary: 'User prefers concise release summaries.',+ },+ reviewScope: MaintenanceReviewScope.SelfIterationIntent,+ sourceId: intentSourceId,+ userId: 'user-1',+ });+ expect(deps.executePlan).toHaveBeenCalledWith(+ expect.objectContaining({+ actions: [+ expect.objectContaining({+ actionType: 'write_memory',+ applyMode: MaintenanceApplyMode.AutoApply,+ operation: expect.objectContaining({+ input: expect.objectContaining({+ content: 'User prefers concise release summaries.',+ userId: 'user-1',+ }),+ }),+ }),+ ],+ }),+ );+ expect(result).toEqual(+ expect.objectContaining({+ execution: expect.objectContaining({ status: ReviewRunStatus.Completed }),+ plannedActionCount: 1,+ planSummary: 'User prefers concise release summaries.',+ sourceId: intentSourceId,+ status: ReviewRunStatus.Completed,+ }),+ );+ });++ /**+ * @example+ * expect(executedPlan.actions[0].applyMode).toBe('skip');+ */+ it('skips evidence-poor memory intent through the real planner', async () => {+ const deps = createDependencies({+ enrichEvidence: vi.fn(async () => ({ evidenceRefs: [] })),+ });+ const handler = createSelfIterationIntentSourceHandler(deps);++ await handler.handle(+ createIntentSource({+ ...intentPayload,+ confidence: 0.78,+ evidenceRefs: [],+ summary: 'Maybe remember terse summaries.',+ }),+ );++ expect(deps.executePlan).toHaveBeenCalledWith(+ expect.objectContaining({+ actions: [+ expect.objectContaining({+ actionType: 'write_memory',+ applyMode: MaintenanceApplyMode.Skip,+ }),+ ],+ }),+ );+ });++ /**+ * @example+ * expect(executedPlan.actions[0].applyMode).toBe('proposal_only');+ */+ it('keeps high-risk consolidation intent proposal-only', async () => {+ const deps = createDependencies();+ const handler = createSelfIterationIntentSourceHandler(deps);++ await handler.handle(+ createIntentSource({+ ...intentPayload,+ action: 'consolidate',+ confidence: 0.99,+ evidenceRefs: [{ id: 'skill-1', type: 'agent_document' }],+ kind: 'skill',+ skillId: 'skill-1',+ summary: 'Merge overlapping planning skills.',+ }),+ );++ expect(deps.executePlan).toHaveBeenCalledWith(+ expect.objectContaining({+ actions: [+ expect.objectContaining({+ actionType: 'consolidate_skill',+ applyMode: MaintenanceApplyMode.ProposalOnly,+ operation: expect.objectContaining({+ input: expect.objectContaining({+ canonicalSkillDocumentId: 'skill-1',+ sourceSkillIds: ['skill-1'],+ userId: 'user-1',+ }),+ }),+ target: expect.objectContaining({ skillDocumentId: 'skill-1' }),+ }),+ ],+ }),+ );+ });++ /**+ * @example+ * expect(executedPlan.actions[0].actionType).toBe('proposal_only');+ */+ it('keeps skill refinement without a target skill id as proposal-only', async () => {+ const deps = createDependencies();+ const handler = createSelfIterationIntentSourceHandler(deps);++ await handler.handle(+ createIntentSource({+ ...intentPayload,+ action: 'refine',+ confidence: 0.96,+ evidenceRefs: [{ id: 'msg-2', type: 'message' }],+ kind: 'skill',+ summary: 'Refine an unspecified skill.',+ }),+ );++ expect(deps.executePlan).toHaveBeenCalledWith(+ expect.objectContaining({+ actions: [+ expect.objectContaining({+ actionType: 'proposal_only',+ applyMode: MaintenanceApplyMode.ProposalOnly,+ operation: undefined,+ }),+ ],+ }),+ );+ });++ /**+ * @example+ * expect(executedPlan.actions[0].applyMode).toBe('skip');+ */+ it('skips intent that conflicts with explicit user instruction', async () => {+ const deps = createDependencies({+ enrichEvidence: vi.fn(async () => ({+ evidenceRefs: [conflictEvidence],+ hasUserInstructionConflict: true,+ })),+ });+ const handler = createSelfIterationIntentSourceHandler(deps);++ await handler.handle(createIntentSource());++ expect(deps.executePlan).toHaveBeenCalledWith(+ expect.objectContaining({+ actions: [+ expect.objectContaining({+ applyMode: MaintenanceApplyMode.Skip,+ confidence: 0,+ evidenceRefs: [],+ rationale: expect.stringContaining('explicit user instruction'),+ }),+ ],+ }),+ );+ });++ /**+ * @example+ * expect(deps.writeReceipt).toHaveBeenCalledTimes(1);+ */+ it('keeps completed runs completed when receipt writing fails', async () => {+ const receiptError = new Error('receipt store unavailable');+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});+ const deps = createDependencies({+ writeReceipt: vi.fn(async () => {+ throw receiptError;+ }),+ });+ const handler = createSelfIterationIntentSourceHandler(deps);++ const result = await handler.handle(createIntentSource());++ expect(result).toEqual(+ expect.objectContaining({+ execution: expect.objectContaining({ status: ReviewRunStatus.Completed }),+ status: ReviewRunStatus.Completed,+ }),+ );+ expect(consoleError).toHaveBeenCalledWith(+ '[AgentSignal] Failed to write self-iteration intent receipt:',+ receiptError,+ );+ consoleError.mockRestore();+ });++ /**+ * @example+ * expect(deps.writeReceipts).toHaveBeenCalledWith(expect.arrayContaining([...])).+ */+ it('writes durable review and action receipts for declared intent runs', async () => {+ const deps = createDependencies({ writeReceipts: vi.fn(async () => {}) });+ const handler = createSelfIterationIntentSourceHandler(deps);++ const result = await handler.handle(createIntentSource());++ expect(deps.writeReceipts).toHaveBeenCalledWith([+ expect.objectContaining({ id: `${intentSourceId}:review-summary` }),+ expect.objectContaining({+ id: `${intentSourceId}:write_memory:memory:User prefers concise release summaries.:action`,+ }),+ ]);+ expect(result.execution).toEqual(+ expect.objectContaining({+ summaryReceiptId: `${intentSourceId}:review-summary`,+ }),+ );+ });++ /**+ * @example+ * expect(result.reason).toBe('invalid_payload');+ */+ it('requires the service-emitted tool call id for stable source verification', async () => {+ const deps = createDependencies();+ const handler = createSelfIterationIntentSourceHandler(deps);++ const result = await handler.handle(+ createIntentSource({+ ...intentPayload,+ toolCallId: undefined,+ }),+ );++ expect(result).toEqual(+ expect.objectContaining({+ reason: 'invalid_payload',+ status: ReviewRunStatus.Skipped,+ }),+ );+ expect(deps.canRunReview).not.toHaveBeenCalled();+ expect(deps.executePlan).not.toHaveBeenCalled();+ });++ /**+ * @example+ * expect(result.status).toBe('skipped');+ */+ it('skips without enrichment or execution when the review gate is disabled', async () => {+ const deps = createDependencies({+ canRunReview: vi.fn(async () => false),+ });+ const handler = createSelfIterationIntentSourceHandler(deps);++ const result = await handler.handle(createIntentSource());++ expect(result).toEqual(+ expect.objectContaining({+ reason: 'gate_disabled',+ status: ReviewRunStatus.Skipped,+ }),+ );+ expect(deps.acquireReviewGuard).not.toHaveBeenCalled();+ expect(deps.enrichEvidence).not.toHaveBeenCalled();+ expect(deps.executePlan).not.toHaveBeenCalled();+ });++ /**+ * @example+ * expect(result.status).toBe('deduped');+ */+ it('dedupes without enrichment or execution when the declaration guard already exists', async () => {+ const deps = createDependencies({+ acquireReviewGuard: vi.fn(async () => false),+ });+ const handler = createSelfIterationIntentSourceHandler(deps);++ const result = await handler.handle(createIntentSource());++ expect(result).toEqual(+ expect.objectContaining({+ guardKey: intentSourceId,+ status: ReviewRunStatus.Deduped,+ }),+ );+ expect(deps.enrichEvidence).not.toHaveBeenCalled();+ expect(deps.executePlan).not.toHaveBeenCalled();+ });++ /**+ * @example+ * expect(deps.executePlan).toHaveBeenCalledWith(expect.objectContaining({ actions: expect.any(Array) }));+ */+ it('validates operation-scoped source ids and forwards operation context', async () => {+ const deps = createDependencies();+ const handler = createSelfIterationIntentSourceHandler(deps);+ const operationSourceId =+ 'self-iteration-intent:user-1:agent-1:operation:operation-1:tool-call-1';++ await handler.handle(+ createIntentSource(+ {+ ...intentPayload,+ operationId: 'operation-1',+ },+ operationSourceId,+ ),+ );++ expect(deps.enrichEvidence).toHaveBeenCalledWith(+ expect.objectContaining({+ operationId: 'operation-1',+ scopeId: 'operation-1',+ scopeType: 'operation',+ topicId: 'topic-1',+ }),+ );+ expect(deps.executePlan).toHaveBeenCalledWith(+ expect.objectContaining({+ actions: [+ expect.objectContaining({+ idempotencyKey: expect.stringContaining(operationSourceId),+ }),+ ],+ }),+ );+ });++ /**+ * @example+ * expect(result.reason).toBe('invalid_payload');+ */+ it('returns skipped invalid when source id does not match the expected declaration key', async () => {+ const deps = createDependencies();+ const handler = createSelfIterationIntentSourceHandler(deps);++ const result = await handler.handle(+ createIntentSource(intentPayload, 'self-iteration-intent:wrong'),+ );++ expect(result).toEqual(+ expect.objectContaining({+ reason: 'invalid_payload',+ sourceId: 'self-iteration-intent:wrong',+ status: ReviewRunStatus.Skipped,+ }),+ );+ expect(deps.canRunReview).not.toHaveBeenCalled();+ expect(deps.executePlan).not.toHaveBeenCalled();+ });++ /**+ * @example+ * expect(sourceHandlers[0].listen).toBe('agent.self_iteration_intent.declared');+ */+ it('installs an optional self-iteration intent source policy through default policy composition', async () => {+ const sourceHandlers: AgentSignalSourceHandlerDefinition[] = [];+ const deps = createDependencies();+ const policies = createDefaultAgentSignalPolicies({+ feedbackSatisfactionJudge: {+ judge: {+ judgeSatisfaction: async () => ({+ confidence: 1,+ evidence: [],+ reason: 'No feedback in self-iteration registration test.',+ result: 'neutral',+ }),+ },+ },+ selfIterationIntent: deps,+ });++ for (const policy of policies) {+ await policy.install({+ handleAction(handler: AgentSignalActionHandlerDefinition) {+ expect(handler.type).toBe('action');+ },+ handleSignal(handler: AgentSignalSignalHandlerDefinition) {+ expect(handler.type).toBe('signal');+ },+ handleSource(handler) {+ sourceHandlers.push(handler);+ },+ });+ }++ const selfIterationIntentHandler = sourceHandlers.find(+ (handler) => handler.listen === AGENT_SIGNAL_SOURCE_TYPES.agentSelfIterationIntentDeclared,+ );++ expect(selfIterationIntentHandler).toEqual(+ expect.objectContaining({+ id: `${AGENT_SIGNAL_SOURCE_TYPES.agentSelfIterationIntentDeclared}:maintenance-review`,+ type: 'source',+ }),+ );++ const runtimeResult = await selfIterationIntentHandler?.handle(+ createIntentSource(),+ runtimeContext,+ );++ expect(runtimeResult).toEqual(+ expect.objectContaining({+ concluded: expect.objectContaining({ status: ReviewRunStatus.Completed }),+ status: 'conclude',+ }),+ );+ });+});++describe('self-iteration intent source policy handler', () => {+ /**+ * @example+ * expect(handler.listen).toBe('agent.self_iteration_intent.declared');+ */+ it('listens to the self-iteration intent declared source type', () => {+ const handler = createSelfIterationIntentSourcePolicyHandler(createDependencies());++ expect(handler.listen).toBe(AGENT_SIGNAL_SOURCE_TYPES.agentSelfIterationIntentDeclared);+ });+});diff --git a/src/server/services/agentSignal/policies/reviewNightly/__tests__/selfReflection.test.ts b/src/server/services/agentSignal/policies/reviewNightly/__tests__/selfReflection.test.tsnew file mode 100644index 00000000000..76fbea75f36--- /dev/null+++ b/src/server/services/agentSignal/policies/reviewNightly/__tests__/selfReflection.test.ts@@ -0,0 +1,584 @@+// @vitest-environment node+import { createSource } from '@lobechat/agent-signal';+import type { SourceAgentSelfReflectionRequested } from '@lobechat/agent-signal/source';+import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';+import { describe, expect, it, vi } from 'vitest';++import type { RuntimeProcessorContext } from '../../../runtime/context';+import type {+ AgentSignalActionHandlerDefinition,+ AgentSignalSignalHandlerDefinition,+ AgentSignalSourceHandlerDefinition,+} from '../../../runtime/middleware';+import type {+ MaintenancePlan,+ MaintenancePlanDraft,+ MaintenanceReviewRunResult,+} from '../../../services/maintenance/types';+import {+ MaintenanceActionStatus,+ MaintenanceApplyMode,+ MaintenanceReviewScope,+ MaintenanceRisk,+ ReviewRunStatus,+} from '../../../services/maintenance/types';+import { createDefaultAgentSignalPolicies } from '../..';+import type {+ CreateSelfReflectionSourceHandlerDependencies,+ SelfReflectionReviewContext,+} from '../selfReflection';+import {+ createSelfReflectionSourceHandler,+ createSelfReflectionSourcePolicyHandler,+} from '../selfReflection';++const reflectionPayload = {+ agentId: 'agent-1',+ operationId: 'operation-1',+ reason: 'failed_tool_count',+ scopeId: 'task-1',+ scopeType: 'task',+ taskId: 'task-1',+ topicId: 'topic-1',+ userId: 'user-1',+ windowEnd: '2026-05-04T14:30:00.000Z',+ windowStart: '2026-05-04T14:00:00.000Z',+} as const;++const reflectionSourceId =+ 'self-reflection:user-1:agent-1:task:task-1:failed_tool_count:2026-05-04T14:00:00.000Z:2026-05-04T14:30:00.000Z';++const runtimeContext = {+ now: () => 100,+ runtimeState: {+ getGuardState: async () => ({}),+ touchGuardState: async () => ({}),+ },+ scopeKey: 'agent:agent-1',+} satisfies RuntimeProcessorContext;++const createReflectionSource = (+ payload: Record<string, unknown> = reflectionPayload,+ sourceType = AGENT_SIGNAL_SOURCE_TYPES.agentSelfReflectionRequested,+): SourceAgentSelfReflectionRequested =>+ createSource({+ payload,+ scope: { agentId: 'agent-1', userId: 'user-1' },+ scopeKey: 'agent:agent-1',+ sourceId: reflectionSourceId,+ sourceType,+ timestamp: 100,+ }) as SourceAgentSelfReflectionRequested;++const reflectionContext = {+ agentId: 'agent-1',+ evidence: [{ id: 'task-1', type: 'task' }],+ operationId: 'operation-1',+ scopeId: 'task-1',+ scopeType: 'task',+ taskId: 'task-1',+ topicId: 'topic-1',+ userId: 'user-1',+ windowEnd: reflectionPayload.windowEnd,+ windowStart: reflectionPayload.windowStart,+} satisfies SelfReflectionReviewContext;++const reflectionDraft = {+ actions: [+ {+ actionType: 'write_memory',+ confidence: 0.9,+ evidenceRefs: [{ id: 'task-1', type: 'task' }],+ rationale: 'The task exposed a durable preference.',+ value: { content: 'User prefers scoped task follow-up.' },+ },+ ],+ findings: [],+ summary: 'Task-scoped reflection found one durable preference.',+} satisfies MaintenancePlanDraft;++const reflectionPlan = {+ actions: [+ {+ actionType: 'write_memory',+ applyMode: MaintenanceApplyMode.AutoApply,+ confidence: 0.9,+ dedupeKey: 'memory:User prefers scoped task follow-up.',+ evidenceRefs: [{ id: 'task-1', type: 'task' }],+ idempotencyKey: `${reflectionSourceId}:write_memory:memory:User prefers scoped task follow-up.`,+ operation: {+ domain: 'memory',+ input: { content: 'User prefers scoped task follow-up.', userId: 'user-1' },+ operation: 'write',+ },+ rationale: 'The task exposed a durable preference.',+ risk: MaintenanceRisk.Low,+ },+ ],+ plannerVersion: 'test-planner',+ reviewScope: MaintenanceReviewScope.SelfReflection,+ summary: 'Task-scoped reflection found one durable preference.',+} satisfies MaintenancePlan;++const executionResult = {+ actions: [+ {+ idempotencyKey: `${reflectionSourceId}:write_memory:memory:User prefers scoped task follow-up.`,+ receiptId: 'receipt-1',+ status: MaintenanceActionStatus.Applied,+ summary: 'Memory written.',+ },+ ],+ status: ReviewRunStatus.Completed,+} satisfies MaintenanceReviewRunResult;++const createDependencies = (+ overrides: Partial<CreateSelfReflectionSourceHandlerDependencies> = {},+): CreateSelfReflectionSourceHandlerDependencies => ({+ acquireReviewGuard: vi.fn(async () => true),+ canRunReview: vi.fn(async () => true),+ collectContext: vi.fn(async () => reflectionContext),+ executePlan: vi.fn(async () => executionResult),+ planReviewOutput: vi.fn(async () => reflectionPlan),+ runMaintenanceReviewAgent: vi.fn(async () => reflectionDraft),+ writeReceipt: vi.fn(async () => {}),+ ...overrides,+});++describe('self-reflection source handler', () => {+ /**+ * @example+ * expect(result.status).toBe('completed');+ */+ it('orchestrates scoped collector reviewer planner executor and receipt writer', async () => {+ const deps = createDependencies();+ const handler = createSelfReflectionSourceHandler(deps);++ const result = await handler.handle(createReflectionSource());++ expect(deps.canRunReview).toHaveBeenCalledWith(+ expect.objectContaining({+ agentId: 'agent-1',+ guardKey: reflectionSourceId,+ reason: 'failed_tool_count',+ scopeId: 'task-1',+ scopeType: 'task',+ userId: 'user-1',+ }),+ );+ expect(deps.acquireReviewGuard).toHaveBeenCalledWith(+ expect.objectContaining({ guardKey: reflectionSourceId }),+ );+ expect(deps.collectContext).toHaveBeenCalledWith({+ agentId: 'agent-1',+ operationId: 'operation-1',+ scopeId: 'task-1',+ scopeType: 'task',+ taskId: 'task-1',+ topicId: 'topic-1',+ userId: 'user-1',+ windowEnd: reflectionPayload.windowEnd,+ windowStart: reflectionPayload.windowStart,+ });+ expect(deps.runMaintenanceReviewAgent).toHaveBeenCalledWith(reflectionContext);+ expect(deps.planReviewOutput).toHaveBeenCalledWith({+ draft: reflectionDraft,+ reviewScope: MaintenanceReviewScope.SelfReflection,+ sourceId: reflectionSourceId,+ userId: 'user-1',+ });+ expect(deps.executePlan).toHaveBeenCalledWith(reflectionPlan);+ expect(deps.writeReceipt).toHaveBeenCalledWith({+ execution: expect.objectContaining({+ status: executionResult.status,+ summaryReceiptId: `${reflectionSourceId}:review-summary`,+ }),+ plan: reflectionPlan,+ reason: 'failed_tool_count',+ scopeId: 'task-1',+ scopeType: 'task',+ sourceId: reflectionSourceId,+ });+ expect(result).toEqual(+ expect.objectContaining({+ agentId: 'agent-1',+ execution: expect.objectContaining({ status: executionResult.status }),+ plannedActionCount: 1,+ planSummary: 'Task-scoped reflection found one durable preference.',+ sourceId: reflectionSourceId,+ status: ReviewRunStatus.Completed,+ userId: 'user-1',+ }),+ );+ });++ /**+ * @example+ * expect(executedPlan.actions[0].applyMode).toBe('proposal_only');+ */+ it('passes SelfReflection scope so consolidate skill drafts stay proposal-only', async () => {+ const consolidateDraft = {+ actions: [+ {+ actionType: 'consolidate_skill',+ confidence: 0.99,+ evidenceRefs: [+ { id: 'skill-a', type: 'agent_document' },+ { id: 'skill-b', type: 'agent_document' },+ ],+ rationale: 'Two managed skills overlap.',+ target: { skillDocumentId: 'skill-a' },+ value: { sourceSkillIds: ['skill-a', 'skill-b'] },+ },+ ],+ findings: [],+ summary: 'Overlap found.',+ } satisfies MaintenancePlanDraft;+ const proposalOnlyPlan = {+ actions: [+ {+ actionType: 'consolidate_skill',+ applyMode: MaintenanceApplyMode.ProposalOnly,+ confidence: 0.99,+ dedupeKey: 'skill:skill-a',+ evidenceRefs: [+ { id: 'skill-a', type: 'agent_document' },+ { id: 'skill-b', type: 'agent_document' },+ ],+ idempotencyKey: `${reflectionSourceId}:consolidate_skill:skill:skill-a`,+ operation: {+ domain: 'skill',+ input: {+ canonicalSkillDocumentId: 'skill-a',+ sourceSkillIds: ['skill-a', 'skill-b'],+ userId: 'user-1',+ },+ operation: 'consolidate',+ },+ rationale: 'Two managed skills overlap.',+ risk: MaintenanceRisk.High,+ target: { skillDocumentId: 'skill-a' },+ },+ ],+ plannerVersion: 'test-planner',+ reviewScope: MaintenanceReviewScope.SelfReflection,+ summary: 'Overlap found.',+ } satisfies MaintenancePlan;+ const deps = createDependencies({+ executePlan: vi.fn(async () => ({+ actions: [+ {+ idempotencyKey: `${reflectionSourceId}:consolidate_skill:skill:skill-a`,+ status: MaintenanceActionStatus.Proposed,+ summary: 'Two managed skills overlap.',+ },+ ],+ status: ReviewRunStatus.Completed,+ })),+ planReviewOutput: vi.fn(async () => proposalOnlyPlan),+ runMaintenanceReviewAgent: vi.fn(async () => consolidateDraft),+ });+ const handler = createSelfReflectionSourceHandler(deps);++ await handler.handle(createReflectionSource());++ expect(deps.planReviewOutput).toHaveBeenCalledWith({+ draft: consolidateDraft,+ reviewScope: MaintenanceReviewScope.SelfReflection,+ sourceId: reflectionSourceId,+ userId: 'user-1',+ });+ expect(deps.executePlan).toHaveBeenCalledWith(+ expect.objectContaining({+ actions: [+ expect.objectContaining({+ actionType: 'consolidate_skill',+ applyMode: MaintenanceApplyMode.ProposalOnly,+ }),+ ],+ }),+ );+ });++ /**+ * @example+ * expect(deps.writeReceipt).toHaveBeenCalledTimes(1);+ */+ it('emits receipts without requiring a daily brief dependency', async () => {+ const deps = createDependencies({ writeReceipts: vi.fn(async () => {}) });+ const handler = createSelfReflectionSourceHandler(deps);++ await handler.handle(createReflectionSource());++ expect(deps.writeReceipts).toHaveBeenCalledWith([+ expect.objectContaining({ id: `${reflectionSourceId}:review-summary` }),+ expect.objectContaining({+ id: `${reflectionSourceId}:write_memory:memory:User prefers scoped task follow-up.:action`,+ }),+ ]);+ expect(deps.writeReceipt).toHaveBeenCalledTimes(1);+ expect('writeDailyBrief' in deps).toBe(false);+ });++ /**+ * @example+ * expect(result.status).toBe('completed');+ */+ it('keeps applied self-reflection runs completed when receipt writing fails', async () => {+ const receiptError = new Error('receipt store unavailable');+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});+ const deps = createDependencies({+ writeReceipt: vi.fn(async () => {+ throw receiptError;+ }),+ });+ const handler = createSelfReflectionSourceHandler(deps);++ const result = await handler.handle(createReflectionSource());++ expect(deps.executePlan).toHaveBeenCalledWith(reflectionPlan);+ expect(result).toEqual(+ expect.objectContaining({+ execution: expect.objectContaining({ status: executionResult.status }),+ status: ReviewRunStatus.Completed,+ }),+ );+ expect(consoleError).toHaveBeenCalledWith(+ '[AgentSignal] Failed to write self-reflection receipt:',+ receiptError,+ );+ consoleError.mockRestore();+ });++ /**+ * @example+ * expect(result.status).toBe('deduped');+ */+ it('returns deduped without collecting when the review guard is already held', async () => {+ const deps = createDependencies({+ acquireReviewGuard: vi.fn(async () => false),+ });+ const handler = createSelfReflectionSourceHandler(deps);++ const result = await handler.handle(createReflectionSource());++ expect(result).toEqual(+ expect.objectContaining({+ guardKey: reflectionSourceId,+ status: ReviewRunStatus.Deduped,+ }),+ );+ expect(deps.collectContext).not.toHaveBeenCalled();+ expect(deps.runMaintenanceReviewAgent).not.toHaveBeenCalled();+ expect(deps.executePlan).not.toHaveBeenCalled();+ expect(deps.writeReceipt).not.toHaveBeenCalled();+ });++ /**+ * @example+ * expect(result.reason).toBe('gate_disabled');+ */+ it('returns skipped without acquiring the guard when gates reject the review', async () => {+ const deps = createDependencies({+ canRunReview: vi.fn(async () => false),+ });+ const handler = createSelfReflectionSourceHandler(deps);++ const result = await handler.handle(createReflectionSource());++ expect(result).toEqual(+ expect.objectContaining({+ reason: 'gate_disabled',+ status: ReviewRunStatus.Skipped,+ }),+ );+ expect(deps.acquireReviewGuard).not.toHaveBeenCalled();+ expect(deps.collectContext).not.toHaveBeenCalled();+ });++ /**+ * @example+ * expect(result.reason).toBe('invalid_payload');+ */+ it('returns skipped invalid without throwing for invalid payloads', async () => {+ const deps = createDependencies();+ const handler = createSelfReflectionSourceHandler(deps);++ const result = await handler.handle(+ createReflectionSource({ agentId: 'agent-1', userId: 'user-1' }),+ );++ expect(result).toEqual(+ expect.objectContaining({+ reason: 'invalid_payload',+ status: ReviewRunStatus.Skipped,+ }),+ );+ expect(deps.canRunReview).not.toHaveBeenCalled();+ expect(deps.acquireReviewGuard).not.toHaveBeenCalled();+ expect(deps.collectContext).not.toHaveBeenCalled();+ });++ /**+ * @example+ * expect(result.reason).toBe('invalid_payload');+ */+ it('returns skipped invalid when scope type is outside the supported set', async () => {+ const deps = createDependencies();+ const handler = createSelfReflectionSourceHandler(deps);++ const result = await handler.handle(+ createReflectionSource({+ ...reflectionPayload,+ scopeType: 'session',+ }),+ );++ expect(result).toEqual(+ expect.objectContaining({+ reason: 'invalid_payload',+ status: ReviewRunStatus.Skipped,+ }),+ );+ expect(deps.canRunReview).not.toHaveBeenCalled();+ });++ /**+ * @example+ * expect(result.reason).toBe('invalid_payload');+ */+ it('returns skipped invalid when source id does not match the expected self-reflection key', async () => {+ const deps = createDependencies();+ const handler = createSelfReflectionSourceHandler(deps);++ const mismatchedSource = {+ ...createReflectionSource(),+ sourceId:+ 'self-reflection:user-1:agent-1:task:task-1:wrong:2026-05-04T14:00:00.000Z:2026-05-04T14:30:00.000Z',+ } satisfies SourceAgentSelfReflectionRequested;+ const result = await handler.handle(mismatchedSource);++ expect(result).toEqual(+ expect.objectContaining({+ reason: 'invalid_payload',+ sourceId:+ 'self-reflection:user-1:agent-1:task:task-1:wrong:2026-05-04T14:00:00.000Z:2026-05-04T14:30:00.000Z',+ status: ReviewRunStatus.Skipped,+ }),+ );+ expect(deps.canRunReview).not.toHaveBeenCalled();+ expect(deps.acquireReviewGuard).not.toHaveBeenCalled();+ expect(deps.collectContext).not.toHaveBeenCalled();+ });++ /**+ * @example+ * expect(sourceHandlers[0].listen).toBe('agent.self_reflection.requested');+ */+ it('installs an optional self-reflection source policy through default policy composition', async () => {+ const sourceHandlers: AgentSignalSourceHandlerDefinition[] = [];+ const deps = createDependencies();+ const policies = createDefaultAgentSignalPolicies({+ feedbackSatisfactionJudge: {+ judge: {+ judgeSatisfaction: async () => ({+ confidence: 1,+ evidence: [],+ reason: 'No feedback in self-reflection registration test.',+ result: 'neutral',+ }),+ },+ },+ selfReflection: deps,+ });++ for (const policy of policies) {+ await policy.install({+ handleAction(handler: AgentSignalActionHandlerDefinition) {+ expect(handler.type).toBe('action');+ },+ handleSignal(handler: AgentSignalSignalHandlerDefinition) {+ expect(handler.type).toBe('signal');+ },+ handleSource(handler) {+ sourceHandlers.push(handler);+ },+ });+ }++ const selfReflectionHandler = sourceHandlers.find(+ (handler) => handler.listen === AGENT_SIGNAL_SOURCE_TYPES.agentSelfReflectionRequested,+ );++ expect(selfReflectionHandler).toEqual(+ expect.objectContaining({+ id: `${AGENT_SIGNAL_SOURCE_TYPES.agentSelfReflectionRequested}:maintenance-review`,+ type: 'source',+ }),+ );++ const runtimeResult = await selfReflectionHandler?.handle(+ createReflectionSource(),+ runtimeContext,+ );++ expect(runtimeResult).toEqual(+ expect.objectContaining({+ concluded: expect.objectContaining({ status: ReviewRunStatus.Completed }),+ status: 'conclude',+ }),+ );+ });++ /**+ * @example+ * expect(selfReflectionHandler).toBeUndefined();+ */+ it('does not install self-reflection source handlers without self-reflection dependencies', async () => {+ const sourceHandlers: AgentSignalSourceHandlerDefinition[] = [];+ const policies = createDefaultAgentSignalPolicies({+ feedbackSatisfactionJudge: {+ judge: {+ judgeSatisfaction: async () => ({+ confidence: 1,+ evidence: [],+ reason: 'No feedback in self-reflection registration test.',+ result: 'neutral',+ }),+ },+ },+ });++ for (const policy of policies) {+ await policy.install({+ handleAction(handler: AgentSignalActionHandlerDefinition) {+ expect(handler.type).toBe('action');+ },+ handleSignal(handler: AgentSignalSignalHandlerDefinition) {+ expect(handler.type).toBe('signal');+ },+ handleSource(handler) {+ sourceHandlers.push(handler);+ },+ });+ }++ const selfReflectionHandler = sourceHandlers.find(+ (handler) => handler.listen === AGENT_SIGNAL_SOURCE_TYPES.agentSelfReflectionRequested,+ );++ expect(selfReflectionHandler).toBeUndefined();+ });+});++describe('self-reflection source policy handler', () => {+ /**+ * @example+ * expect(handler.listen).toBe('agent.self_reflection.requested');+ */+ it('listens to the self-reflection requested source type', () => {+ const handler = createSelfReflectionSourcePolicyHandler(createDependencies());++ expect(handler.listen).toBe(AGENT_SIGNAL_SOURCE_TYPES.agentSelfReflectionRequested);+ });+});diff --git a/src/server/services/agentSignal/policies/reviewNightly/index.ts b/src/server/services/agentSignal/policies/reviewNightly/index.tsnew file mode 100644index 00000000000..1d39e7859f1--- /dev/null+++ b/src/server/services/agentSignal/policies/reviewNightly/index.ts@@ -0,0 +1,58 @@+import type { AgentSignalHandlerDefinition, AgentSignalMiddleware } from '../../runtime/middleware';+import { defineAgentSignalHandlers } from '../../runtime/middleware';+import type { CreateNightlyReviewSourceHandlerDependencies } from './nightlyReview';+import { createNightlyReviewSourcePolicyHandler } from './nightlyReview';+import type { CreateSelfIterationIntentSourceHandlerDependencies } from './selfIterationIntent';+import { createSelfIterationIntentSourcePolicyHandler } from './selfIterationIntent';+import type { CreateSelfReflectionSourceHandlerDependencies } from './selfReflection';+import { createSelfReflectionSourcePolicyHandler } from './selfReflection';++const createOptionalSourceHandler = <TOptions>(+ options: TOptions | undefined,+ create: (options: TOptions) => AgentSignalHandlerDefinition,+) => (options ? [create(options)] : []);++/**+ * Options for composing review-nightly maintenance source handlers.+ */+export interface CreateReviewNightlyPolicyOptions {+ /** Optional nightly review source handler options. */+ nightlyReview?: CreateNightlyReviewSourceHandlerDependencies;+ /** Optional self-iteration intent source handler options. */+ selfIterationIntent?: CreateSelfIterationIntentSourceHandlerDependencies;+ /** Optional self-reflection source handler options. */+ selfReflection?: CreateSelfReflectionSourceHandlerDependencies;+}++/**+ * Creates the Agent Signal policy slice for deferred maintenance reviews.+ *+ * Use when:+ * - Runtime creation wants to install nightly review source handlers+ * - Runtime creation wants self-reflection or self-iteration intent handlers in the same domain+ *+ * Expects:+ * - Each optional handler option bundle is complete for its corresponding source handler+ * - Missing optional bundles mean that source handler is intentionally not installed+ *+ * Returns:+ * - Zero or one middleware that registers all enabled review-nightly source handlers+ */+export const createReviewNightlyPolicy = (+ options: CreateReviewNightlyPolicyOptions = {},+): AgentSignalMiddleware[] => {+ const handlers = [+ ...createOptionalSourceHandler(options.nightlyReview, createNightlyReviewSourcePolicyHandler),+ ...createOptionalSourceHandler(options.selfReflection, createSelfReflectionSourcePolicyHandler),+ ...createOptionalSourceHandler(+ options.selfIterationIntent,+ createSelfIterationIntentSourcePolicyHandler,+ ),+ ];++ return handlers.length > 0 ? [defineAgentSignalHandlers(handlers)] : [];+};++export * from './nightlyReview';+export * from './selfIterationIntent';+export * from './selfReflection';diff --git a/src/server/services/agentSignal/policies/reviewNightly/nightlyReview.ts b/src/server/services/agentSignal/policies/reviewNightly/nightlyReview.tsnew file mode 100644index 00000000000..86398dee2a3--- /dev/null+++ b/src/server/services/agentSignal/policies/reviewNightly/nightlyReview.ts@@ -0,0 +1,408 @@+import type { SourceAgentNightlyReviewRequested } from '@lobechat/agent-signal/source';+import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';++import { defineSourceHandler } from '../../runtime/middleware';+import type { MaintenanceBriefProjection } from '../../services/maintenance/brief';+import { createBriefMaintenanceService } from '../../services/maintenance/brief';+import type {+ CollectNightlyReviewContextInput,+ NightlyReviewContext,+} from '../../services/maintenance/nightlyCollector';+import type {+ EvidenceRef,+ MaintenancePlan,+ MaintenancePlanDraft,+ MaintenancePlanRequest,+ MaintenanceReviewRunResult,+} from '../../services/maintenance/types';+import {+ buildNightlyReviewSourceId,+ MaintenanceReviewScope,+ ReviewRunStatus,+} from '../../services/maintenance/types';+import type { AgentSignalReceipt } from '../../services/receiptService';+import { createMaintenanceReviewReceipts } from '../../services/receiptService';++/**+ * Validated nightly review request payload consumed by the handler.+ */+export interface NightlyReviewSourcePayload {+ /** Stable agent id being reviewed. */+ agentId: string;+ /** User-local date in YYYY-MM-DD form. */+ localDate: string;+ /** ISO timestamp when the scheduler requested the review. */+ requestedAt: string;+ /** Review window end as an ISO string. */+ reviewWindowEnd: string;+ /** Review window start as an ISO string. */+ reviewWindowStart: string;+ /** IANA timezone used to compute the local nightly window. */+ timezone: string;+ /** Stable user id owning the agent. */+ userId: string;+}++/**+ * Idempotency and gate input shared by nightly review handler dependencies.+ */+export interface NightlyReviewSourceGuardInput extends NightlyReviewSourcePayload {+ /** Stable guard key for one user-agent local date review. */+ guardKey: string;+ /** Normalized source id that triggered the run. */+ sourceId: string;+}++/**+ * Result returned by the nightly review source handler.+ */+export interface NightlyReviewSourceHandlerResult extends Record<string, unknown> {+ /** Stable agent id being reviewed when payload validation succeeds. */+ agentId?: string;+ /** Whether Daily Brief creation failed after maintenance execution. */+ briefWriteFailed?: boolean;+ /** Executor result for completed runs. */+ execution?: MaintenanceReviewRunResult;+ /** Stable guard key used for idempotency when payload validation succeeds. */+ guardKey?: string;+ /** User-local date in YYYY-MM-DD form when payload validation succeeds. */+ localDate?: string;+ /** Number of planned maintenance actions before execution. */+ plannedActionCount?: number;+ /** Planner summary for future brief construction. */+ planSummary?: string;+ /** Machine-readable skip reason for non-completed runs. */+ reason?: 'gate_disabled' | 'invalid_payload';+ /** Review window end as an ISO string when payload validation succeeds. */+ reviewWindowEnd?: string;+ /** Review window start as an ISO string when payload validation succeeds. */+ reviewWindowStart?: string;+ /** Source id that triggered the run. */+ sourceId?: string;+ /** Coarse run status for observability and retry semantics. */+ status: ReviewRunStatus;+ /** Stable user id owning the agent when payload validation succeeds. */+ userId?: string;+}++/**+ * Dependencies required by the nightly review source handler.+ */+export interface CreateNightlyReviewSourceHandlerDependencies {+ /** Acquires the per-user-agent local date idempotency guard. */+ acquireReviewGuard: (input: NightlyReviewSourceGuardInput) => Promise<boolean>;+ /** Re-checks runtime gates before doing reviewer work. */+ canRunReview: (input: NightlyReviewSourceGuardInput) => Promise<boolean>;+ /** Collects bounded digest context without mutating maintenance resources. */+ collectContext: (input: CollectNightlyReviewContextInput) => Promise<NightlyReviewContext>;+ /** Applies only the planner-approved maintenance plan mutations. */+ executePlan: (plan: MaintenancePlan) => Promise<MaintenanceReviewRunResult>;+ /** Converts reviewer output into a deterministic maintenance plan. */+ planReviewOutput: (request: MaintenancePlanRequest) => MaintenancePlan | Promise<MaintenancePlan>;+ /** Runs the bounded maintenance reviewer against collected digest context. */+ runMaintenanceReviewAgent: (context: NightlyReviewContext) => Promise<MaintenancePlanDraft>;+ /** Writes a Daily Brief payload for user-visible nightly outcomes. */+ writeDailyBrief?: (brief: MaintenanceBriefProjection) => Promise<{ id?: string } | void>;+ /** Writes durable receipts for the review summary and action outcomes. */+ writeReceipts?: (receipts: AgentSignalReceipt[]) => Promise<void>;+}++const isNonEmptyString = (value: unknown): value is string =>+ typeof value === 'string' && value.length > 0;++const readNightlyReviewPayload = (+ source: SourceAgentNightlyReviewRequested,+): NightlyReviewSourcePayload | undefined => {+ if (source.sourceType !== AGENT_SIGNAL_SOURCE_TYPES.agentNightlyReviewRequested) return;++ const payload = source.payload;+ if (+ !isNonEmptyString(payload.agentId) ||+ !isNonEmptyString(payload.localDate) ||+ !isNonEmptyString(payload.requestedAt) ||+ !isNonEmptyString(payload.reviewWindowEnd) ||+ !isNonEmptyString(payload.reviewWindowStart) ||+ !isNonEmptyString(payload.timezone) ||+ !isNonEmptyString(payload.userId)+ ) {+ return;+ }++ return {+ agentId: payload.agentId,+ localDate: payload.localDate,+ requestedAt: payload.requestedAt,+ reviewWindowEnd: payload.reviewWindowEnd,+ reviewWindowStart: payload.reviewWindowStart,+ timezone: payload.timezone,+ userId: payload.userId,+ };+};++const toGuardInput = (+ payload: NightlyReviewSourcePayload,+ source: SourceAgentNightlyReviewRequested,+): NightlyReviewSourceGuardInput => {+ return {+ ...payload,+ guardKey: buildNightlyReviewSourceId({+ agentId: payload.agentId,+ localDate: payload.localDate,+ userId: payload.userId,+ }),+ sourceId: source.sourceId,+ };+};++const toBaseResult = (+ guardInput: NightlyReviewSourceGuardInput,+): Omit<NightlyReviewSourceHandlerResult, 'status'> => ({+ agentId: guardInput.agentId,+ guardKey: guardInput.guardKey,+ localDate: guardInput.localDate,+ reviewWindowEnd: guardInput.reviewWindowEnd,+ reviewWindowStart: guardInput.reviewWindowStart,+ sourceId: guardInput.sourceId,+ userId: guardInput.userId,+});++const applyReceiptIdsToExecution = (+ execution: MaintenanceReviewRunResult,+ receipts: AgentSignalReceipt[],+): MaintenanceReviewRunResult => {+ const receiptByActionKey = new Map(+ receipts+ .filter((receipt) => receipt.id.endsWith(':action'))+ .map((receipt) => [receipt.id.slice(0, -':action'.length), receipt.id]),+ );++ return {+ ...execution,+ actions: execution.actions.map((action) => ({+ ...action,+ ...(receiptByActionKey.get(action.idempotencyKey)+ ? { receiptId: receiptByActionKey.get(action.idempotencyKey) }+ : {}),+ })),+ summaryReceiptId: `${execution.sourceId ?? receipts[0]?.sourceId}:review-summary`,+ };+};++const collectPlanEvidenceRefs = (plan: MaintenancePlan): EvidenceRef[] => {+ const evidenceRefs = new Map<string, EvidenceRef>();++ for (const action of plan.actions) {+ for (const evidenceRef of action.evidenceRefs) {+ evidenceRefs.set(`${evidenceRef.type}:${evidenceRef.id}`, evidenceRef);+ }+ }++ return [...evidenceRefs.values()];+};++const writeNightlyReceipts = async (+ deps: CreateNightlyReviewSourceHandlerDependencies,+ receipts: AgentSignalReceipt[],+) => {+ if (!deps.writeReceipts || receipts.length === 0) return;++ try {+ await deps.writeReceipts(receipts);+ } catch (error) {+ console.error('[AgentSignal] Failed to write nightly review receipts:', error);+ }+};++const writeNightlyBrief = async (+ deps: CreateNightlyReviewSourceHandlerDependencies,+ brief: MaintenanceBriefProjection | undefined,+) => {+ if (!deps.writeDailyBrief || !brief) return {};++ try {+ const result = await deps.writeDailyBrief(brief);++ return result && result.id ? { briefId: result.id } : {};+ } catch (error) {+ console.error('[AgentSignal] Failed to write nightly review brief:', error);++ return { briefWriteFailed: true };+ }+};++/**+ * Creates the DI-friendly handler for nightly review request sources.+ *+ * Triggering workflow:+ *+ * {@link createNightlyReviewSourcePolicyHandler}+ * -> `agent.nightly_review.requested`+ * -> {@link createNightlyReviewSourceHandler}+ *+ * Upstream:+ * - `agent.nightly_review.requested`+ *+ * Downstream:+ * - injected `executePlan`+ *+ * Use when:+ * - Tests need to run the nightly review orchestration without DB or LLM dependencies+ * - Runtime policy composition needs a side-effect boundary before executing maintenance plans+ *+ * Expects:+ * - `source` is an `agent.nightly_review.requested` source with scheduler-produced payload+ * - Dependencies enforce gates, idempotency, reviewer limits, and executor persistence+ *+ * Returns:+ * - A run result with status and enough plan metadata for future brief builders+ */+export const createNightlyReviewSourceHandler = (+ deps: CreateNightlyReviewSourceHandlerDependencies,+) => ({+ handle: async (+ source: SourceAgentNightlyReviewRequested,+ ): Promise<NightlyReviewSourceHandlerResult> => {+ const payload = readNightlyReviewPayload(source);++ if (!payload) {+ return {+ reason: 'invalid_payload',+ sourceId: source.sourceId,+ status: ReviewRunStatus.Skipped,+ };+ }++ const guardInput = toGuardInput(payload, source);+ if (source.sourceId !== guardInput.guardKey) {+ return {+ reason: 'invalid_payload',+ sourceId: source.sourceId,+ status: ReviewRunStatus.Skipped,+ };+ }++ const baseResult = toBaseResult(guardInput);++ if (!(await deps.canRunReview(guardInput))) {+ return {+ ...baseResult,+ reason: 'gate_disabled',+ status: ReviewRunStatus.Skipped,+ };+ }++ if (!(await deps.acquireReviewGuard(guardInput))) {+ return {+ ...baseResult,+ status: ReviewRunStatus.Deduped,+ };+ }++ const context = await deps.collectContext({+ agentId: payload.agentId,+ reviewWindowEnd: payload.reviewWindowEnd,+ reviewWindowStart: payload.reviewWindowStart,+ userId: payload.userId,+ });+ const draft = await deps.runMaintenanceReviewAgent(context);+ const plan = await deps.planReviewOutput({+ draft,+ localDate: payload.localDate,+ reviewScope: MaintenanceReviewScope.Nightly,+ sourceId: source.sourceId,+ userId: payload.userId,+ });+ const execution = await deps.executePlan(plan);+ const receipts = createMaintenanceReviewReceipts({+ agentId: payload.agentId,+ createdAt: source.timestamp,+ localDate: payload.localDate,+ plan,+ result: {+ ...execution,+ sourceId: source.sourceId,+ },+ sourceId: source.sourceId,+ sourceType: source.sourceType,+ timezone: payload.timezone,+ userId: payload.userId,+ });+ const executionWithReceipts = applyReceiptIdsToExecution(+ {+ ...execution,+ sourceId: source.sourceId,+ },+ receipts,+ );++ await writeNightlyReceipts(deps, receipts);++ const brief = createBriefMaintenanceService().projectNightlyReviewBrief({+ agentId: payload.agentId,+ evidenceRefs: collectPlanEvidenceRefs(plan),+ localDate: payload.localDate,+ result: executionWithReceipts,+ reviewWindowEnd: payload.reviewWindowEnd,+ reviewWindowStart: payload.reviewWindowStart,+ timezone: payload.timezone,+ userId: payload.userId,+ });+ const briefResult = await writeNightlyBrief(deps, brief);++ return {+ ...baseResult,+ ...briefResult,+ execution: {+ ...executionWithReceipts,+ ...('briefId' in briefResult ? { briefId: briefResult.briefId } : {}),+ },+ plannedActionCount: plan.actions.length,+ planSummary: plan.summary,+ status: execution.status,+ };+ },+});++/**+ * Creates the runtime source handler definition for nightly review policy composition.+ *+ * Triggering workflow:+ *+ * {@link defineSourceHandler}+ * -> `agent.nightly_review.requested`+ * -> {@link createNightlyReviewSourcePolicyHandler}+ *+ * Upstream:+ * - `agent.nightly_review.requested`+ *+ * Downstream:+ * - {@link createNightlyReviewSourceHandler}+ *+ * Use when:+ * - Default Agent Signal policies are composed with nightly review dependencies+ * - The runtime source registry needs an installable source handler definition+ *+ * Expects:+ * - All server-only dependencies are injected by the caller+ *+ * Returns:+ * - A source handler that concludes the runtime chain with the review run metadata+ */+export const createNightlyReviewSourcePolicyHandler = (+ deps: CreateNightlyReviewSourceHandlerDependencies,+) => {+ const handler = createNightlyReviewSourceHandler(deps);++ return defineSourceHandler(+ AGENT_SIGNAL_SOURCE_TYPES.agentNightlyReviewRequested,+ `${AGENT_SIGNAL_SOURCE_TYPES.agentNightlyReviewRequested}:maintenance-review`,+ async (source: SourceAgentNightlyReviewRequested) => {+ const result = await handler.handle(source);++ return {+ concluded: result,+ status: 'conclude',+ };+ },+ );+};diff --git a/src/server/services/agentSignal/policies/reviewNightly/selfIterationIntent.ts b/src/server/services/agentSignal/policies/reviewNightly/selfIterationIntent.tsnew file mode 100644index 00000000000..7834df86bd5--- /dev/null+++ b/src/server/services/agentSignal/policies/reviewNightly/selfIterationIntent.ts@@ -0,0 +1,668 @@+import type { SourceAgentSelfIterationIntentDeclared } from '@lobechat/agent-signal/source';+import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';++import { defineSourceHandler } from '../../runtime/middleware';+import type {+ EvidenceRef,+ MaintenanceActionDraft,+ MaintenancePlan,+ MaintenancePlanDraft,+ MaintenancePlanRequest,+ MaintenanceReviewRunResult,+} from '../../services/maintenance/types';+import {+ buildSelfIterationIntentSourceId,+ MaintenanceReviewScope,+ ReviewRunStatus,+} from '../../services/maintenance/types';+import type { AgentSignalReceipt } from '../../services/receiptService';+import { createMaintenanceReviewReceipts } from '../../services/receiptService';++/** Source scope supported by self-iteration intent declarations. */+export type SelfIterationIntentSourceScopeType = 'operation' | 'topic';++/** Actions that an agent may declare as maintenance intent. */+export type SelfIterationIntentDeclaredAction =+ | 'write'+ | 'create'+ | 'refine'+ | 'consolidate'+ | 'proposal';++/** Maintenance target category declared by the running agent. */+export type SelfIterationIntentDeclaredKind = 'memory' | 'skill' | 'gap';++/**+ * Validated self-iteration intent source payload consumed by the handler.+ */+export interface SelfIterationIntentSourcePayload {+ /** Declared maintenance action. */+ action: SelfIterationIntentDeclaredAction;+ /** Stable agent id being reviewed. */+ agentId: string;+ /** Agent-declared confidence from 0 to 1. */+ confidence: number;+ /** Source-provided evidence references. */+ evidenceRefs: EvidenceRef[];+ /** Declared maintenance target category. */+ kind: SelfIterationIntentDeclaredKind;+ /** Existing memory id when the intent targets a memory. */+ memoryId?: string;+ /** Runtime operation id when the declaration is operation-scoped. */+ operationId?: string;+ /** Agent rationale for the declared intent. */+ reason: string;+ /** Scope id selected from operation or topic payload fields. */+ scopeId: string;+ /** Scope type selected from operation or topic payload fields. */+ scopeType: SelfIterationIntentSourceScopeType;+ /** Existing skill id when the intent targets a managed skill. */+ skillId?: string;+ /** Short declaration summary. */+ summary: string;+ /** Stable tool-call id used for source id verification. */+ toolCallId: string;+ /** Current topic id when available. */+ topicId?: string;+ /** Stable user id owning the agent. */+ userId: string;+}++/**+ * Idempotency and gate input shared by self-iteration intent handler dependencies.+ */+export interface SelfIterationIntentSourceGuardInput extends SelfIterationIntentSourcePayload {+ /** Stable guard key for one declaration source. */+ guardKey: string;+ /** Normalized source id that triggered the run. */+ sourceId: string;+}++/**+ * Context enrichment input for agent-declared self-iteration intent.+ */+export interface EnrichSelfIterationIntentEvidenceInput {+ /** Declared maintenance action. */+ action: SelfIterationIntentDeclaredAction;+ /** Stable agent id being reviewed. */+ agentId: string;+ /** Declared maintenance target category. */+ kind: SelfIterationIntentDeclaredKind;+ /** Runtime operation id when the declaration is operation-scoped. */+ operationId?: string;+ /** Scope id selected from operation or topic payload fields. */+ scopeId: string;+ /** Scope type selected from operation or topic payload fields. */+ scopeType: SelfIterationIntentSourceScopeType;+ /** Stable tool-call id used for source id verification. */+ toolCallId: string;+ /** Current topic id when available. */+ topicId?: string;+ /** Stable user id owning the agent. */+ userId: string;+}++/**+ * Extra evidence collected from the current operation or topic.+ */+export interface SelfIterationIntentEvidenceEnrichment {+ /** Additional evidence references to append before deterministic planning. */+ evidenceRefs: EvidenceRef[];+ /** Whether current context shows an explicit user instruction conflict. */+ hasUserInstructionConflict?: boolean;+}++/**+ * Receipt input emitted after one self-iteration intent maintenance execution.+ */+export interface SelfIterationIntentReceiptInput {+ /** Executor result for the completed declaration run. */+ execution: MaintenanceReviewRunResult;+ /** Normalized maintenance plan sent to the executor. */+ plan: MaintenancePlan;+ /** Runtime scope id reviewed by the run. */+ scopeId: string;+ /** Runtime scope family reviewed by the run. */+ scopeType: SelfIterationIntentSourceScopeType;+ /** Source id that triggered the run. */+ sourceId: string;+ /** Tool-call id that produced the declaration. */+ toolCallId: string;+}++/**+ * Result returned by the self-iteration intent source handler.+ */+export interface SelfIterationIntentSourceHandlerResult extends Record<string, unknown> {+ /** Stable agent id being reviewed when payload validation succeeds. */+ agentId?: string;+ /** Executor result for completed runs. */+ execution?: MaintenanceReviewRunResult;+ /** Stable guard key used for idempotency when payload validation succeeds. */+ guardKey?: string;+ /** Number of planned maintenance actions before execution. */+ plannedActionCount?: number;+ /** Planner summary for receipt construction. */+ planSummary?: string;+ /** Machine-readable skip reason for non-completed runs. */+ reason?: 'gate_disabled' | 'invalid_payload';+ /** Runtime scope id reviewed by the run. */+ scopeId?: string;+ /** Runtime scope family reviewed by the run. */+ scopeType?: SelfIterationIntentSourceScopeType;+ /** Source id that triggered the run. */+ sourceId?: string;+ /** Coarse run status for observability and retry semantics. */+ status: ReviewRunStatus;+ /** Tool-call id that produced the declaration. */+ toolCallId?: string;+ /** Stable user id owning the agent when payload validation succeeds. */+ userId?: string;+}++/**+ * Dependencies required by the self-iteration intent source handler.+ */+export interface CreateSelfIterationIntentSourceHandlerDependencies {+ /** Acquires the per-declaration idempotency guard. */+ acquireReviewGuard: (input: SelfIterationIntentSourceGuardInput) => Promise<boolean>;+ /** Re-checks runtime gates before doing reviewer work. */+ canRunReview: (input: SelfIterationIntentSourceGuardInput) => Promise<boolean>;+ /** Adds topic or operation evidence without mutating maintenance resources. */+ enrichEvidence?: (+ input: EnrichSelfIterationIntentEvidenceInput,+ ) => Promise<SelfIterationIntentEvidenceEnrichment>;+ /** Applies only the planner-approved maintenance plan mutations. */+ executePlan: (plan: MaintenancePlan) => Promise<MaintenanceReviewRunResult>;+ /** Converts declaration drafts into deterministic maintenance plans. */+ planReviewOutput: (request: MaintenancePlanRequest) => MaintenancePlan | Promise<MaintenancePlan>;+ /** Writes durable receipt metadata for the declaration run. */+ writeReceipt: (input: SelfIterationIntentReceiptInput) => Promise<void>;+ /** Writes durable receipt records for the review summary and action outcomes. */+ writeReceipts?: (receipts: AgentSignalReceipt[]) => Promise<void>;+}++const isNonEmptyString = (value: unknown): value is string =>+ typeof value === 'string' && value.length > 0;++const isValidConfidence = (value: unknown): value is number =>+ typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 1;++const isSelfIterationIntentAction = (value: unknown): value is SelfIterationIntentDeclaredAction =>+ value === 'write' ||+ value === 'create' ||+ value === 'refine' ||+ value === 'consolidate' ||+ value === 'proposal';++const isSelfIterationIntentKind = (value: unknown): value is SelfIterationIntentDeclaredKind =>+ value === 'memory' || value === 'skill' || value === 'gap';++const isEvidenceRefType = (value: unknown): value is EvidenceRef['type'] =>+ value === 'topic' ||+ value === 'message' ||+ value === 'operation' ||+ value === 'source' ||+ value === 'receipt' ||+ value === 'tool_call' ||+ value === 'task' ||+ value === 'agent_document' ||+ value === 'memory';++const readEvidenceRefs = (value: unknown): EvidenceRef[] => {+ if (!Array.isArray(value)) return [];++ return value.flatMap((item): EvidenceRef[] => {+ if (!item || typeof item !== 'object') return [];++ const id = 'id' in item ? item.id : undefined;+ const type = 'type' in item ? item.type : undefined;+ if (!isNonEmptyString(id) || !isEvidenceRefType(type)) return [];++ const summary = 'summary' in item ? item.summary : undefined;++ return [+ {+ id,+ ...(isNonEmptyString(summary) ? { summary } : {}),+ type,+ },+ ];+ });+};++const readSelfIterationIntentPayload = (+ source: SourceAgentSelfIterationIntentDeclared,+): SelfIterationIntentSourcePayload | undefined => {+ if (source.sourceType !== AGENT_SIGNAL_SOURCE_TYPES.agentSelfIterationIntentDeclared) return;++ const payload = source.payload;+ if (+ !isSelfIterationIntentAction(payload.action) ||+ !isNonEmptyString(payload.agentId) ||+ !isValidConfidence(payload.confidence) ||+ !isSelfIterationIntentKind(payload.kind) ||+ !isNonEmptyString(payload.reason) ||+ !isNonEmptyString(payload.summary) ||+ !isNonEmptyString(payload.toolCallId) ||+ !isNonEmptyString(payload.userId)+ ) {+ return;+ }++ const scope = isNonEmptyString(payload.operationId)+ ? ({ scopeId: payload.operationId, scopeType: 'operation' } as const)+ : isNonEmptyString(payload.topicId)+ ? ({ scopeId: payload.topicId, scopeType: 'topic' } as const)+ : undefined;++ if (!scope) return;++ return {+ action: payload.action,+ agentId: payload.agentId,+ confidence: payload.confidence,+ evidenceRefs: readEvidenceRefs(payload.evidenceRefs),+ kind: payload.kind,+ ...(isNonEmptyString(payload.memoryId) ? { memoryId: payload.memoryId } : {}),+ ...(isNonEmptyString(payload.operationId) ? { operationId: payload.operationId } : {}),+ reason: payload.reason,+ ...(isNonEmptyString(payload.skillId) ? { skillId: payload.skillId } : {}),+ scopeId: scope.scopeId,+ scopeType: scope.scopeType,+ summary: payload.summary,+ toolCallId: payload.toolCallId,+ ...(isNonEmptyString(payload.topicId) ? { topicId: payload.topicId } : {}),+ userId: payload.userId,+ };+};++const toGuardInput = (+ payload: SelfIterationIntentSourcePayload,+ source: SourceAgentSelfIterationIntentDeclared,+): SelfIterationIntentSourceGuardInput => {+ return {+ ...payload,+ guardKey: buildSelfIterationIntentSourceId({+ agentId: payload.agentId,+ scopeId: payload.scopeId,+ scopeType: payload.scopeType,+ toolCallId: payload.toolCallId,+ userId: payload.userId,+ }),+ sourceId: source.sourceId,+ };+};++const toEnrichEvidenceInput = (+ payload: SelfIterationIntentSourcePayload,+): EnrichSelfIterationIntentEvidenceInput => ({+ action: payload.action,+ agentId: payload.agentId,+ kind: payload.kind,+ ...(payload.operationId ? { operationId: payload.operationId } : {}),+ scopeId: payload.scopeId,+ scopeType: payload.scopeType,+ toolCallId: payload.toolCallId,+ ...(payload.topicId ? { topicId: payload.topicId } : {}),+ userId: payload.userId,+});++const toBaseResult = (+ guardInput: SelfIterationIntentSourceGuardInput,+): Omit<SelfIterationIntentSourceHandlerResult, 'status'> => ({+ agentId: guardInput.agentId,+ guardKey: guardInput.guardKey,+ scopeId: guardInput.scopeId,+ scopeType: guardInput.scopeType,+ sourceId: guardInput.sourceId,+ toolCallId: guardInput.toolCallId,+ userId: guardInput.userId,+});++const createDraftTarget = (+ payload: SelfIterationIntentSourcePayload,+): MaintenanceActionDraft['target'] => ({+ ...(payload.memoryId ? { memoryId: payload.memoryId } : {}),+ ...(payload.skillId ? { skillDocumentId: payload.skillId } : {}),+ ...(payload.topicId ? { topicIds: [payload.topicId] } : {}),+});++const createProposalDraft = (+ payload: SelfIterationIntentSourcePayload,+ evidenceRefs: EvidenceRef[],+ rationale: string,+): MaintenanceActionDraft => ({+ actionType: 'proposal_only',+ confidence: payload.confidence,+ evidenceRefs,+ rationale,+ target: createDraftTarget(payload),+ value: {+ action: payload.action,+ kind: payload.kind,+ reason: payload.reason,+ summary: payload.summary,+ },+});++const createActionDraft = (+ payload: SelfIterationIntentSourcePayload,+ evidenceRefs: EvidenceRef[],+ hasUserInstructionConflict?: boolean,+): MaintenanceActionDraft => {+ const rationale = hasUserInstructionConflict+ ? `${payload.reason} Skipped because it conflicts with an explicit user instruction.`+ : payload.reason;+ const confidence = hasUserInstructionConflict ? 0 : payload.confidence;+ const safeEvidenceRefs = hasUserInstructionConflict ? [] : evidenceRefs;+ const base = {+ confidence,+ evidenceRefs: safeEvidenceRefs,+ policyHints: hasUserInstructionConflict+ ? {+ evidenceStrength: 'weak' as const,+ userExplicitness: 'explicit' as const,+ }+ : {+ evidenceStrength: 'strong' as const,+ mutationScope: 'small' as const,+ persistence: 'stable' as const,+ sensitivity: 'normal' as const,+ userExplicitness: 'explicit' as const,+ },+ rationale,+ target: createDraftTarget(payload),+ };++ if (payload.kind === 'memory' && payload.action === 'write') {+ return {+ ...base,+ actionType: 'write_memory',+ value: {+ content: payload.summary,+ reason: payload.reason,+ userId: payload.userId,+ },+ };+ }++ if (payload.kind === 'skill' && payload.action === 'create') {+ return {+ ...base,+ actionType: 'create_skill',+ value: {+ bodyMarkdown: payload.summary,+ description: payload.reason,+ name: payload.summary,+ reason: payload.reason,+ summary: payload.summary,+ title: payload.summary,+ userId: payload.userId,+ },+ };+ }++ if (payload.kind === 'skill' && payload.action === 'refine' && payload.skillId) {+ return {+ ...base,+ actionType: 'refine_skill',+ value: {+ patch: payload.summary,+ reason: payload.reason,+ skillDocumentId: payload.skillId,+ summary: payload.summary,+ userId: payload.userId,+ },+ };+ }++ if (payload.kind === 'skill' && payload.action === 'consolidate' && payload.skillId) {+ return {+ ...base,+ actionType: 'consolidate_skill',+ value: {+ canonicalSkillDocumentId: payload.skillId,+ reason: payload.reason,+ sourceSkillIds: payload.skillId ? [payload.skillId] : [],+ summary: payload.summary,+ userId: payload.userId,+ },+ };+ }++ return {+ ...createProposalDraft(payload, safeEvidenceRefs, rationale),+ confidence,+ };+};++const toMaintenancePlanDraft = (+ payload: SelfIterationIntentSourcePayload,+ enrichment: SelfIterationIntentEvidenceEnrichment,+): MaintenancePlanDraft => ({+ actions: [+ createActionDraft(+ payload,+ [...payload.evidenceRefs, ...enrichment.evidenceRefs],+ enrichment.hasUserInstructionConflict,+ ),+ ],+ findings: [],+ summary: payload.summary,+});++const writeSelfIterationIntentReceipt = async (+ deps: CreateSelfIterationIntentSourceHandlerDependencies,+ input: SelfIterationIntentReceiptInput,+) => {+ try {+ await deps.writeReceipt(input);+ } catch (error) {+ console.error('[AgentSignal] Failed to write self-iteration intent receipt:', error);+ }+};++const writeSelfIterationIntentReceipts = async (+ deps: CreateSelfIterationIntentSourceHandlerDependencies,+ receipts: AgentSignalReceipt[],+) => {+ if (!deps.writeReceipts || receipts.length === 0) return;++ try {+ await deps.writeReceipts(receipts);+ } catch (error) {+ console.error('[AgentSignal] Failed to write self-iteration intent receipts:', error);+ }+};++const applyReceiptIdsToExecution = (+ execution: MaintenanceReviewRunResult,+ receipts: AgentSignalReceipt[],+): MaintenanceReviewRunResult => {+ const receiptByActionKey = new Map(+ receipts+ .filter((receipt) => receipt.id.endsWith(':action'))+ .map((receipt) => [receipt.id.slice(0, -':action'.length), receipt.id]),+ );++ return {+ ...execution,+ actions: execution.actions.map((action) => ({+ ...action,+ ...(receiptByActionKey.get(action.idempotencyKey)+ ? { receiptId: receiptByActionKey.get(action.idempotencyKey) }+ : {}),+ })),+ summaryReceiptId: `${execution.sourceId ?? receipts[0]?.sourceId}:review-summary`,+ };+};++/**+ * Creates the DI-friendly handler for self-iteration intent declaration sources.+ *+ * Triggering workflow:+ *+ * {@link createSelfIterationIntentSourcePolicyHandler}+ * -> `agent.self_iteration_intent.declared`+ * -> {@link createSelfIterationIntentSourceHandler}+ *+ * Upstream:+ * - `agent.self_iteration_intent.declared`+ *+ * Downstream:+ * - injected `planReviewOutput`+ * - injected `executePlan`+ * - injected `writeReceipt`+ *+ * Use when:+ * - Tests need to run declared-intent orchestration without DB or LLM dependencies+ * - Runtime policy composition needs a side-effect boundary before executing maintenance plans+ *+ * Expects:+ * - `source` is an `agent.self_iteration_intent.declared` source with service-produced payload+ * - Dependencies enforce gates, idempotency, planner policy, executor persistence, and receipts+ *+ * Returns:+ * - A run result with status and enough plan metadata for self-iteration intent receipts+ */+export const createSelfIterationIntentSourceHandler = (+ deps: CreateSelfIterationIntentSourceHandlerDependencies,+) => ({+ handle: async (+ source: SourceAgentSelfIterationIntentDeclared,+ ): Promise<SelfIterationIntentSourceHandlerResult> => {+ const payload = readSelfIterationIntentPayload(source);++ if (!payload) {+ return {+ reason: 'invalid_payload',+ sourceId: source.sourceId,+ status: ReviewRunStatus.Skipped,+ };+ }++ const guardInput = toGuardInput(payload, source);+ if (source.sourceId !== guardInput.guardKey) {+ return {+ reason: 'invalid_payload',+ sourceId: source.sourceId,+ status: ReviewRunStatus.Skipped,+ };+ }++ const baseResult = toBaseResult(guardInput);++ if (!(await deps.canRunReview(guardInput))) {+ return {+ ...baseResult,+ reason: 'gate_disabled',+ status: ReviewRunStatus.Skipped,+ };+ }++ if (!(await deps.acquireReviewGuard(guardInput))) {+ return {+ ...baseResult,+ status: ReviewRunStatus.Deduped,+ };+ }++ const enrichment = (await deps.enrichEvidence?.(toEnrichEvidenceInput(payload))) ?? {+ evidenceRefs: [],+ };+ const draft = toMaintenancePlanDraft(payload, enrichment);+ const plan = await deps.planReviewOutput({+ draft,+ reviewScope: MaintenanceReviewScope.SelfIterationIntent,+ sourceId: source.sourceId,+ userId: payload.userId,+ });+ const execution = await deps.executePlan(plan);+ const receipts = createMaintenanceReviewReceipts({+ agentId: payload.agentId,+ createdAt: source.timestamp,+ plan,+ result: {+ ...execution,+ sourceId: source.sourceId,+ },+ scopeId: payload.scopeId,+ scopeType: payload.scopeType,+ sourceId: source.sourceId,+ sourceType: source.sourceType,+ ...(payload.topicId ? { topicId: payload.topicId } : {}),+ userId: payload.userId,+ });+ const executionWithReceipts = applyReceiptIdsToExecution(+ {+ ...execution,+ sourceId: source.sourceId,+ },+ receipts,+ );++ await writeSelfIterationIntentReceipts(deps, receipts);++ await writeSelfIterationIntentReceipt(deps, {+ execution: executionWithReceipts,+ plan,+ scopeId: payload.scopeId,+ scopeType: payload.scopeType,+ sourceId: source.sourceId,+ toolCallId: payload.toolCallId,+ });++ return {+ ...baseResult,+ execution: executionWithReceipts,+ plannedActionCount: plan.actions.length,+ planSummary: plan.summary,+ status: execution.status,+ };+ },+});++/**+ * Creates the runtime source handler definition for self-iteration intent policy composition.+ *+ * Triggering workflow:+ *+ * {@link defineSourceHandler}+ * -> `agent.self_iteration_intent.declared`+ * -> {@link createSelfIterationIntentSourcePolicyHandler}+ *+ * Upstream:+ * - `agent.self_iteration_intent.declared`+ *+ * Downstream:+ * - {@link createSelfIterationIntentSourceHandler}+ *+ * Use when:+ * - Default Agent Signal policies are composed with self-iteration intent dependencies+ * - The runtime source registry needs an installable source handler definition+ *+ * Expects:+ * - All server-only dependencies are injected by the caller+ *+ * Returns:+ * - A source handler that concludes the runtime chain with the review run metadata+ */+export const createSelfIterationIntentSourcePolicyHandler = (+ deps: CreateSelfIterationIntentSourceHandlerDependencies,+) => {+ const handler = createSelfIterationIntentSourceHandler(deps);++ return defineSourceHandler(+ AGENT_SIGNAL_SOURCE_TYPES.agentSelfIterationIntentDeclared,+ `${AGENT_SIGNAL_SOURCE_TYPES.agentSelfIterationIntentDeclared}:maintenance-review`,+ async (source: SourceAgentSelfIterationIntentDeclared) => {+ const result = await handler.handle(source);++ return {+ concluded: result,+ status: 'conclude',+ };+ },+ );+};diff --git a/src/server/services/agentSignal/policies/reviewNightly/selfReflection.ts b/src/server/services/agentSignal/policies/reviewNightly/selfReflection.tsnew file mode 100644index 00000000000..2f626835835--- /dev/null+++ b/src/server/services/agentSignal/policies/reviewNightly/selfReflection.ts@@ -0,0 +1,460 @@+import type { SourceAgentSelfReflectionRequested } from '@lobechat/agent-signal/source';+import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';++import { defineSourceHandler } from '../../runtime/middleware';+import type {+ MaintenancePlan,+ MaintenancePlanDraft,+ MaintenancePlanRequest,+ MaintenanceReviewRunResult,+} from '../../services/maintenance/types';+import {+ buildSelfReflectionSourceId,+ MaintenanceReviewScope,+ ReviewRunStatus,+} from '../../services/maintenance/types';+import type { AgentSignalReceipt } from '../../services/receiptService';+import { createMaintenanceReviewReceipts } from '../../services/receiptService';++/** Runtime scope supported by self-reflection source handlers. */+export type SelfReflectionSourceScopeType = 'operation' | 'task' | 'topic';++/**+ * Validated self-reflection request payload consumed by the handler.+ */+export interface SelfReflectionSourcePayload {+ /** Stable agent id being reviewed. */+ agentId: string;+ /** Runtime operation id when the source is operation-scoped or associated with one. */+ operationId?: string;+ /** Threshold or policy reason that requested reflection. */+ reason: string;+ /** Topic, task, or operation id selected for bounded evidence collection. */+ scopeId: string;+ /** Runtime scope family selected by the source producer. */+ scopeType: SelfReflectionSourceScopeType;+ /** Task id when the source is task-scoped or associated with one. */+ taskId?: string;+ /** Topic id when the source is topic-scoped or associated with one. */+ topicId?: string;+ /** Stable user id owning the agent. */+ userId: string;+ /** Reflection window end as an ISO string. */+ windowEnd: string;+ /** Reflection window start as an ISO string. */+ windowStart: string;+}++/**+ * Idempotency and gate input shared by self-reflection handler dependencies.+ */+export interface SelfReflectionSourceGuardInput extends SelfReflectionSourcePayload {+ /** Stable guard key for one scoped self-reflection window. */+ guardKey: string;+ /** Normalized source id that triggered the run. */+ sourceId: string;+}++/**+ * Scoped evidence collection input for self-reflection reviews.+ */+export interface CollectSelfReflectionContextInput {+ /** Stable agent id being reviewed. */+ agentId: string;+ /** Runtime operation id when the bounded evidence scope references one. */+ operationId?: string;+ /** Topic, task, or operation id selected for bounded evidence collection. */+ scopeId: string;+ /** Runtime scope family selected by the source producer. */+ scopeType: SelfReflectionSourceScopeType;+ /** Task id when the bounded evidence scope references one. */+ taskId?: string;+ /** Topic id when the bounded evidence scope references one. */+ topicId?: string;+ /** Stable user id owning the agent. */+ userId: string;+ /** Reflection window end as an ISO string. */+ windowEnd: string;+ /** Reflection window start as an ISO string. */+ windowStart: string;+}++/**+ * Review context collected for one self-reflection run.+ */+export interface SelfReflectionReviewContext extends CollectSelfReflectionContextInput {+ /** Additional collector-specific evidence fields. */+ [key: string]: unknown;+}++/**+ * Receipt input emitted after one self-reflection maintenance execution.+ */+export interface SelfReflectionReceiptInput {+ /** Executor result for the completed self-reflection run. */+ execution: MaintenanceReviewRunResult;+ /** Normalized maintenance plan sent to the executor. */+ plan: MaintenancePlan;+ /** Stable reason that requested reflection. */+ reason: string;+ /** Runtime scope id reviewed by the run. */+ scopeId: string;+ /** Runtime scope family reviewed by the run. */+ scopeType: SelfReflectionSourceScopeType;+ /** Source id that triggered the run. */+ sourceId: string;+}++/**+ * Result returned by the self-reflection source handler.+ */+export interface SelfReflectionSourceHandlerResult extends Record<string, unknown> {+ /** Stable agent id being reviewed when payload validation succeeds. */+ agentId?: string;+ /** Executor result for completed runs. */+ execution?: MaintenanceReviewRunResult;+ /** Stable guard key used for idempotency when payload validation succeeds. */+ guardKey?: string;+ /** Number of planned maintenance actions before execution. */+ plannedActionCount?: number;+ /** Planner summary for receipt construction. */+ planSummary?: string;+ /** Machine-readable skip reason for non-completed runs. */+ reason?: 'gate_disabled' | 'invalid_payload';+ /** Topic, task, or operation id selected for bounded evidence collection. */+ scopeId?: string;+ /** Runtime scope family selected by the source producer. */+ scopeType?: SelfReflectionSourceScopeType;+ /** Source id that triggered the run. */+ sourceId?: string;+ /** Coarse run status for observability and retry semantics. */+ status: ReviewRunStatus;+ /** Stable user id owning the agent when payload validation succeeds. */+ userId?: string;+ /** Reflection window end as an ISO string when payload validation succeeds. */+ windowEnd?: string;+ /** Reflection window start as an ISO string when payload validation succeeds. */+ windowStart?: string;+}++/**+ * Dependencies required by the self-reflection source handler.+ */+export interface CreateSelfReflectionSourceHandlerDependencies {+ /** Acquires the per-user-agent-scope window idempotency guard. */+ acquireReviewGuard: (input: SelfReflectionSourceGuardInput) => Promise<boolean>;+ /** Re-checks runtime gates before doing reviewer work. */+ canRunReview: (input: SelfReflectionSourceGuardInput) => Promise<boolean>;+ /** Collects only source-scoped evidence without mutating maintenance resources. */+ collectContext: (+ input: CollectSelfReflectionContextInput,+ ) => Promise<SelfReflectionReviewContext>;+ /** Applies only the planner-approved maintenance plan mutations. */+ executePlan: (plan: MaintenancePlan) => Promise<MaintenanceReviewRunResult>;+ /** Converts reviewer output into a deterministic maintenance plan. */+ planReviewOutput: (request: MaintenancePlanRequest) => MaintenancePlan | Promise<MaintenancePlan>;+ /** Runs the bounded maintenance reviewer against collected scoped context. */+ runMaintenanceReviewAgent: (+ context: SelfReflectionReviewContext,+ ) => Promise<MaintenancePlanDraft>;+ /** Writes durable receipt metadata for the self-reflection run. */+ writeReceipt: (input: SelfReflectionReceiptInput) => Promise<void>;+ /** Writes durable receipt records for the review summary and action outcomes. */+ writeReceipts?: (receipts: AgentSignalReceipt[]) => Promise<void>;+}++const isNonEmptyString = (value: unknown): value is string =>+ typeof value === 'string' && value.length > 0;++const isSelfReflectionScopeType = (value: unknown): value is SelfReflectionSourceScopeType =>+ value === 'topic' || value === 'task' || value === 'operation';++const readSelfReflectionPayload = (+ source: SourceAgentSelfReflectionRequested,+): SelfReflectionSourcePayload | undefined => {+ if (source.sourceType !== AGENT_SIGNAL_SOURCE_TYPES.agentSelfReflectionRequested) return;++ const payload = source.payload;+ if (+ !isNonEmptyString(payload.agentId) ||+ !isNonEmptyString(payload.reason) ||+ !isNonEmptyString(payload.scopeId) ||+ !isSelfReflectionScopeType(payload.scopeType) ||+ !isNonEmptyString(payload.userId) ||+ !isNonEmptyString(payload.windowEnd) ||+ !isNonEmptyString(payload.windowStart)+ ) {+ return;+ }++ return {+ agentId: payload.agentId,+ ...(isNonEmptyString(payload.operationId) ? { operationId: payload.operationId } : {}),+ reason: payload.reason,+ scopeId: payload.scopeId,+ scopeType: payload.scopeType,+ ...(isNonEmptyString(payload.taskId) ? { taskId: payload.taskId } : {}),+ ...(isNonEmptyString(payload.topicId) ? { topicId: payload.topicId } : {}),+ userId: payload.userId,+ windowEnd: payload.windowEnd,+ windowStart: payload.windowStart,+ };+};++const toGuardInput = (+ payload: SelfReflectionSourcePayload,+ source: SourceAgentSelfReflectionRequested,+): SelfReflectionSourceGuardInput => {+ return {+ ...payload,+ guardKey: buildSelfReflectionSourceId({+ agentId: payload.agentId,+ reason: payload.reason,+ scopeId: payload.scopeId,+ scopeType: payload.scopeType,+ userId: payload.userId,+ windowEnd: payload.windowEnd,+ windowStart: payload.windowStart,+ }),+ sourceId: source.sourceId,+ };+};++const toCollectContextInput = (+ payload: SelfReflectionSourcePayload,+): CollectSelfReflectionContextInput => ({+ agentId: payload.agentId,+ ...(payload.operationId ? { operationId: payload.operationId } : {}),+ scopeId: payload.scopeId,+ scopeType: payload.scopeType,+ ...(payload.taskId ? { taskId: payload.taskId } : {}),+ ...(payload.topicId ? { topicId: payload.topicId } : {}),+ userId: payload.userId,+ windowEnd: payload.windowEnd,+ windowStart: payload.windowStart,+});++const toBaseResult = (+ guardInput: SelfReflectionSourceGuardInput,+): Omit<SelfReflectionSourceHandlerResult, 'status'> => ({+ agentId: guardInput.agentId,+ guardKey: guardInput.guardKey,+ scopeId: guardInput.scopeId,+ scopeType: guardInput.scopeType,+ sourceId: guardInput.sourceId,+ userId: guardInput.userId,+ windowEnd: guardInput.windowEnd,+ windowStart: guardInput.windowStart,+});++const writeSelfReflectionReceipt = async (+ deps: CreateSelfReflectionSourceHandlerDependencies,+ input: SelfReflectionReceiptInput,+) => {+ try {+ await deps.writeReceipt(input);+ } catch (error) {+ console.error('[AgentSignal] Failed to write self-reflection receipt:', error);+ }+};++const writeSelfReflectionReceipts = async (+ deps: CreateSelfReflectionSourceHandlerDependencies,+ receipts: AgentSignalReceipt[],+) => {+ if (!deps.writeReceipts || receipts.length === 0) return;++ try {+ await deps.writeReceipts(receipts);+ } catch (error) {+ console.error('[AgentSignal] Failed to write self-reflection receipts:', error);+ }+};++const applyReceiptIdsToExecution = (+ execution: MaintenanceReviewRunResult,+ receipts: AgentSignalReceipt[],+): MaintenanceReviewRunResult => {+ const receiptByActionKey = new Map(+ receipts+ .filter((receipt) => receipt.id.endsWith(':action'))+ .map((receipt) => [receipt.id.slice(0, -':action'.length), receipt.id]),+ );++ return {+ ...execution,+ actions: execution.actions.map((action) => ({+ ...action,+ ...(receiptByActionKey.get(action.idempotencyKey)+ ? { receiptId: receiptByActionKey.get(action.idempotencyKey) }+ : {}),+ })),+ summaryReceiptId: `${execution.sourceId ?? receipts[0]?.sourceId}:review-summary`,+ };+};++/**+ * Creates the DI-friendly handler for self-reflection request sources.+ *+ * Triggering workflow:+ *+ * {@link createSelfReflectionSourcePolicyHandler}+ * -> `agent.self_reflection.requested`+ * -> {@link createSelfReflectionSourceHandler}+ *+ * Upstream:+ * - `agent.self_reflection.requested`+ *+ * Downstream:+ * - injected `executePlan`+ * - injected `writeReceipt`+ *+ * Use when:+ * - Tests need to run scoped self-reflection orchestration without DB or LLM dependencies+ * - Runtime policy composition needs a side-effect boundary before executing maintenance plans+ *+ * Expects:+ * - `source` is an `agent.self_reflection.requested` source with service-produced payload+ * - Dependencies enforce gates, idempotency, reviewer limits, executor persistence, and receipts+ *+ * Returns:+ * - A run result with status and enough plan metadata for self-reflection receipts+ */+export const createSelfReflectionSourceHandler = (+ deps: CreateSelfReflectionSourceHandlerDependencies,+) => ({+ handle: async (+ source: SourceAgentSelfReflectionRequested,+ ): Promise<SelfReflectionSourceHandlerResult> => {+ const payload = readSelfReflectionPayload(source);++ if (!payload) {+ return {+ reason: 'invalid_payload',+ sourceId: source.sourceId,+ status: ReviewRunStatus.Skipped,+ };+ }++ const guardInput = toGuardInput(payload, source);+ if (source.sourceId !== guardInput.guardKey) {+ return {+ reason: 'invalid_payload',+ sourceId: source.sourceId,+ status: ReviewRunStatus.Skipped,+ };+ }++ const baseResult = toBaseResult(guardInput);++ if (!(await deps.canRunReview(guardInput))) {+ return {+ ...baseResult,+ reason: 'gate_disabled',+ status: ReviewRunStatus.Skipped,+ };+ }++ if (!(await deps.acquireReviewGuard(guardInput))) {+ return {+ ...baseResult,+ status: ReviewRunStatus.Deduped,+ };+ }++ const context = await deps.collectContext(toCollectContextInput(payload));+ const draft = await deps.runMaintenanceReviewAgent(context);+ const plan = await deps.planReviewOutput({+ draft,+ reviewScope: MaintenanceReviewScope.SelfReflection,+ sourceId: source.sourceId,+ userId: payload.userId,+ });+ const execution = await deps.executePlan(plan);+ const receipts = createMaintenanceReviewReceipts({+ agentId: payload.agentId,+ createdAt: source.timestamp,+ plan,+ result: {+ ...execution,+ sourceId: source.sourceId,+ },+ scopeId: payload.scopeId,+ scopeType: payload.scopeType,+ sourceId: source.sourceId,+ sourceType: source.sourceType,+ ...(payload.topicId ? { topicId: payload.topicId } : {}),+ userId: payload.userId,+ });+ const executionWithReceipts = applyReceiptIdsToExecution(+ {+ ...execution,+ sourceId: source.sourceId,+ },+ receipts,+ );++ await writeSelfReflectionReceipts(deps, receipts);++ await writeSelfReflectionReceipt(deps, {+ execution: executionWithReceipts,+ plan,+ reason: payload.reason,+ scopeId: payload.scopeId,+ scopeType: payload.scopeType,+ sourceId: source.sourceId,+ });++ return {+ ...baseResult,+ execution: executionWithReceipts,+ plannedActionCount: plan.actions.length,+ planSummary: plan.summary,+ status: execution.status,+ };+ },+});++/**+ * Creates the runtime source handler definition for self-reflection policy composition.+ *+ * Triggering workflow:+ *+ * {@link defineSourceHandler}+ * -> `agent.self_reflection.requested`+ * -> {@link createSelfReflectionSourcePolicyHandler}+ *+ * Upstream:+ * - `agent.self_reflection.requested`+ *+ * Downstream:+ * - {@link createSelfReflectionSourceHandler}+ *+ * Use when:+ * - Default Agent Signal policies are composed with self-reflection dependencies+ * - The runtime source registry needs an installable source handler definition+ *+ * Expects:+ * - All server-only dependencies are injected by the caller+ *+ * Returns:+ * - A source handler that concludes the runtime chain with the review run metadata+ */+export const createSelfReflectionSourcePolicyHandler = (+ deps: CreateSelfReflectionSourceHandlerDependencies,+) => {+ const handler = createSelfReflectionSourceHandler(deps);++ return defineSourceHandler(+ AGENT_SIGNAL_SOURCE_TYPES.agentSelfReflectionRequested,+ `${AGENT_SIGNAL_SOURCE_TYPES.agentSelfReflectionRequested}:maintenance-review`,+ async (source: SourceAgentSelfReflectionRequested) => {+ const result = await handler.handle(source);++ return {+ concluded: result,+ status: 'conclude',+ };+ },+ );+};diff --git a/src/server/services/agentSignal/procedure/__tests__/accumulator.test.ts b/src/server/services/agentSignal/procedure/__tests__/accumulator.test.tsindex 8120f68485f..ae13c0ec0c6 100644--- a/src/server/services/agentSignal/procedure/__tests__/accumulator.test.ts+++ b/src/server/services/agentSignal/procedure/__tests__/accumulator.test.ts@@ -3,7 +3,7 @@ import {appendAndScoreProcedureAccumulatorRecord,appendDomainProcedureRecord,shouldScoreAccumulator,-} from '../accumulator';+} from '../accumulators/procedure';import { PROCEDURE_ACCUMULATOR_POLICY_ID } from '../keys';const createStore = (): AgentSignalPolicyStateStore => {diff --git a/src/server/services/agentSignal/procedure/__tests__/selfReflectionAccumulator.test.ts b/src/server/services/agentSignal/procedure/__tests__/selfReflectionAccumulator.test.tsnew file mode 100644index 00000000000..05a23fb87e6--- /dev/null+++ b/src/server/services/agentSignal/procedure/__tests__/selfReflectionAccumulator.test.ts@@ -0,0 +1,362 @@+import type {+ AsyncSelfReflectionAccumulator,+ SelfReflectionAccumulator,+ SelfReflectionAccumulatorEventType,+ SelfReflectionAccumulatorRecordInput,+ SelfReflectionRequestReason,+} from '../accumulators/selfReflection';+import {+ createDurableSelfReflectionAccumulator,+ createSelfReflectionAccumulator,+} from '../accumulators/selfReflection';++const createInput = (+ eventType: SelfReflectionAccumulatorEventType,+ sourceId: string,+ overrides: Partial<SelfReflectionAccumulatorRecordInput> = {},+): SelfReflectionAccumulatorRecordInput => ({+ agentId: 'agent-1',+ eventType,+ sourceId,+ taskId: 'task-1',+ userId: 'user-1',+ ...overrides,+});++const recordRepeated = (+ accumulator: SelfReflectionAccumulator,+ eventType: SelfReflectionAccumulatorEventType,+ count: number,+ overrides: Partial<SelfReflectionAccumulatorRecordInput> = {},+) => {+ let decision = accumulator.record(createInput(eventType, `${eventType}-1`, overrides));++ for (let index = 2; index <= count; index += 1) {+ decision = accumulator.record(createInput(eventType, `${eventType}-${index}`, overrides));+ }++ return decision;+};++const expectRequest = (+ accumulator: SelfReflectionAccumulator,+ eventType: SelfReflectionAccumulatorEventType,+ count: number,+ reason: SelfReflectionRequestReason,+) => {+ const decision = recordRepeated(accumulator, eventType, count);++ /**+ * @example+ * expectRequest(accumulator, 'runtime_step', 6, 'runtime_step_count')+ */+ expect(decision).toMatchObject({+ reason,+ scopeId: 'task-1',+ scopeType: 'task',+ shouldRequest: true,+ });+};++/**+ * @example+ * createSelfReflectionAccumulator().record(input) returns threshold decisions for one scope.+ */+describe('selfReflectionAccumulator', () => {+ /**+ * @example+ * Two failed tool calls in the same task emit a self-reflection request.+ */+ it('requests self-reflection when failed tool threshold is reached', () => {+ const accumulator = createSelfReflectionAccumulator();++ accumulator.record(createInput('tool_failed', 'source-1'));+ const decision = accumulator.record(createInput('tool_failed', 'source-2'));++ /**+ * @example+ * expect(decision).toMatchObject({ shouldRequest: true })+ */+ expect(decision).toMatchObject({+ reason: 'failed_tool_count',+ scopeId: 'task-1',+ scopeType: 'task',+ shouldRequest: true,+ });+ });++ /**+ * @example+ * Two failed calls to the same named tool emit the same-tool threshold on the second failure.+ */+ it('requests self-reflection for the same tool failure threshold at crossing time', () => {+ const accumulator = createSelfReflectionAccumulator();++ accumulator.record(createInput('tool_failed', 'source-1', { toolName: 'searchWeb' }));+ const decision = accumulator.record(+ createInput('tool_failed', 'source-2', { toolName: 'searchWeb' }),+ );+ const staleDecision = accumulator.record(+ createInput('tool_failed', 'source-3', { toolName: 'searchWeb' }),+ );++ /**+ * @example+ * expect(decision.reason).toBe('same_tool_failure_count')+ */+ expect(decision).toMatchObject({+ reason: 'same_tool_failure_count',+ scopeId: 'task-1',+ scopeType: 'task',+ shouldRequest: true,+ });+ expect(staleDecision.shouldRequest).toBe(false);+ });++ /**+ * @example+ * Ten ordinary tool events emit the tool-call-count threshold.+ */+ it('requests self-reflection when tool call threshold is reached', () => {+ const accumulator = createSelfReflectionAccumulator();++ expectRequest(accumulator, 'tool_completed', 10, 'tool_call_count');+ });++ /**+ * @example+ * Two correction signals emit the user-correction threshold.+ */+ it('requests self-reflection when correction threshold is reached', () => {+ const accumulator = createSelfReflectionAccumulator();++ expectRequest(accumulator, 'correction', 2, 'user_correction_count');+ });++ /**+ * @example+ * Six runtime steps emit the runtime-step threshold.+ */+ it('requests self-reflection when runtime step threshold is reached', () => {+ const accumulator = createSelfReflectionAccumulator();++ expectRequest(accumulator, 'runtime_step', 6, 'runtime_step_count');+ });++ /**+ * @example+ * Three receipt signals emit the receipt threshold.+ */+ it('requests self-reflection when receipt threshold is reached', () => {+ const accumulator = createSelfReflectionAccumulator();++ expectRequest(accumulator, 'receipt', 3, 'receipt_count');+ });++ /**+ * @example+ * Execution failure emits a self-reflection request immediately.+ */+ it('requests self-reflection when execution fails', () => {+ const accumulator = createSelfReflectionAccumulator();++ const decision = accumulator.record(createInput('execution_failed', 'source-1'));++ /**+ * @example+ * expect(decision.reason).toBe('execution_failed')+ */+ expect(decision).toMatchObject({+ reason: 'execution_failed',+ scopeId: 'task-1',+ scopeType: 'task',+ shouldRequest: true,+ });+ });++ /**+ * @example+ * taskId wins over operationId and topicId when all are present.+ */+ it('prefers task scope over operation and topic scope', () => {+ const accumulator = createSelfReflectionAccumulator();++ const decision = accumulator.record(+ createInput('execution_failed', 'source-1', {+ operationId: 'operation-1',+ taskId: 'task-1',+ topicId: 'topic-1',+ }),+ );++ /**+ * @example+ * expect(decision.scopeType).toBe('task')+ */+ expect(decision).toMatchObject({+ scopeId: 'task-1',+ scopeType: 'task',+ shouldRequest: true,+ });+ });++ /**+ * @example+ * operationId is used when taskId is absent.+ */+ it('uses operation scope when task scope is absent', () => {+ const accumulator = createSelfReflectionAccumulator();++ const decision = accumulator.record(+ createInput('execution_failed', 'source-1', {+ operationId: 'operation-1',+ taskId: undefined,+ topicId: 'topic-1',+ }),+ );++ /**+ * @example+ * expect(decision.scopeType).toBe('operation')+ */+ expect(decision).toMatchObject({+ scopeId: 'operation-1',+ scopeType: 'operation',+ shouldRequest: true,+ });+ });++ /**+ * @example+ * topicId is used when taskId and operationId are absent.+ */+ it('uses topic scope when task and operation scopes are absent', () => {+ const accumulator = createSelfReflectionAccumulator();++ const decision = accumulator.record(+ createInput('execution_failed', 'source-1', {+ operationId: undefined,+ taskId: undefined,+ topicId: 'topic-1',+ }),+ );++ /**+ * @example+ * expect(decision.scopeType).toBe('topic')+ */+ expect(decision).toMatchObject({+ scopeId: 'topic-1',+ scopeType: 'topic',+ shouldRequest: true,+ });+ });++ /**+ * @example+ * Same task ids do not share counters across different users or agents.+ */+ it('isolates counters by user and agent', () => {+ const accumulator = createSelfReflectionAccumulator();++ accumulator.record(createInput('tool_failed', 'source-1'));+ const otherUserDecision = accumulator.record(+ createInput('tool_failed', 'source-2', { userId: 'user-2' }),+ );+ const otherAgentDecision = accumulator.record(+ createInput('tool_failed', 'source-3', { agentId: 'agent-2' }),+ );+ const originalScopeDecision = accumulator.record(createInput('tool_failed', 'source-4'));++ /**+ * @example+ * expect(otherUserDecision.shouldRequest).toBe(false)+ */+ expect(otherUserDecision.shouldRequest).toBe(false);+ expect(otherAgentDecision.shouldRequest).toBe(false);+ expect(originalScopeDecision).toMatchObject({+ reason: 'failed_tool_count',+ shouldRequest: true,+ });+ });++ /**+ * @example+ * Two workflow events using two accumulator instances still cross the failed-tool threshold.+ */+ it('persists threshold counters across durable accumulator instances', async () => {+ const fields = new Map<string, Record<string, string>>();+ const createAccumulator = (): AsyncSelfReflectionAccumulator =>+ createDurableSelfReflectionAccumulator({+ policyStateStore: {+ readPolicyState: async (_policyId, scopeKey) => fields.get(scopeKey),+ writePolicyState: async (_policyId, scopeKey, data) => {+ fields.set(scopeKey, { ...fields.get(scopeKey), ...data });+ },+ },+ ttlSeconds: 60,+ });++ await createAccumulator().record(+ createInput('tool_failed', 'source-1', {+ eventTimestamp: '2026-05-04T14:00:00.000Z',+ }),+ );+ const decision = await createAccumulator().record(+ createInput('tool_failed', 'source-2', {+ eventTimestamp: '2026-05-04T14:05:00.000Z',+ }),+ );++ expect(decision).toMatchObject({+ reason: 'failed_tool_count',+ scopeId: 'task-1',+ scopeType: 'task',+ shouldRequest: true,+ windowStart: '2026-05-04T14:00:00.000Z',+ });+ });++ /**+ * @example+ * Signals without taskId, operationId, or topicId never request self-reflection.+ */+ it('does not request self-reflection without a scope id', () => {+ const accumulator = createSelfReflectionAccumulator();++ const decision = accumulator.record(+ createInput('execution_failed', 'source-1', {+ operationId: undefined,+ taskId: undefined,+ topicId: undefined,+ }),+ );++ /**+ * @example+ * expect(decision.shouldRequest).toBe(false)+ */+ expect(decision.shouldRequest).toBe(false);+ });++ /**+ * @example+ * Low-signal ordinary progress does not emit a source.+ */+ it('does not request reflection below thresholds', () => {+ const accumulator = createSelfReflectionAccumulator();++ const decision = accumulator.record(+ createInput('tool_completed', 'source-1', {+ taskId: undefined,+ topicId: 'topic-1',+ }),+ );++ /**+ * @example+ * expect(decision.shouldRequest).toBe(false)+ */+ expect(decision.shouldRequest).toBe(false);+ });+});diff --git a/src/server/services/agentSignal/procedure/__tests__/toolOutcome.test.ts b/src/server/services/agentSignal/procedure/__tests__/toolOutcome.test.tsindex 9188e71f096..39ee1ca8334 100644--- a/src/server/services/agentSignal/procedure/__tests__/toolOutcome.test.ts+++ b/src/server/services/agentSignal/procedure/__tests__/toolOutcome.test.ts@@ -5,6 +5,7 @@ import type {} from '@lobechat/agent-signal/source';import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';+import { createSelfReflectionAccumulator } from '../accumulators/selfReflection';import { createToolOutcomeSourceHandler } from '../toolOutcome';describe('tool outcome procedure handler', () => {@@ -202,4 +203,285 @@ describe('tool outcome procedure handler', () => {expect(markers).toHaveLength(0);});++ /**+ * @example+ * two failed outcomes in one task request self-reflection once for the crossed tool threshold.+ */+ it('requests self-reflection once when repeated same-tool failures cross threshold', async () => {+ const requestSelfReflection = vi.fn(async () => ({ enqueued: true, sourceId: 'reflect-1' }));+ const handler = createToolOutcomeSourceHandler({+ accumulator: { appendRecord: async () => {} },+ markerStore: { write: async () => {} },+ now: () => 100,+ receiptStore: { append: async () => {} },+ recordStore: { write: async () => {} },+ selfReflection: {+ accumulator: createSelfReflectionAccumulator(),+ getWindowStart: ({ decision }) => decision.windowStart ?? 'missing-window-start',+ service: { requestSelfReflection },+ },+ ttlSeconds: 3600,+ });+ const createFailedSource = (sourceId: string, timestamp: number) =>+ createSource({+ payload: {+ agentId: 'agent-1',+ domainKey: 'skill:market-skill',+ intentClass: 'tool_command',+ operationId: 'operation-1',+ outcome: { action: 'import', errorReason: 'network', status: 'failed' },+ taskId: 'task-1',+ tool: { apiName: 'importFromMarket', identifier: 'lobe-skill-store' },+ topicId: 'topic-1',+ },+ scope: { agentId: 'agent-1', taskId: 'task-1', topicId: 'topic-1', userId: 'user-1' },+ scopeKey: 'topic:topic-1',+ sourceId,+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.toolOutcomeFailed,+ timestamp,+ }) as SourceToolOutcomeFailed;++ await handler.handle(createFailedSource('source_failed_1', 2000), {+ now: () => 2000,+ scopeKey: 'topic:topic-1',+ } as never);+ await handler.handle(createFailedSource('source_failed_2', 3000), {+ now: () => 3000,+ scopeKey: 'topic:topic-1',+ } as never);++ expect(requestSelfReflection).toHaveBeenCalledTimes(1);+ expect(requestSelfReflection).toHaveBeenCalledWith({+ agentId: 'agent-1',+ operationId: 'operation-1',+ reason: 'same_tool_failure_count',+ scopeId: 'task-1',+ scopeType: 'task',+ taskId: 'task-1',+ topicId: 'topic-1',+ userId: 'user-1',+ windowEnd: '1970-01-01T00:00:03.000Z',+ windowStart: '1970-01-01T00:00:02.000Z',+ });+ });++ /**+ * @example+ * a single completed outcome stays below self-reflection thresholds.+ */+ it('does not request self-reflection for one completed outcome below threshold', async () => {+ const requestSelfReflection = vi.fn(async () => ({ enqueued: true, sourceId: 'reflect-1' }));+ const handler = createToolOutcomeSourceHandler({+ accumulator: { appendRecord: async () => {} },+ markerStore: { write: async () => {} },+ now: () => 100,+ receiptStore: { append: async () => {} },+ recordStore: { write: async () => {} },+ selfReflection: {+ accumulator: createSelfReflectionAccumulator(),+ getWindowStart: () => '2026-05-04T00:00:00.000Z',+ service: { requestSelfReflection },+ },+ ttlSeconds: 3600,+ });+ const source = createSource({+ payload: {+ agentId: 'agent-1',+ domainKey: 'memory:user-preference',+ intentClass: 'explicit_persistence',+ outcome: { action: 'create', status: 'succeeded', summary: 'Saved preference.' },+ taskId: 'task-1',+ tool: { apiName: 'addPreferenceMemory', identifier: 'lobe-user-memory' },+ topicId: 'topic-1',+ },+ scope: { agentId: 'agent-1', taskId: 'task-1', topicId: 'topic-1', userId: 'user-1' },+ scopeKey: 'topic:topic-1',+ sourceId: 'source_completed_1',+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.toolOutcomeCompleted,+ timestamp: 2000,+ }) as SourceToolOutcomeCompleted;++ await handler.handle(source, { now: () => 2000, scopeKey: 'topic:topic-1' } as never);++ expect(requestSelfReflection).not.toHaveBeenCalled();+ });++ /**+ * @example+ * rejected self-reflection requests do not block marker writes for handled outcomes.+ */+ it('isolates self-reflection request failures from marker writes and dispatch', async () => {+ const markers: unknown[] = [];+ const reflectionError = new Error('reflection queue unavailable');+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});+ const requestSelfReflection = vi.fn(async () => {+ throw reflectionError;+ });+ const handler = createToolOutcomeSourceHandler({+ accumulator: { appendRecord: async () => {} },+ markerStore: {+ write: async (marker) => {+ markers.push(marker);+ },+ },+ now: () => 100,+ receiptStore: { append: async () => {} },+ recordStore: { write: async () => {} },+ selfReflection: {+ accumulator: createSelfReflectionAccumulator(),+ getWindowStart: () => '2026-05-04T00:00:00.000Z',+ service: { requestSelfReflection },+ },+ ttlSeconds: 3600,+ });+ const createCompletedSource = (sourceId: string, timestamp: number) =>+ createSource({+ payload: {+ agentId: 'agent-1',+ domainKey: 'memory:user-preference',+ intentClass: 'explicit_persistence',+ outcome: { action: 'create', status: 'succeeded', summary: 'Saved preference.' },+ taskId: 'task-1',+ tool: { apiName: 'addPreferenceMemory', identifier: 'lobe-user-memory' },+ topicId: 'topic-1',+ },+ scope: { agentId: 'agent-1', taskId: 'task-1', topicId: 'topic-1', userId: 'user-1' },+ scopeKey: 'topic:topic-1',+ sourceId,+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.toolOutcomeCompleted,+ timestamp,+ }) as SourceToolOutcomeCompleted;++ const results = [];+ for (const index of Array.from({ length: 10 }, (_, itemIndex) => itemIndex)) {+ results.push(+ await handler.handle(createCompletedSource(`source_completed_${index}`, 2000 + index), {+ now: () => 2000 + index,+ scopeKey: 'topic:topic-1',+ } as never),+ );+ }++ expect(requestSelfReflection).toHaveBeenCalledTimes(1);+ expect(markers).toHaveLength(10);+ expect(results.at(-1)).toEqual(+ expect.objectContaining({+ signals: [expect.objectContaining({ signalType: 'signal.tool.outcome' })],+ status: 'dispatch',+ }),+ );+ await vi.waitFor(() =>+ expect(consoleError).toHaveBeenCalledWith(+ '[AgentSignal] Failed to request self-reflection:',+ reflectionError,+ ),+ );+ consoleError.mockRestore();+ });++ /**+ * @example+ * invalid source timestamps fall back to the procedure clock at threshold crossing.+ */+ it('uses the procedure clock when threshold-crossing source timestamp is invalid', async () => {+ const requestSelfReflection = vi.fn(async () => ({ enqueued: true, sourceId: 'reflect-1' }));+ const handler = createToolOutcomeSourceHandler({+ accumulator: { appendRecord: async () => {} },+ markerStore: { write: async () => {} },+ now: () => 4000,+ receiptStore: { append: async () => {} },+ recordStore: { write: async () => {} },+ selfReflection: {+ accumulator: createSelfReflectionAccumulator(),+ getWindowStart: () => '2026-05-04T00:00:00.000Z',+ service: { requestSelfReflection },+ },+ ttlSeconds: 3600,+ });+ const createFailedSource = (sourceId: string, timestamp: number) =>+ createSource({+ payload: {+ agentId: 'agent-1',+ domainKey: 'skill:market-skill',+ intentClass: 'tool_command',+ operationId: 'operation-1',+ outcome: { action: 'import', errorReason: 'network', status: 'failed' },+ taskId: 'task-1',+ tool: { apiName: 'importFromMarket', identifier: 'lobe-skill-store' },+ topicId: 'topic-1',+ },+ scope: { agentId: 'agent-1', taskId: 'task-1', topicId: 'topic-1', userId: 'user-1' },+ scopeKey: 'topic:topic-1',+ sourceId,+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.toolOutcomeFailed,+ timestamp,+ }) as SourceToolOutcomeFailed;++ await handler.handle(createFailedSource('source_failed_valid', 2000), {+ now: () => 2000,+ scopeKey: 'topic:topic-1',+ } as never);+ const result = await handler.handle(createFailedSource('source_failed_invalid', Number.NaN), {+ now: () => 4000,+ scopeKey: 'topic:topic-1',+ } as never);++ expect(result).toEqual(+ expect.objectContaining({+ signals: [expect.objectContaining({ signalType: 'signal.tool.outcome' })],+ status: 'dispatch',+ }),+ );+ expect(requestSelfReflection).toHaveBeenCalledWith(+ expect.objectContaining({ windowEnd: '1970-01-01T00:00:04.000Z' }),+ );+ });++ /**+ * @example+ * tool outcome procedure wiring remains optional for callers without self-reflection deps.+ */+ it('preserves dispatch behavior without self-reflection dependencies', async () => {+ const records: unknown[] = [];+ const handler = createToolOutcomeSourceHandler({+ accumulator: { appendRecord: async () => {} },+ markerStore: { write: async () => {} },+ now: () => 100,+ receiptStore: { append: async () => {} },+ recordStore: {+ write: async (record) => {+ records.push(record);+ },+ },+ ttlSeconds: 3600,+ });+ const source = createSource({+ payload: {+ agentId: 'agent-1',+ domainKey: 'skill:market-skill',+ intentClass: 'tool_command',+ outcome: { action: 'import', errorReason: 'network', status: 'failed' },+ taskId: 'task-1',+ tool: { apiName: 'importFromMarket', identifier: 'lobe-skill-store' },+ },+ scope: { agentId: 'agent-1', taskId: 'task-1', userId: 'user-1' },+ scopeKey: 'task:task-1',+ sourceId: 'source_no_self_reflection',+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.toolOutcomeFailed,+ }) as SourceToolOutcomeFailed;++ const result = await handler.handle(source, {+ now: () => 100,+ scopeKey: 'task:task-1',+ } as never);++ expect(records).toHaveLength(1);+ expect(result).toEqual(+ expect.objectContaining({+ signals: [expect.objectContaining({ signalType: 'signal.tool.outcome' })],+ status: 'dispatch',+ }),+ );+ });});diff --git a/src/server/services/agentSignal/procedure/accumulators/index.ts b/src/server/services/agentSignal/procedure/accumulators/index.tsnew file mode 100644index 00000000000..c141132e75a--- /dev/null+++ b/src/server/services/agentSignal/procedure/accumulators/index.ts@@ -0,0 +1,2 @@+export * from './procedure';+export * from './selfReflection';diff --git a/src/server/services/agentSignal/procedure/accumulator.ts b/src/server/services/agentSignal/procedure/accumulators/procedure.tssimilarity index 98%rename from src/server/services/agentSignal/procedure/accumulator.tsrename to src/server/services/agentSignal/procedure/accumulators/procedure.tsindex c07d7885aff..379002bcc92 100644--- a/src/server/services/agentSignal/procedure/accumulator.ts+++ b/src/server/services/agentSignal/procedure/accumulators/procedure.ts@@ -1,11 +1,11 @@-import type { AgentSignalPolicyStateStore } from '../store/types';-import { scoreDomainProcedureBatch } from './batchScorer';-import { getCoarseProcedureDomain, PROCEDURE_ACCUMULATOR_POLICY_ID } from './keys';+import type { AgentSignalPolicyStateStore } from '../../store/types';+import { scoreDomainProcedureBatch } from '../batchScorer';+import { getCoarseProcedureDomain, PROCEDURE_ACCUMULATOR_POLICY_ID } from '../keys';import type {AgentSignalProcedureRecord,DomainProcedureAccumulatorState,DomainProcedureBatchScore,-} from './types';+} from '../types';/*** Default deterministic P0 scoring thresholds for weak procedure candidates.diff --git a/src/server/services/agentSignal/procedure/accumulators/selfReflection.ts b/src/server/services/agentSignal/procedure/accumulators/selfReflection.tsnew file mode 100644index 00000000000..a0c698f5913--- /dev/null+++ b/src/server/services/agentSignal/procedure/accumulators/selfReflection.ts@@ -0,0 +1,413 @@+import type { AgentSignalPolicyStateStore } from '../../store/types';++type SelfReflectionScopeType = 'operation' | 'task' | 'topic';++const SELF_REFLECTION_ACCUMULATOR_POLICY_ID = 'self-reflection-accumulator';++export type SelfReflectionAccumulatorEventType =+ | 'correction'+ | 'execution_failed'+ | 'negative_feedback'+ | 'receipt'+ | 'runtime_step'+ | 'tool_called'+ | 'tool_completed'+ | 'tool_failed';++export type SelfReflectionRequestReason =+ | 'execution_failed'+ | 'failed_tool_count'+ | 'receipt_count'+ | 'runtime_step_count'+ | 'same_tool_failure_count'+ | 'tool_call_count'+ | 'user_correction_count';++export interface SelfReflectionAccumulatorScope {+ scopeId: string;+ scopeType: SelfReflectionScopeType;+}++export interface SelfReflectionAccumulatorThresholds {+ correctionCount: number;+ failedToolCount: number;+ receiptCount: number;+ runtimeStepCount: number;+ sameToolFailureCount: number;+ toolCallCount: number;+}++export interface SelfReflectionAccumulatorCounters {+ correctionCount: number;+ failedToolCount: number;+ negativeFeedbackCount: number;+ receiptCount: number;+ runtimeStepCount: number;+ sameToolFailureCount: number;+ toolCallCount: number;+}++export interface SelfReflectionAccumulatorRecordInput {+ agentId: string;+ eventTimestamp?: string;+ eventType: SelfReflectionAccumulatorEventType;+ operationId?: string;+ sourceId: string;+ taskId?: string;+ toolName?: string;+ topicId?: string;+ userId: string;+}++export interface SelfReflectionAccumulatorDecision {+ counters?: SelfReflectionAccumulatorCounters;+ reason?: SelfReflectionRequestReason;+ scopeId?: string;+ scopeType?: SelfReflectionScopeType;+ shouldRequest: boolean;+ windowStart?: string;+}++interface SelfReflectionAccumulatorState {+ counters: SelfReflectionAccumulatorCounters;+ emittedReasons: Set<SelfReflectionRequestReason>;+ toolFailures: Map<string, number>;+ windowStart?: string;+}++export interface SelfReflectionAccumulator {+ record: (input: SelfReflectionAccumulatorRecordInput) => SelfReflectionAccumulatorDecision;+}++export interface AsyncSelfReflectionAccumulator {+ record: (+ input: SelfReflectionAccumulatorRecordInput,+ ) => Promise<SelfReflectionAccumulatorDecision> | SelfReflectionAccumulatorDecision;+}++const DEFAULT_THRESHOLDS = {+ correctionCount: 2,+ failedToolCount: 2,+ receiptCount: 3,+ runtimeStepCount: 6,+ sameToolFailureCount: 2,+ toolCallCount: 10,+} satisfies SelfReflectionAccumulatorThresholds;++const createInitialCounters = (): SelfReflectionAccumulatorCounters => ({+ correctionCount: 0,+ failedToolCount: 0,+ negativeFeedbackCount: 0,+ receiptCount: 0,+ runtimeStepCount: 0,+ sameToolFailureCount: 0,+ toolCallCount: 0,+});++const copyCounters = (+ counters: SelfReflectionAccumulatorCounters,+): SelfReflectionAccumulatorCounters => ({+ ...counters,+});++const resolveScope = (+ input: SelfReflectionAccumulatorRecordInput,+): SelfReflectionAccumulatorScope | undefined => {+ if (input.taskId) return { scopeId: input.taskId, scopeType: 'task' };+ if (input.operationId) return { scopeId: input.operationId, scopeType: 'operation' };+ if (input.topicId) return { scopeId: input.topicId, scopeType: 'topic' };+};++const getScopeKey = (+ input: SelfReflectionAccumulatorRecordInput,+ scope: SelfReflectionAccumulatorScope,+) => `${input.userId}:${input.agentId}:${scope.scopeType}:${scope.scopeId}`;++const createState = (): SelfReflectionAccumulatorState => ({+ counters: createInitialCounters(),+ emittedReasons: new Set<SelfReflectionRequestReason>(),+ toolFailures: new Map<string, number>(),+});++const chooseEarlierTimestamp = (previous: string | undefined, next: string | undefined) => {+ if (!next) return previous;+ if (!previous) return next;++ return next < previous ? next : previous;+};++const serializeCounters = (counters: SelfReflectionAccumulatorCounters) => JSON.stringify(counters);++const parseCounters = (value: string | undefined): SelfReflectionAccumulatorCounters => {+ if (!value) return createInitialCounters();++ try {+ const parsed = JSON.parse(value) as Partial<SelfReflectionAccumulatorCounters>;++ return {+ correctionCount: Number(parsed.correctionCount ?? 0),+ failedToolCount: Number(parsed.failedToolCount ?? 0),+ negativeFeedbackCount: Number(parsed.negativeFeedbackCount ?? 0),+ receiptCount: Number(parsed.receiptCount ?? 0),+ runtimeStepCount: Number(parsed.runtimeStepCount ?? 0),+ sameToolFailureCount: Number(parsed.sameToolFailureCount ?? 0),+ toolCallCount: Number(parsed.toolCallCount ?? 0),+ };+ } catch {+ return createInitialCounters();+ }+};++const serializeReasons = (reasons: Set<SelfReflectionRequestReason>) =>+ JSON.stringify([...reasons]);++const parseReasons = (value: string | undefined): Set<SelfReflectionRequestReason> => {+ if (!value) return new Set<SelfReflectionRequestReason>();++ try {+ const parsed = JSON.parse(value);++ return new Set(+ Array.isArray(parsed)+ ? parsed.filter((item): item is SelfReflectionRequestReason => typeof item === 'string')+ : [],+ );+ } catch {+ return new Set<SelfReflectionRequestReason>();+ }+};++const serializeToolFailures = (toolFailures: Map<string, number>) =>+ JSON.stringify(Object.fromEntries(toolFailures));++const parseToolFailures = (value: string | undefined): Map<string, number> => {+ if (!value) return new Map<string, number>();++ try {+ const parsed = JSON.parse(value);+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {+ return new Map<string, number>();+ }++ return new Map(+ Object.entries(parsed)+ .map(([key, count]) => [key, Number(count)] as const)+ .filter(([, count]) => Number.isFinite(count)),+ );+ } catch {+ return new Map<string, number>();+ }+};++const createStateFromStoredFields = (+ fields: Awaited<ReturnType<AgentSignalPolicyStateStore['readPolicyState']>>,+): SelfReflectionAccumulatorState => ({+ counters: parseCounters(fields?.counters),+ emittedReasons: parseReasons(fields?.emittedReasons),+ toolFailures: parseToolFailures(fields?.toolFailures),+ windowStart: fields?.windowStart,+});++const createDecisionAfterRecord = (+ input: SelfReflectionAccumulatorRecordInput,+ scope: SelfReflectionAccumulatorScope,+ state: SelfReflectionAccumulatorState,+): SelfReflectionAccumulatorDecision => {+ const previousCounters = copyCounters(state.counters);++ state.windowStart = chooseEarlierTimestamp(state.windowStart, input.eventTimestamp);+ incrementCounters(state, input);++ const newlyCrossedReasons = getNewlyCrossedReasons(+ previousCounters,+ state.counters,+ input.eventType,+ );+ const reason = newlyCrossedReasons.find(+ (crossedReason) => !state.emittedReasons.has(crossedReason),+ );++ for (const crossedReason of newlyCrossedReasons) {+ state.emittedReasons.add(crossedReason);+ }++ if (!reason) {+ return { counters: copyCounters(state.counters), shouldRequest: false };+ }++ return {+ counters: copyCounters(state.counters),+ reason,+ scopeId: scope.scopeId,+ scopeType: scope.scopeType,+ shouldRequest: true,+ windowStart: state.windowStart,+ };+};++const incrementCounters = (+ state: SelfReflectionAccumulatorState,+ input: SelfReflectionAccumulatorRecordInput,+) => {+ const { counters } = state;++ switch (input.eventType) {+ case 'correction': {+ counters.correctionCount += 1;+ break;+ }++ case 'execution_failed': {+ break;+ }++ case 'negative_feedback': {+ counters.negativeFeedbackCount += 1;+ break;+ }++ case 'receipt': {+ counters.receiptCount += 1;+ break;+ }++ case 'runtime_step': {+ counters.runtimeStepCount += 1;+ break;+ }++ case 'tool_called':+ case 'tool_completed': {+ counters.toolCallCount += 1;+ break;+ }++ case 'tool_failed': {+ counters.failedToolCount += 1;+ counters.toolCallCount += 1;++ if (input.toolName) {+ const toolFailureCount = (state.toolFailures.get(input.toolName) ?? 0) + 1;++ state.toolFailures.set(input.toolName, toolFailureCount);+ counters.sameToolFailureCount = Math.max(counters.sameToolFailureCount, toolFailureCount);+ }++ break;+ }+ }+};++const didCrossThreshold = (previous: number, next: number, threshold: number) =>+ previous < threshold && next >= threshold;++const getNewlyCrossedReasons = (+ previous: SelfReflectionAccumulatorCounters,+ next: SelfReflectionAccumulatorCounters,+ eventType: SelfReflectionAccumulatorEventType,+): SelfReflectionRequestReason[] => {+ const reasons: SelfReflectionRequestReason[] = [];++ if (eventType === 'execution_failed') reasons.push('execution_failed');+ if (+ didCrossThreshold(+ previous.sameToolFailureCount,+ next.sameToolFailureCount,+ DEFAULT_THRESHOLDS.sameToolFailureCount,+ )+ ) {+ reasons.push('same_tool_failure_count');+ }+ if (+ didCrossThreshold(+ previous.failedToolCount,+ next.failedToolCount,+ DEFAULT_THRESHOLDS.failedToolCount,+ )+ ) {+ reasons.push('failed_tool_count');+ }+ if (+ didCrossThreshold(previous.toolCallCount, next.toolCallCount, DEFAULT_THRESHOLDS.toolCallCount)+ ) {+ reasons.push('tool_call_count');+ }+ if (+ didCrossThreshold(+ previous.correctionCount,+ next.correctionCount,+ DEFAULT_THRESHOLDS.correctionCount,+ )+ ) {+ reasons.push('user_correction_count');+ }+ if (+ didCrossThreshold(+ previous.runtimeStepCount,+ next.runtimeStepCount,+ DEFAULT_THRESHOLDS.runtimeStepCount,+ )+ ) {+ reasons.push('runtime_step_count');+ }+ if (+ didCrossThreshold(previous.receiptCount, next.receiptCount, DEFAULT_THRESHOLDS.receiptCount)+ ) {+ reasons.push('receipt_count');+ }++ return reasons;+};++/** Creates an in-memory weak-signal accumulator for one runtime or test lifecycle. */+export const createSelfReflectionAccumulator = (): SelfReflectionAccumulator => {+ const scopes = new Map<string, SelfReflectionAccumulatorState>();++ return {+ record: (input) => {+ const scope = resolveScope(input);++ if (!scope) return { shouldRequest: false };++ const scopeKey = getScopeKey(input, scope);+ const state = scopes.get(scopeKey) ?? createState();++ scopes.set(scopeKey, state);+ return createDecisionAfterRecord(input, scope, state);+ },+ };+};++/** Creates a durable weak-signal accumulator for workflow events processed one at a time. */+export const createDurableSelfReflectionAccumulator = (input: {+ policyStateStore: AgentSignalPolicyStateStore;+ ttlSeconds: number;+}): AsyncSelfReflectionAccumulator => ({+ record: async (recordInput) => {+ const scope = resolveScope(recordInput);++ if (!scope) return { shouldRequest: false };++ const scopeKey = getScopeKey(recordInput, scope);+ const state = createStateFromStoredFields(+ await input.policyStateStore.readPolicyState(SELF_REFLECTION_ACCUMULATOR_POLICY_ID, scopeKey),+ );+ const decision = createDecisionAfterRecord(recordInput, scope, state);++ await input.policyStateStore.writePolicyState(+ SELF_REFLECTION_ACCUMULATOR_POLICY_ID,+ scopeKey,+ {+ counters: serializeCounters(state.counters),+ emittedReasons: serializeReasons(state.emittedReasons),+ lastSourceId: recordInput.sourceId,+ toolFailures: serializeToolFailures(state.toolFailures),+ version: '1',+ ...(state.windowStart ? { windowStart: state.windowStart } : {}),+ },+ input.ttlSeconds,+ );++ return decision;+ },+});diff --git a/src/server/services/agentSignal/procedure/emitToolOutcome.ts b/src/server/services/agentSignal/procedure/emitToolOutcome.tsindex 3185d7a57d5..ca7ec11e2e9 100644--- a/src/server/services/agentSignal/procedure/emitToolOutcome.ts+++ b/src/server/services/agentSignal/procedure/emitToolOutcome.ts@@ -3,7 +3,7 @@ import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';import type { AgentSignalExecutionContext } from '../emitter';import { enqueueAgentSignalSourceEvent } from '../emitter';import type { AgentSignalPolicyStateStore } from '../store/types';-import { appendProcedureAccumulatorRecord } from './accumulator';+import { appendProcedureAccumulatorRecord } from './accumulators/procedure';import { createProcedureKey } from './keys';import { createProcedureMarker, writeProcedureMarker } from './marker';import { appendProcedureReceipt } from './receipt';diff --git a/src/server/services/agentSignal/procedure/index.ts b/src/server/services/agentSignal/procedure/index.tsindex af62244f22e..3c0a5dfa597 100644--- a/src/server/services/agentSignal/procedure/index.ts+++ b/src/server/services/agentSignal/procedure/index.ts@@ -1,9 +1,11 @@import { createProcedureStateService } from '../services/procedureStateService';import type { AgentSignalPolicyStateStore } from '../store/types';+import type { ToolOutcomeSelfReflectionDeps } from './toolOutcome';import type { AgentSignalProcedureRecord } from './types';export { createProcedureStateService } from '../services/procedureStateService';-export * from './accumulator';+export * from './accumulators/procedure';+export * from './accumulators/selfReflection';export * from './batchScorer';export * from './emitToolOutcome';export * from './inspector';@@ -22,6 +24,8 @@ export interface CreateProcedurePolicyOptionsInput {now?: () => number;/** Policy-state store shared by records, markers, receipts, and accumulators. */policyStateStore: AgentSignalPolicyStateStore;+ /** Optional weak-signal self-reflection wiring for procedure-owned tool outcomes. */+ selfReflection?: ToolOutcomeSelfReflectionDeps;/** TTL in seconds for procedure policy-state fields. */ttlSeconds: number;}@@ -70,6 +74,7 @@ export const createProcedurePolicyOptions = (input: CreateProcedurePolicyOptionsrecordStore: {write: (record: AgentSignalProcedureRecord) => procedureState.records.write(record),},+ ...(input.selfReflection ? { selfReflection: input.selfReflection } : {}),ttlSeconds: input.ttlSeconds,};};diff --git a/src/server/services/agentSignal/procedure/inspector.ts b/src/server/services/agentSignal/procedure/inspector.tsindex c681002e1a0..3bf5f5c318b 100644--- a/src/server/services/agentSignal/procedure/inspector.ts+++ b/src/server/services/agentSignal/procedure/inspector.ts@@ -37,7 +37,7 @@ export interface AgentSignalProcedureInspectionSnapshot {* - Store values are JSON fields written by procedure helpers** Returns:- * - Inspection snapshots without exposing a production route+ * - Inspection snapshots without exposing a server route*/export class AgentSignalProcedureInspector {constructor(private readonly store: Pick<AgentSignalPolicyStateStore, 'readPolicyState'>) {}diff --git a/src/server/services/agentSignal/procedure/toolOutcome.ts b/src/server/services/agentSignal/procedure/toolOutcome.tsindex 3261b190a81..12bb7c51b0a 100644--- a/src/server/services/agentSignal/procedure/toolOutcome.ts+++ b/src/server/services/agentSignal/procedure/toolOutcome.ts@@ -5,6 +5,12 @@ import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';import { AGENT_SIGNAL_POLICY_SIGNAL_TYPES } from '../policies/types';import type { RuntimeProcessorContext } from '../runtime/context';import { defineSourceHandler } from '../runtime/middleware';+import type { SelfReflectionService } from '../services/selfReflection';+import type {+ AsyncSelfReflectionAccumulator,+ SelfReflectionAccumulatorDecision,+ SelfReflectionAccumulatorEventType,+} from './accumulators/selfReflection';import { createProcedureKey, getCoarseProcedureDomain } from './keys';import { createProcedureMarker } from './marker';import { createProcedureRecord } from './record';@@ -14,6 +20,28 @@ import type {AgentSignalProcedureRecord,} from './types';+/**+ * Stable self-reflection weak-signal window coordinates for one tool outcome.+ */+export interface ToolOutcomeSelfReflectionWindowInput {+ /** Accumulator decision that crossed a self-reflection threshold. */+ decision: SelfReflectionAccumulatorDecision;+ /** Normalized source being handled by the tool-outcome procedure handler. */+ source: AgentSignalSource;+}++/**+ * Optional self-reflection dependencies for tool outcome weak-signal wiring.+ */+export interface ToolOutcomeSelfReflectionDeps {+ /** Records weak tool-outcome signals across a caller-owned lifecycle. */+ accumulator: AsyncSelfReflectionAccumulator;+ /** Provides the stable beginning of the accumulated weak-signal window. */+ getWindowStart: (input: ToolOutcomeSelfReflectionWindowInput) => string;+ /** Emits self-reflection requests when an accumulator threshold crosses. */+ service: SelfReflectionService;+}+/*** Storage dependencies for the tool outcome procedure source handler.*/@@ -28,6 +56,8 @@ export interface ToolOutcomeProcedureDeps {receiptStore: { append: (receipt: AgentSignalProcedureReceipt) => Promise<void> };/** Writes the compact procedure record. */recordStore: { write: (record: AgentSignalProcedureRecord) => Promise<void> };+ /** Optional self-reflection service wiring owned by a stable runtime lifecycle. */+ selfReflection?: ToolOutcomeSelfReflectionDeps;/** TTL used for marker expiration and policy-state writes. */ttlSeconds: number;}@@ -38,13 +68,17 @@ const TOOL_OUTCOME_SOURCE_TYPES = [] as const;interface ToolOutcomePayload {+ agentId?: string;domainKey?: string;intentClass?: string;messageId?: string;operationId?: string;outcome?: { status?: string; summary?: string };relatedObjects?: AgentSignalProcedureRecord['relatedObjects'];+ taskId?: string;+ tool?: { apiName?: string; identifier?: string };toolCallId?: string;+ topicId?: string;}const shouldWriteHandledMarker = (input: {@@ -65,6 +99,108 @@ const shouldWriteHandledMarker = (input: {return false;};+const resolveSelfReflectionEventType = (status: string): SelfReflectionAccumulatorEventType => {+ return status === 'failed' ? 'tool_failed' : 'tool_completed';+};++const resolveToolName = (payload: ToolOutcomePayload) =>+ payload.tool?.apiName ?? payload.tool?.identifier;++/**+ * Normalizes a millisecond timestamp into an ISO string only when Date can represent it.+ *+ * Before:+ * - 4000+ * - Number.NaN+ *+ * After:+ * - "1970-01-01T00:00:04.000Z"+ * - undefined+ */+const toSafeIsoTimestamp = (timestamp: number): string | undefined => {+ if (!Number.isFinite(timestamp)) return;++ try {+ return new Date(timestamp).toISOString();+ } catch {+ return;+ }+};++/**+ * Resolves self-reflection window end from source time, then the procedure write clock.+ *+ * Before:+ * - sourceTimestamp: Number.NaN, fallbackTimestamp: 4000+ *+ * After:+ * - "1970-01-01T00:00:04.000Z"+ */+const resolveSelfReflectionWindowEnd = (input: {+ fallbackTimestamp: number;+ sourceTimestamp: number;+}) => {+ return toSafeIsoTimestamp(input.sourceTimestamp) ?? toSafeIsoTimestamp(input.fallbackTimestamp);+};++const handleSelfReflectionToolOutcome = async (input: {+ deps: ToolOutcomeProcedureDeps;+ fallbackTimestamp: number;+ payload: ToolOutcomePayload;+ source: AgentSignalSource;+}) => {+ try {+ const { selfReflection } = input.deps;+ if (!selfReflection) return;++ const userId = input.source.scope?.userId;+ const agentId = input.payload.agentId ?? input.source.scope?.agentId;+ const status = input.payload.outcome?.status;+ if (!userId || !agentId || !status) return;++ const windowEnd = resolveSelfReflectionWindowEnd({+ fallbackTimestamp: input.fallbackTimestamp,+ sourceTimestamp: input.source.timestamp,+ });+ if (!windowEnd) return;++ const decision = await selfReflection.accumulator.record({+ agentId,+ eventType: resolveSelfReflectionEventType(status),+ eventTimestamp: windowEnd,+ operationId: input.payload.operationId,+ sourceId: input.source.sourceId,+ taskId: input.payload.taskId ?? input.source.scope?.taskId,+ toolName: resolveToolName(input.payload),+ topicId: input.payload.topicId ?? input.source.scope?.topicId,+ userId,+ });++ if (!decision.shouldRequest || !decision.reason || !decision.scopeId || !decision.scopeType) {+ return;+ }++ void selfReflection.service+ .requestSelfReflection({+ agentId,+ operationId: input.payload.operationId,+ reason: decision.reason,+ scopeId: decision.scopeId,+ scopeType: decision.scopeType,+ taskId: input.payload.taskId ?? input.source.scope?.taskId,+ topicId: input.payload.topicId ?? input.source.scope?.topicId,+ userId,+ windowEnd,+ windowStart: selfReflection.getWindowStart({ decision, source: input.source }),+ })+ .catch((error) => {+ console.error('[AgentSignal] Failed to request self-reflection:', error);+ });+ } catch (error) {+ console.error('[AgentSignal] Failed to request self-reflection:', error);+ }+};+/*** Creates the source handler that normalizes direct tool outcomes into procedure projections.*@@ -78,6 +214,20 @@ const shouldWriteHandledMarker = (input: {** Returns:* - Source handler that dispatches a `signal.tool.outcome` signal+ *+ * Triggering workflow:+ *+ * {@link defineSourceHandler}+ * -> `source.tool-outcome.procedure`+ * -> `tool.outcome.completed` / `tool.outcome.failed`+ * -> {@link createToolOutcomeSourceHandler}+ *+ * Upstream:+ * - {@link defineSourceHandler}+ *+ * Downstream:+ * - {@link createProcedureRecord}+ * - {@link SelfReflectionService.requestSelfReflection}*/export const createToolOutcomeSourceHandler = (deps: ToolOutcomeProcedureDeps) =>defineSourceHandler(@@ -137,6 +287,8 @@ export const createToolOutcomeSourceHandler = (deps: ToolOutcomeProcedureDeps) =updatedAt: now,});+ await handleSelfReflectionToolOutcome({ deps, fallbackTimestamp: now, payload, source });+if (shouldWriteHandledMarker({domainKey: payload.domainKey,diff --git a/src/server/services/agentSignal/processors/classifiers.ts b/src/server/services/agentSignal/processors/classifiers.tsindex 7dbba82f1c9..11b6d50016d 100644--- a/src/server/services/agentSignal/processors/classifiers.ts+++ b/src/server/services/agentSignal/processors/classifiers.ts@@ -1,7 +1,6 @@import {- AGENT_SIGNAL_SOURCE_TYPES,type AgentSignalSourceVariants,- type SourceAgentUserMessage,+ isAgentUserMessageSource,} from '@lobechat/agent-signal/source';import {@@ -51,12 +50,6 @@ export type FeedbackDomainClassifierSignal =| SignalFeedbackDomainPrompt| SignalFeedbackDomainSkill;-const isAgentUserMessageSource = (- source: AgentSignalSourceVariants,-): source is SourceAgentUserMessage => {- return source.sourceType === AGENT_SIGNAL_SOURCE_TYPES.agentUserMessage;-};-const isRecordLike = (value: unknown): value is Record<PropertyKey, unknown> => {return typeof value === 'object' && value !== null;};diff --git a/src/server/services/agentSignal/services/__tests__/receiptService.selfReflect.test.ts b/src/server/services/agentSignal/services/__tests__/receiptService.selfReflect.test.tsnew file mode 100644index 00000000000..7b0cb218797--- /dev/null+++ b/src/server/services/agentSignal/services/__tests__/receiptService.selfReflect.test.ts@@ -0,0 +1,172 @@+// @vitest-environment node+import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';+import { describe, expect, it } from 'vitest';++import type { MaintenanceActionResult, MaintenancePlan } from '../maintenance/types';+import {+ MaintenanceActionStatus,+ MaintenanceApplyMode,+ MaintenanceReviewScope,+ MaintenanceRisk,+ ReviewRunStatus,+} from '../maintenance/types';+import { createMaintenanceActionReceipt, createReviewSummaryReceipt } from '../receiptService';++const nightlyPlan = {+ actions: [+ {+ actionType: 'write_memory',+ applyMode: MaintenanceApplyMode.AutoApply,+ confidence: 0.93,+ dedupeKey: 'memory:concise',+ evidenceRefs: [{ id: 'topic-1', summary: 'User prefers concise summaries.', type: 'topic' }],+ idempotencyKey: 'nightly-review:user-1:agent-1:2026-05-04:write_memory:memory:concise',+ operation: {+ domain: 'memory',+ input: { content: 'User prefers concise summaries.', userId: 'user-1' },+ operation: 'write',+ },+ rationale: 'Stable preference found in the review window.',+ risk: MaintenanceRisk.Low,+ target: { topicIds: ['topic-1'] },+ },+ ],+ localDate: '2026-05-04',+ plannerVersion: 'test-planner',+ reviewScope: MaintenanceReviewScope.Nightly,+ summary: 'Saved one stable preference.',+} satisfies MaintenancePlan;++const actionResult = {+ idempotencyKey: 'nightly-review:user-1:agent-1:2026-05-04:write_memory:memory:concise',+ receiptId: 'receipt-action-1',+ resourceId: 'memory-1',+ status: MaintenanceActionStatus.Applied,+ summary: 'Memory written.',+} satisfies MaintenanceActionResult;++describe('createReviewSummaryReceipt', () => {+ /**+ * @example+ * A completed nightly review produces one source-level audit receipt.+ */+ it('projects one summary receipt for completed nightly reviews', () => {+ const receipt = createReviewSummaryReceipt({+ agentId: 'agent-1',+ createdAt: 1_700_000,+ localDate: '2026-05-04',+ plan: nightlyPlan,+ result: {+ actions: [actionResult],+ sourceId: 'nightly-review:user-1:agent-1:2026-05-04',+ status: ReviewRunStatus.Completed,+ },+ sourceId: 'nightly-review:user-1:agent-1:2026-05-04',+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentNightlyReviewRequested,+ timezone: 'Asia/Shanghai',+ userId: 'user-1',+ });++ expect(receipt).toMatchObject({+ agentId: 'agent-1',+ id: 'nightly-review:user-1:agent-1:2026-05-04:review-summary',+ kind: 'review',+ sourceId: 'nightly-review:user-1:agent-1:2026-05-04',+ topicId: 'nightly-review:user-1:agent-1:2026-05-04',+ userId: 'user-1',+ });+ expect(receipt.metadata).toMatchObject({+ actionCount: 1,+ localDate: '2026-05-04',+ reviewScope: MaintenanceReviewScope.Nightly,+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentNightlyReviewRequested,+ timezone: 'Asia/Shanghai',+ });+ });++ /**+ * @example+ * A topic-scoped self-reflection receipt remains indexed by the original topic.+ */+ it('keeps self-reflection receipts topic local when a topic id is available', () => {+ const receipt = createReviewSummaryReceipt({+ agentId: 'agent-1',+ createdAt: 1_700_000,+ plan: { ...nightlyPlan, reviewScope: MaintenanceReviewScope.SelfReflection },+ result: { actions: [actionResult], status: ReviewRunStatus.Completed },+ scopeId: 'topic-1',+ scopeType: 'topic',+ sourceId: 'self-reflection:user-1:agent-1:topic:topic-1:receipt_count:window',+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentSelfReflectionRequested,+ topicId: 'topic-1',+ userId: 'user-1',+ });++ expect(receipt.topicId).toBe('topic-1');+ expect(receipt.metadata).toMatchObject({+ reviewScope: MaintenanceReviewScope.SelfReflection,+ scopeId: 'topic-1',+ scopeType: 'topic',+ });+ });+});++describe('createMaintenanceActionReceipt', () => {+ /**+ * @example+ * Applied and proposed maintenance actions become durable action receipts.+ */+ it('projects applied maintenance actions with action metadata and target resource', () => {+ const receipt = createMaintenanceActionReceipt({+ action: nightlyPlan.actions[0],+ agentId: 'agent-1',+ createdAt: 1_700_001,+ localDate: '2026-05-04',+ result: actionResult,+ reviewScope: MaintenanceReviewScope.Nightly,+ sourceId: 'nightly-review:user-1:agent-1:2026-05-04',+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentNightlyReviewRequested,+ timezone: 'Asia/Shanghai',+ userId: 'user-1',+ });++ expect(receipt).toMatchObject({+ id: 'nightly-review:user-1:agent-1:2026-05-04:write_memory:memory:concise:action',+ kind: 'memory',+ status: 'applied',+ target: {+ id: 'memory-1',+ summary: 'Memory written.',+ title: 'Memory written.',+ type: 'memory',+ },+ });+ expect(receipt?.metadata).toMatchObject({+ actionStatus: MaintenanceActionStatus.Applied,+ actionType: 'write_memory',+ localDate: '2026-05-04',+ reviewScope: MaintenanceReviewScope.Nightly,+ });+ });++ /**+ * @example+ * Skipped maintenance actions do not create action receipts.+ */+ it('does not project skipped action receipts', () => {+ expect(+ createMaintenanceActionReceipt({+ action: nightlyPlan.actions[0],+ agentId: 'agent-1',+ result: {+ idempotencyKey: actionResult.idempotencyKey,+ status: MaintenanceActionStatus.Skipped,+ },+ reviewScope: MaintenanceReviewScope.Nightly,+ sourceId: 'nightly-review:user-1:agent-1:2026-05-04',+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentNightlyReviewRequested,+ userId: 'user-1',+ }),+ ).toBeUndefined();+ });+});diff --git a/src/server/services/agentSignal/services/__tests__/selfIterationIntent.test.ts b/src/server/services/agentSignal/services/__tests__/selfIterationIntent.test.tsnew file mode 100644index 00000000000..681f2809ee7--- /dev/null+++ b/src/server/services/agentSignal/services/__tests__/selfIterationIntent.test.ts@@ -0,0 +1,345 @@+import { describe, expect, it, vi } from 'vitest';++import type { AgentSignalSourceEventInput } from '@/server/services/agentSignal/emitter';++import type { SelfIterationIntentAction, SelfIterationIntentKind } from '../selfIterationIntent';+import { createSelfIterationIntentService } from '../selfIterationIntent';++const createStrongIntentInput = () => ({+ action: 'refine' as const,+ confidence: 0.92,+ evidenceRefs: [{ id: 'msg-1', type: 'message' as const }],+ kind: 'skill' as const,+ reason: 'The agent noticed a reusable release-note correction.',+ summary: 'Refine release note workflow skill.',+});++const createEnqueueSource = () =>+ vi+ .fn<+ (+ input: AgentSignalSourceEventInput<'agent.self_iteration_intent.declared'>,+ ) => Promise<unknown>+ >()+ .mockResolvedValue({ enqueued: true });++describe('selfIterationIntent', () => {+ /**+ * @example+ * declareSelfIterationIntent emits a source and does not mutate resources.+ */+ it('emits declared intent source events', async () => {+ const enqueueSource = createEnqueueSource();+ const service = createSelfIterationIntentService({+ enqueueSource,+ nextToolCallId: () => 'tool-call-1',+ });++ const result = await service.declareIntent({+ agentId: 'agent-1',+ input: createStrongIntentInput(),+ topicId: 'topic-1',+ userId: 'user-1',+ });++ expect(result).toEqual({+ accepted: true,+ sourceId: 'self-iteration-intent:user-1:agent-1:topic:topic-1:tool-call-1',+ strength: 'strong',+ });+ expect(enqueueSource).toHaveBeenCalledWith({+ payload: {+ action: 'refine',+ agentId: 'agent-1',+ confidence: 0.92,+ evidenceRefs: [{ id: 'msg-1', type: 'message' }],+ kind: 'skill',+ reason: 'The agent noticed a reusable release-note correction.',+ summary: 'Refine release note workflow skill.',+ toolCallId: 'tool-call-1',+ topicId: 'topic-1',+ userId: 'user-1',+ },+ scopeKey: 'topic:topic-1',+ sourceId: 'self-iteration-intent:user-1:agent-1:topic:topic-1:tool-call-1',+ sourceType: 'agent.self_iteration_intent.declared',+ });+ });++ /**+ * @example+ * Empty evidence is accepted as a source but marked weak for downstream downgrade.+ */+ it('marks evidence-poor declarations as weak', async () => {+ const service = createSelfIterationIntentService({+ enqueueSource: createEnqueueSource(),+ nextToolCallId: () => 'tool-call-1',+ });++ await expect(+ service.declareIntent({+ agentId: 'agent-1',+ input: {+ action: 'write',+ confidence: 0.6,+ kind: 'memory',+ reason: 'Maybe remember this.',+ summary: 'Weak candidate.',+ },+ topicId: 'topic-1',+ userId: 'user-1',+ }),+ ).resolves.toMatchObject({ accepted: true, strength: 'weak' });+ });++ /**+ * @example+ * The fourth accepted declaration in the same topic returns a rate-limited result.+ */+ it('rate limits after three accepted declarations in one topic scope', async () => {+ const enqueueSource = createEnqueueSource();+ const service = createSelfIterationIntentService({+ enqueueSource,+ nextToolCallId: vi+ .fn()+ .mockReturnValueOnce('tool-call-1')+ .mockReturnValueOnce('tool-call-2')+ .mockReturnValueOnce('tool-call-3')+ .mockReturnValueOnce('tool-call-4'),+ });++ for (const toolCallId of ['tool-call-1', 'tool-call-2', 'tool-call-3']) {+ await expect(+ service.declareIntent({+ agentId: 'agent-1',+ input: createStrongIntentInput(),+ toolCallId,+ topicId: 'topic-1',+ userId: 'user-1',+ }),+ ).resolves.toMatchObject({ accepted: true });+ }++ await expect(+ service.declareIntent({+ agentId: 'agent-1',+ input: createStrongIntentInput(),+ topicId: 'topic-1',+ userId: 'user-1',+ }),+ ).resolves.toEqual({ accepted: false, reason: 'rate_limited', strength: 'strong' });+ expect(enqueueSource).toHaveBeenCalledTimes(3);+ });++ /**+ * @example+ * Caller-provided tool-call ids produce stable source ids and do not consume generated ids.+ */+ it('uses explicit toolCallId without calling nextToolCallId', async () => {+ const nextToolCallId = vi.fn(() => 'generated-tool-call');+ const enqueueSource = createEnqueueSource();+ const service = createSelfIterationIntentService({+ enqueueSource,+ nextToolCallId,+ });++ await expect(+ service.declareIntent({+ agentId: 'agent-1',+ input: createStrongIntentInput(),+ toolCallId: 'explicit-tool-call',+ topicId: 'topic-1',+ userId: 'user-1',+ }),+ ).resolves.toMatchObject({+ sourceId: 'self-iteration-intent:user-1:agent-1:topic:topic-1:explicit-tool-call',+ });++ expect(nextToolCallId).not.toHaveBeenCalled();+ });++ /**+ * @example+ * Invalid action, kind, or confidence declarations return rejection reasons and do not enqueue.+ */+ it('rejects invalid action kind and confidence declarations', async () => {+ const enqueueSource = createEnqueueSource();+ const service = createSelfIterationIntentService({+ enqueueSource,+ nextToolCallId: () => 'tool-call-1',+ });++ await expect(+ service.declareIntent({+ agentId: 'agent-1',+ input: {+ ...createStrongIntentInput(),+ action: 'delete' as unknown as SelfIterationIntentAction,+ },+ topicId: 'topic-1',+ userId: 'user-1',+ }),+ ).resolves.toEqual({ accepted: false, reason: 'invalid_action', strength: 'weak' });+ await expect(+ service.declareIntent({+ agentId: 'agent-1',+ input: {+ ...createStrongIntentInput(),+ kind: 'preference' as unknown as SelfIterationIntentKind,+ },+ topicId: 'topic-1',+ userId: 'user-1',+ }),+ ).resolves.toEqual({ accepted: false, reason: 'invalid_kind', strength: 'weak' });+ await expect(+ service.declareIntent({+ agentId: 'agent-1',+ input: {+ ...createStrongIntentInput(),+ confidence: 1.1,+ },+ topicId: 'topic-1',+ userId: 'user-1',+ }),+ ).resolves.toEqual({ accepted: false, reason: 'invalid_confidence', strength: 'weak' });+ await expect(+ service.declareIntent({+ agentId: 'agent-1',+ input: {+ ...createStrongIntentInput(),+ action: 'delete' as unknown as SelfIterationIntentAction,+ confidence: Number.NaN,+ },+ topicId: 'topic-1',+ userId: 'user-1',+ }),+ ).resolves.toEqual({ accepted: false, reason: 'invalid_action', strength: 'weak' });+ expect(enqueueSource).not.toHaveBeenCalled();+ });++ /**+ * @example+ * Operation-scoped declarations rate-limit independently from the surrounding topic.+ */+ it('uses operationId as the rate-limit scope when present', async () => {+ const enqueueSource = createEnqueueSource();+ const service = createSelfIterationIntentService({+ enqueueSource,+ nextToolCallId: vi+ .fn()+ .mockReturnValueOnce('op-tool-call-1')+ .mockReturnValueOnce('op-tool-call-2')+ .mockReturnValueOnce('op-tool-call-3')+ .mockReturnValueOnce('topic-tool-call-1'),+ });++ for (const toolCallId of ['op-tool-call-1', 'op-tool-call-2', 'op-tool-call-3']) {+ await service.declareIntent({+ agentId: 'agent-1',+ input: createStrongIntentInput(),+ operationId: 'operation-1',+ toolCallId,+ topicId: 'topic-1',+ userId: 'user-1',+ });+ }++ await expect(+ service.declareIntent({+ agentId: 'agent-1',+ input: createStrongIntentInput(),+ topicId: 'topic-1',+ userId: 'user-1',+ }),+ ).resolves.toMatchObject({ accepted: true });+ expect(enqueueSource).toHaveBeenLastCalledWith(+ expect.objectContaining({ scopeKey: 'topic:topic-1' }),+ );+ expect(enqueueSource).toHaveBeenCalledWith(+ expect.objectContaining({+ payload: expect.objectContaining({ operationId: 'operation-1' }),+ sourceId: 'self-iteration-intent:user-1:agent-1:operation:operation-1:op-tool-call-1',+ scopeKey: 'operation:operation-1',+ }),+ );+ });++ /**+ * @example+ * Matching tool-call ids in different scopes produce different source ids.+ */+ it('includes operation or topic scope identity in source ids', async () => {+ const enqueueSource = createEnqueueSource();+ const service = createSelfIterationIntentService({+ enqueueSource,+ nextToolCallId: () => 'shared-tool-call',+ });++ const operationResult = await service.declareIntent({+ agentId: 'agent-1',+ input: createStrongIntentInput(),+ operationId: 'operation-1',+ topicId: 'topic-1',+ userId: 'user-1',+ });+ const topicResult = await service.declareIntent({+ agentId: 'agent-1',+ input: createStrongIntentInput(),+ topicId: 'topic-1',+ userId: 'user-1',+ });++ expect(operationResult.sourceId).toBe(+ 'self-iteration-intent:user-1:agent-1:operation:operation-1:shared-tool-call',+ );+ expect(topicResult.sourceId).toBe(+ 'self-iteration-intent:user-1:agent-1:topic:topic-1:shared-tool-call',+ );+ expect(operationResult.sourceId).not.toBe(topicResult.sourceId);+ });++ /**+ * @example+ * Gates can reject declarations before enqueueing source events.+ */+ it('honors declaration and enqueue gates', async () => {+ const enqueueSource = createEnqueueSource();+ const blockedDeclarationService = createSelfIterationIntentService({+ canDeclareIntent: vi.fn().mockResolvedValue(false),+ enqueueSource,+ nextToolCallId: () => 'tool-call-1',+ });+ const blockedEnqueueService = createSelfIterationIntentService({+ canEnqueue: vi.fn().mockResolvedValue(false),+ enqueueSource,+ nextToolCallId: () => 'tool-call-1',+ });++ await expect(+ blockedDeclarationService.declareIntent({+ agentId: 'agent-1',+ input: createStrongIntentInput(),+ topicId: 'topic-1',+ userId: 'user-1',+ }),+ ).resolves.toEqual({+ accepted: false,+ reason: 'intent_gate_rejected',+ strength: 'strong',+ });+ await expect(+ blockedEnqueueService.declareIntent({+ agentId: 'agent-1',+ input: createStrongIntentInput(),+ topicId: 'topic-1',+ userId: 'user-1',+ }),+ ).resolves.toEqual({+ accepted: false,+ reason: 'enqueue_gate_rejected',+ sourceId: 'self-iteration-intent:user-1:agent-1:topic:topic-1:tool-call-1',+ strength: 'strong',+ });+ expect(enqueueSource).not.toHaveBeenCalled();+ });+});diff --git a/src/server/services/agentSignal/services/__tests__/selfReflection.test.ts b/src/server/services/agentSignal/services/__tests__/selfReflection.test.tsnew file mode 100644index 00000000000..f28ea15cfbd--- /dev/null+++ b/src/server/services/agentSignal/services/__tests__/selfReflection.test.ts@@ -0,0 +1,132 @@+import { describe, expect, it, vi } from 'vitest';++import type { AgentSignalSourceEventInput } from '@/server/services/agentSignal/emitter';++import { createSelfReflectionService } from '../selfReflection';++describe('selfReflection', () => {+ /**+ * @example+ * Threshold decision emits a stable self-reflection source event.+ */+ it('emits self-reflection source events from threshold decisions', async () => {+ const enqueueSource = vi+ .fn<+ (input: AgentSignalSourceEventInput<'agent.self_reflection.requested'>) => Promise<unknown>+ >()+ .mockResolvedValue({ enqueued: true });+ const service = createSelfReflectionService({+ enqueueSource,+ });++ await service.requestSelfReflection({+ agentId: 'agent-1',+ reason: 'failed_tool_count',+ scopeId: 'task-1',+ scopeType: 'task',+ taskId: 'task-1',+ userId: 'user-1',+ windowEnd: '2026-05-04T14:30:00.000Z',+ windowStart: '2026-05-04T14:00:00.000Z',+ });++ expect(enqueueSource).toHaveBeenCalledWith({+ payload: {+ agentId: 'agent-1',+ reason: 'failed_tool_count',+ scopeId: 'task-1',+ scopeType: 'task',+ taskId: 'task-1',+ userId: 'user-1',+ windowEnd: '2026-05-04T14:30:00.000Z',+ windowStart: '2026-05-04T14:00:00.000Z',+ },+ sourceId:+ 'self-reflection:user-1:agent-1:task:task-1:failed_tool_count:2026-05-04T14:00:00.000Z:2026-05-04T14:30:00.000Z',+ sourceType: 'agent.self_reflection.requested',+ });+ });++ /**+ * @example+ * Disabled request gates skip enqueueing before source payload creation crosses side-effect+ * boundaries.+ */+ it('skips enqueueing when request gate rejects the reflection', async () => {+ const enqueueSource = vi+ .fn<+ (input: AgentSignalSourceEventInput<'agent.self_reflection.requested'>) => Promise<unknown>+ >()+ .mockResolvedValue({ enqueued: true });+ const canRequestSelfReflection = vi.fn().mockResolvedValue(false);+ const service = createSelfReflectionService({+ canRequestSelfReflection,+ enqueueSource,+ });++ const result = await service.requestSelfReflection({+ agentId: 'agent-1',+ reason: 'failed_tool_count',+ scopeId: 'task-1',+ scopeType: 'task',+ taskId: 'task-1',+ userId: 'user-1',+ windowEnd: '2026-05-04T14:30:00.000Z',+ windowStart: '2026-05-04T14:00:00.000Z',+ });++ expect(result).toEqual({ enqueued: false, reason: 'request_gate_rejected' });+ expect(enqueueSource).not.toHaveBeenCalled();+ });++ /**+ * @example+ * Disabled enqueue gates skip the queue call after the stable source event is known.+ */+ it('skips enqueueing when enqueue gate rejects the source event', async () => {+ const enqueueSource = vi+ .fn<+ (input: AgentSignalSourceEventInput<'agent.self_reflection.requested'>) => Promise<unknown>+ >()+ .mockResolvedValue({ enqueued: true });+ const canEnqueue = vi.fn().mockResolvedValue(false);+ const service = createSelfReflectionService({+ canEnqueue,+ enqueueSource,+ });++ const result = await service.requestSelfReflection({+ agentId: 'agent-1',+ reason: 'failed_tool_count',+ scopeId: 'task-1',+ scopeType: 'task',+ taskId: 'task-1',+ userId: 'user-1',+ windowEnd: '2026-05-04T14:30:00.000Z',+ windowStart: '2026-05-04T14:00:00.000Z',+ });++ expect(canEnqueue).toHaveBeenCalledWith({+ payload: {+ agentId: 'agent-1',+ reason: 'failed_tool_count',+ scopeId: 'task-1',+ scopeType: 'task',+ taskId: 'task-1',+ userId: 'user-1',+ windowEnd: '2026-05-04T14:30:00.000Z',+ windowStart: '2026-05-04T14:00:00.000Z',+ },+ sourceId:+ 'self-reflection:user-1:agent-1:task:task-1:failed_tool_count:2026-05-04T14:00:00.000Z:2026-05-04T14:30:00.000Z',+ sourceType: 'agent.self_reflection.requested',+ });+ expect(result).toEqual({+ enqueued: false,+ reason: 'enqueue_gate_rejected',+ sourceId:+ 'self-reflection:user-1:agent-1:task:task-1:failed_tool_count:2026-05-04T14:00:00.000Z:2026-05-04T14:30:00.000Z',+ });+ expect(enqueueSource).not.toHaveBeenCalled();+ });+});diff --git a/src/server/services/agentSignal/services/actionServices.ts b/src/server/services/agentSignal/services/actionServices.tsindex d5c88f67cf2..d25f4178f97 100644--- a/src/server/services/agentSignal/services/actionServices.ts+++ b/src/server/services/agentSignal/services/actionServices.ts@@ -70,7 +70,7 @@ export interface AgentSignalActionServices {** Use when:* - Handlers need stable memory and skill action planning without owning payload construction- * - Tests need injectable action services while preserving production defaults+ * - Tests need injectable action services while preserving server defaults** Expects:* - Input signals have already been narrowed by the handler control flowdiff --git a/src/server/services/agentSignal/services/index.ts b/src/server/services/agentSignal/services/index.tsindex 000a14a8aaf..106e43ddcba 100644--- a/src/server/services/agentSignal/services/index.ts+++ b/src/server/services/agentSignal/services/index.ts@@ -1,5 +1,15 @@export * from './actionServices';export * from './classifierServices';+export * from './maintenance/brief';+export * from './maintenance/executor';+export * from './maintenance/memory';+export * from './maintenance/nightlyCollector';+export * from './maintenance/nightlySchedule';+export * from './maintenance/planner';+export * from './maintenance/skill';+export * from './maintenance/types';export * from './procedureStateService';export * from './receiptService';+export * from './selfIterationIntent';+export * from './selfReflection';export * from './types';diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/brief.test.ts b/src/server/services/agentSignal/services/maintenance/__tests__/brief.test.tsnew file mode 100644index 00000000000..3cf5788a2cf--- /dev/null+++ b/src/server/services/agentSignal/services/maintenance/__tests__/brief.test.ts@@ -0,0 +1,238 @@+// @vitest-environment node+import { describe, expect, it, vi } from 'vitest';++import { BriefModel } from '@/database/models/brief';++import { createBriefMaintenanceService, createServerMaintenanceBriefWriter } from '../brief';+import { MaintenanceActionStatus, ReviewRunStatus } from '../types';++describe('briefMaintenanceService', () => {+ /**+ * @example+ * Applied nightly actions produce an insight brief with stable trigger metadata.+ */+ it('projects applied nightly results to insight briefs', () => {+ const service = createBriefMaintenanceService();++ const brief = service.projectNightlyReviewBrief({+ agentId: 'agent-1',+ localDate: '2026-05-04',+ result: {+ actions: [+ {+ idempotencyKey: 'source:write_memory:memory:concise',+ receiptId: 'receipt-1',+ resourceId: 'mem-1',+ status: MaintenanceActionStatus.Applied,+ summary: 'Saved concise PR summary preference.',+ },+ ],+ sourceId: 'nightly-review:user-1:agent-1:2026-05-04',+ status: ReviewRunStatus.Completed,+ },+ reviewWindowEnd: '2026-05-04T14:30:00.000Z',+ reviewWindowStart: '2026-05-03T16:00:00.000Z',+ timezone: 'Asia/Shanghai',+ userId: 'user-1',+ });++ expect(brief).toMatchObject({+ agentId: 'agent-1',+ trigger: 'agent-signal:nightly-review',+ type: 'insight',+ });+ expect(brief?.metadata).toMatchObject({+ actionCounts: { applied: 1, failed: 0, proposed: 0, skipped: 0 },+ localDate: '2026-05-04',+ outcome: 'applied',+ receiptIds: ['receipt-1'],+ sourceId: 'nightly-review:user-1:agent-1:2026-05-04',+ timezone: 'Asia/Shanghai',+ });+ });++ /**+ * @example+ * Pure noop results do not create Daily Briefs.+ */+ it('does not create briefs for pure noop outcomes', () => {+ const service = createBriefMaintenanceService();++ expect(+ service.projectNightlyReviewBrief({+ agentId: 'agent-1',+ localDate: '2026-05-04',+ result: { actions: [], status: ReviewRunStatus.Completed },+ reviewWindowEnd: '2026-05-04T14:30:00.000Z',+ reviewWindowStart: '2026-05-03T16:00:00.000Z',+ timezone: 'Asia/Shanghai',+ userId: 'user-1',+ }),+ ).toBeUndefined();+ });++ /**+ * @example+ * Proposal actions produce decision briefs.+ */+ it('projects proposal results to decision briefs', () => {+ const service = createBriefMaintenanceService();++ const brief = service.projectNightlyReviewBrief({+ agentId: 'agent-1',+ localDate: '2026-05-04',+ result: {+ actions: [+ {+ idempotencyKey: 'source:proposal_only:skill:merge',+ receiptId: 'receipt-2',+ status: MaintenanceActionStatus.Proposed,+ summary: 'Review skill consolidation proposal.',+ },+ ],+ status: ReviewRunStatus.Completed,+ },+ reviewWindowEnd: '2026-05-04T14:30:00.000Z',+ reviewWindowStart: '2026-05-03T16:00:00.000Z',+ timezone: 'Asia/Shanghai',+ userId: 'user-1',+ });++ expect(brief).toMatchObject({+ trigger: 'agent-signal:nightly-review',+ type: 'decision',+ });+ expect(brief?.priority).toBe('normal');+ });++ /**+ * @example+ * Failed nightly runs produce an error brief when there is a user-actionable failure.+ */+ it('projects failed nightly outcomes to error briefs', () => {+ const service = createBriefMaintenanceService();++ const brief = service.projectNightlyReviewBrief({+ agentId: 'agent-1',+ localDate: '2026-05-04',+ result: {+ actions: [+ {+ idempotencyKey: 'source:write_memory:memory:concise',+ status: MaintenanceActionStatus.Failed,+ summary: 'Memory service unavailable.',+ },+ ],+ status: ReviewRunStatus.Failed,+ },+ reviewWindowEnd: '2026-05-04T14:30:00.000Z',+ reviewWindowStart: '2026-05-03T16:00:00.000Z',+ timezone: 'Asia/Shanghai',+ userId: 'user-1',+ });++ expect(brief).toMatchObject({+ priority: 'normal',+ type: 'error',+ });+ expect(brief?.metadata).toMatchObject({+ outcome: 'error',+ });+ });++ /**+ * @example+ * Pending maintenance proposals stay visible when self-iteration is disabled.+ */+ it('keeps pending maintenance proposals visible after self-iteration is disabled', () => {+ const service = createBriefMaintenanceService();++ expect(+ service.isMaintenanceProposalVisible({+ selfIterationEnabled: false,+ status: 'pending',+ trigger: 'agent-signal:nightly-review',+ }),+ ).toBe(true);+ });++ /**+ * @example+ * Applying a maintenance proposal re-checks server, user, and agent gates.+ */+ it('blocks proposal apply when any current self-iteration gate is disabled', async () => {+ const service = createBriefMaintenanceService();++ await expect(+ service.canApplyMaintenanceProposal({+ checkAgentGate: vi.fn(async () => true),+ checkServerGate: vi.fn(async () => true),+ checkUserGate: vi.fn(async () => false),+ }),+ ).resolves.toEqual({+ allowed: false,+ reason: 'user_gate_disabled',+ });+ });++ /**+ * @example+ * Applying a maintenance proposal is allowed only when all gates pass.+ */+ it('allows proposal apply when all current gates pass', async () => {+ const service = createBriefMaintenanceService();++ await expect(+ service.canApplyMaintenanceProposal({+ checkAgentGate: vi.fn(async () => true),+ checkServerGate: vi.fn(async () => true),+ checkUserGate: vi.fn(async () => true),+ }),+ ).resolves.toEqual({ allowed: true });+ });++ /**+ * @example+ * The server writer persists through BriefModel.create for the source-event user.+ */+ it('creates server brief rows through BriefModel', async () => {+ const create = vi.spyOn(BriefModel.prototype, 'create').mockResolvedValue({+ agentId: 'agent-1',+ createdAt: new Date('2026-05-04T14:30:00.000Z'),+ id: 'brief-1',+ metadata: {},+ priority: 'info',+ summary: '1 maintenance update applied.',+ title: 'Agent self-review updated resources',+ trigger: 'agent-signal:nightly-review',+ type: 'insight',+ userId: 'user-1',+ } as Awaited<ReturnType<BriefModel['create']>>);+ const writer = createServerMaintenanceBriefWriter({} as never, 'user-1');+ const service = createBriefMaintenanceService();+ const brief = service.projectNightlyReviewBrief({+ agentId: 'agent-1',+ localDate: '2026-05-04',+ result: {+ actions: [+ {+ idempotencyKey: 'source:write_memory:memory:concise',+ receiptId: 'receipt-1',+ status: MaintenanceActionStatus.Applied,+ summary: 'Saved concise PR summary preference.',+ },+ ],+ status: ReviewRunStatus.Completed,+ },+ reviewWindowEnd: '2026-05-04T14:30:00.000Z',+ reviewWindowStart: '2026-05-03T16:00:00.000Z',+ timezone: 'Asia/Shanghai',+ userId: 'user-1',+ });++ if (!brief) throw new Error('Expected projected brief');++ await expect(writer.writeDailyBrief(brief)).resolves.toMatchObject({ id: 'brief-1' });+ expect(create).toHaveBeenCalledWith(brief);+ });+});diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/executor.test.ts b/src/server/services/agentSignal/services/maintenance/__tests__/executor.test.tsnew file mode 100644index 00000000000..77ffa4fc322--- /dev/null+++ b/src/server/services/agentSignal/services/maintenance/__tests__/executor.test.ts@@ -0,0 +1,88 @@+import { describe, expect, it, vi } from 'vitest';++import { createMaintenanceExecutorService } from '../executor';+import {+ MaintenanceActionStatus,+ MaintenanceApplyMode,+ MaintenanceReviewScope,+ MaintenanceRisk,+} from '../types';++describe('maintenanceExecutorService', () => {+ /**+ * @example+ * The executor delegates auto-apply memory actions and records applied status.+ */+ it('executes auto-apply memory actions through the memory service', async () => {+ const writeMemory = vi.fn().mockResolvedValue({ memoryId: 'mem-1', summary: 'Saved.' });+ const executor = createMaintenanceExecutorService({+ memory: { writeMemory },+ skill: {},+ });++ const result = await executor.execute({+ actions: [+ {+ actionType: 'write_memory',+ applyMode: MaintenanceApplyMode.AutoApply,+ confidence: 0.95,+ dedupeKey: 'memory:concise',+ evidenceRefs: [{ id: 'msg-1', type: 'message' }],+ idempotencyKey: 'source:write_memory:memory:concise',+ operation: {+ domain: 'memory',+ input: { content: 'User prefers concise PR summaries.', userId: 'user-1' },+ operation: 'write',+ },+ rationale: 'Explicit preference.',+ risk: MaintenanceRisk.Low,+ },+ ],+ plannerVersion: 'test',+ reviewScope: MaintenanceReviewScope.Nightly,+ summary: 'One action.',+ });++ expect(result.actions).toEqual([+ {+ idempotencyKey: 'source:write_memory:memory:concise',+ resourceId: 'mem-1',+ status: MaintenanceActionStatus.Applied,+ summary: 'Saved.',+ },+ ]);+ });++ /**+ * @example+ * Proposal-only actions are recorded without calling domain services.+ */+ it('records proposal-only actions without mutation', async () => {+ const writeMemory = vi.fn();+ const executor = createMaintenanceExecutorService({+ memory: { writeMemory },+ skill: {},+ });++ const result = await executor.execute({+ actions: [+ {+ actionType: 'proposal_only',+ applyMode: MaintenanceApplyMode.ProposalOnly,+ confidence: 0.8,+ dedupeKey: 'proposal:skill-consolidation',+ evidenceRefs: [{ id: 'skill-a', type: 'agent_document' }],+ idempotencyKey: 'source:proposal_only:proposal:skill-consolidation',+ rationale: 'Needs user approval.',+ risk: MaintenanceRisk.High,+ },+ ],+ plannerVersion: 'test',+ reviewScope: MaintenanceReviewScope.Nightly,+ summary: 'One proposal.',+ });++ expect(writeMemory).not.toHaveBeenCalled();+ expect(result.actions[0].status).toBe(MaintenanceActionStatus.Proposed);+ });+});diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/memory.test.ts b/src/server/services/agentSignal/services/maintenance/__tests__/memory.test.tsnew file mode 100644index 00000000000..b3180258064--- /dev/null+++ b/src/server/services/agentSignal/services/maintenance/__tests__/memory.test.ts@@ -0,0 +1,50 @@+import { describe, expect, it, vi } from 'vitest';++import { createMemoryMaintenanceService } from '../memory';++describe('memoryMaintenanceService', () => {+ /**+ * @example+ * Explicit stable preference is passed to the existing memory write adapter.+ */+ it('writes explicit stable memory through the injected adapter', async () => {+ const writeMemory = vi+ .fn()+ .mockResolvedValue({ memoryId: 'mem-1', summary: 'Saved preference.' });+ const service = createMemoryMaintenanceService({ writeMemory });++ await expect(+ service.writeMemory({+ evidenceRefs: [{ id: 'msg-1', type: 'message' }],+ idempotencyKey: 'source:write_memory:memory:concise',+ input: { content: 'User prefers concise PR summaries.', userId: 'user-1' },+ }),+ ).resolves.toEqual({ memoryId: 'mem-1', summary: 'Saved preference.' });++ expect(writeMemory).toHaveBeenCalledWith({+ content: 'User prefers concise PR summaries.',+ evidenceRefs: [{ id: 'msg-1', type: 'message' }],+ idempotencyKey: 'source:write_memory:memory:concise',+ userId: 'user-1',+ });+ });++ /**+ * @example+ * Sensitive inferred facts are rejected before reaching persistence.+ */+ it('rejects sensitive inferred memory candidates', async () => {+ const writeMemory = vi.fn();+ const service = createMemoryMaintenanceService({ writeMemory });++ await expect(+ service.writeMemory({+ evidenceRefs: [{ id: 'msg-1', type: 'message' }],+ idempotencyKey: 'source:write_memory:memory:sensitive',+ input: { content: 'User probably has a medical condition.', userId: 'user-1' },+ }),+ ).rejects.toThrow('Memory candidate is not safe for automatic write');++ expect(writeMemory).not.toHaveBeenCalled();+ });+});diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/nightlyCollector.test.ts b/src/server/services/agentSignal/services/maintenance/__tests__/nightlyCollector.test.tsnew file mode 100644index 00000000000..081b8bde438--- /dev/null+++ b/src/server/services/agentSignal/services/maintenance/__tests__/nightlyCollector.test.ts@@ -0,0 +1,283 @@+import { describe, expect, it, vi } from 'vitest';++import type {+ ListManagedSkillsInput,+ ListRelevantMemoriesInput,+ ListTopicActivityInput,+ NightlyReviewReadAdapters,+} from '../nightlyCollector';+import { createNightlyReviewService } from '../nightlyCollector';++const REVIEW_INPUT = {+ agentId: 'agent-1',+ reviewWindowEnd: '2026-05-04T23:00:00.000Z',+ reviewWindowStart: '2026-05-04T00:00:00.000Z',+ userId: 'user-1',+};++const createDeps = (+ overrides: Partial<NightlyReviewReadAdapters> = {},+): NightlyReviewReadAdapters => ({+ listManagedSkills: vi+ .fn<+ (+ input: ListManagedSkillsInput,+ ) => Promise<Awaited<ReturnType<NightlyReviewReadAdapters['listManagedSkills']>>>+ >()+ .mockResolvedValue([+ {+ description: 'Keeps bug triage concise.',+ documentId: 'skill-1',+ name: 'bug-triage',+ },+ ]),+ listRelevantMemories: vi+ .fn<+ (+ input: ListRelevantMemoriesInput,+ ) => Promise<Awaited<ReturnType<NightlyReviewReadAdapters['listRelevantMemories']>>>+ >()+ .mockResolvedValue([+ {+ content: 'Prefers short nightly summaries.',+ id: 'memory-1',+ },+ ]),+ listTopicActivity: vi+ .fn<+ (+ input: ListTopicActivityInput,+ ) => Promise<Awaited<ReturnType<NightlyReviewReadAdapters['listTopicActivity']>>>+ >()+ .mockResolvedValue([]),+ ...overrides,+});++describe('nightlyReviewService', () => {+ describe('collectNightlyReviewContext', () => {+ it('ranks high-signal topics first and excludes raw messages while including skills and memories', async () => {+ /**+ * @example+ * expect(topics[0].highSignalReasons).toEqual([+ * 'failure',+ * 'negative_feedback',+ * 'correction',+ * 'failed_tool',+ * 'receipt',+ * ]);+ */+ const deps = createDeps({+ listTopicActivity: vi.fn().mockResolvedValue([+ {+ id: 'topic-ordinary',+ messageCount: 100,+ rawMessages: [{ content: 'raw message must not leak' }],+ summary: 'A long successful discussion.',+ },+ {+ correctionCount: 1,+ failedToolCount: 1,+ failureCount: 1,+ id: 'topic-high',+ messageCount: 1,+ negativeFeedbackCount: 1,+ rawMessages: [{ content: 'private raw transcript' }],+ receiptCount: 1,+ summary: 'A failed attempt with feedback.',+ },+ ]),+ });+ const service = createNightlyReviewService(deps);++ const context = await service.collectNightlyReviewContext(REVIEW_INPUT);++ expect(context).toMatchObject({+ agentId: 'agent-1',+ managedSkills: [+ {+ description: 'Keeps bug triage concise.',+ documentId: 'skill-1',+ name: 'bug-triage',+ },+ ],+ relevantMemories: [+ {+ content: 'Prefers short nightly summaries.',+ id: 'memory-1',+ },+ ],+ reviewWindowEnd: '2026-05-04T23:00:00.000Z',+ reviewWindowStart: '2026-05-04T00:00:00.000Z',+ userId: 'user-1',+ });+ expect(context.topics.map((topic) => topic.id)).toEqual(['topic-high', 'topic-ordinary']);+ expect(context.topics[0].highSignalReasons).toEqual([+ 'failure',+ 'negative_feedback',+ 'correction',+ 'failed_tool',+ 'receipt',+ ]);+ expect(context.topics[0]).not.toHaveProperty('rawMessages');+ expect(context.topics[1]).not.toHaveProperty('rawMessages');+ });++ it('clips topic activity to the default max topic budget', async () => {+ /**+ * @example+ * expect(context.topics).toHaveLength(30);+ */+ const deps = createDeps({+ listTopicActivity: vi.fn().mockResolvedValue(+ Array.from({ length: 35 }, (_, index) => ({+ id: `topic-${index}`,+ messageCount: 35 - index,+ })),+ ),+ });+ const service = createNightlyReviewService(deps);++ const context = await service.collectNightlyReviewContext(REVIEW_INPUT);++ expect(context.topics).toHaveLength(30);+ expect(context.topics.at(-1)?.id).toBe('topic-29');+ });++ it('keeps high-signal topics before huge ordinary topics', async () => {+ /**+ * @example+ * expect(context.topics.map((topic) => topic.id)).toEqual(['topic-receipt', 'topic-huge']);+ */+ const deps = createDeps({+ listTopicActivity: vi.fn().mockResolvedValue([+ {+ id: 'topic-huge',+ messageCount: 100_000,+ summary: 'A very long but ordinary successful discussion.',+ },+ {+ id: 'topic-receipt',+ messageCount: 1,+ receiptCount: 1,+ summary: 'A small topic with a receipt.',+ },+ ]),+ });+ const service = createNightlyReviewService(deps);++ const context = await service.collectNightlyReviewContext(REVIEW_INPUT);++ expect(context.topics.map((topic) => topic.id)).toEqual(['topic-receipt', 'topic-huge']);+ expect(context.topics[0].highSignalReasons).toEqual(['receipt']);+ expect(context.topics[1].highSignalReasons).toEqual([]);+ });++ it('preserves evidence refs when provided and synthesizes topic refs when missing', async () => {+ /**+ * @example+ * expect(context.topics[1].evidenceRefs).toEqual([{ id: 'topic-missing', type: 'topic' }]);+ */+ const deps = createDeps({+ listTopicActivity: vi.fn().mockResolvedValue([+ {+ evidenceRefs: [+ { id: 'message-1', summary: 'User corrected the answer.', type: 'message' },+ ],+ id: 'topic-preserved',+ messageCount: 2,+ },+ {+ id: 'topic-missing',+ messageCount: 1,+ },+ ]),+ });+ const service = createNightlyReviewService(deps);++ const context = await service.collectNightlyReviewContext(REVIEW_INPUT);++ expect(context.topics[0].evidenceRefs).toEqual([+ { id: 'message-1', summary: 'User corrected the answer.', type: 'message' },+ ]);+ expect(context.topics[1].evidenceRefs).toEqual([{ id: 'topic-missing', type: 'topic' }]);+ });++ it('uses id tie-breakers when last activity timestamps are invalid', async () => {+ /**+ * @example+ * expect(context.topics.map((topic) => topic.id)).toEqual(['topic-a', 'topic-b']);+ */+ const deps = createDeps({+ listTopicActivity: vi.fn().mockResolvedValue([+ {+ id: 'topic-b',+ lastActivityAt: 'not-a-date',+ messageCount: 1,+ },+ {+ id: 'topic-a',+ lastActivityAt: 'also-not-a-date',+ messageCount: 1,+ },+ ]),+ });+ const service = createNightlyReviewService(deps);++ const context = await service.collectNightlyReviewContext(REVIEW_INPUT);++ expect(context.topics.map((topic) => topic.id)).toEqual(['topic-a', 'topic-b']);+ });++ it('removes raw transcript payload keys from topic attributes while keeping safe attributes', async () => {+ /**+ * @example+ * expect(context.topics[0].attributes).toEqual({ safeLabel: 'billing' });+ */+ const deps = createDeps({+ listTopicActivity: vi.fn().mockResolvedValue([+ {+ attributes: {+ messages: [{ content: 'raw message' }],+ rawMessages: [{ content: 'raw transcript' }],+ safeLabel: 'billing',+ transcript: 'raw transcript text',+ transcripts: ['raw transcript text'],+ },+ id: 'topic-with-attributes',+ messageCount: 1,+ },+ ]),+ });+ const service = createNightlyReviewService(deps);++ const context = await service.collectNightlyReviewContext(REVIEW_INPUT);++ expect(context.topics[0].attributes).toEqual({ safeLabel: 'billing' });+ });++ it('keeps ordinary successful topics low-scored with no high-signal reasons', async () => {+ /**+ * @example+ * expect(context.topics[0].highSignalReasons).toEqual([]);+ */+ const deps = createDeps({+ listTopicActivity: vi.fn().mockResolvedValue([+ {+ id: 'topic-success',+ messageCount: 4,+ summary: 'A successful ordinary exchange.',+ },+ ]),+ });+ const service = createNightlyReviewService(deps);++ const context = await service.collectNightlyReviewContext(REVIEW_INPUT);++ expect(context.topics[0]).toMatchObject({+ highSignalReasons: [],+ id: 'topic-success',+ reviewScore: 4,+ });+ });+ });+});diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/nightlySchedule.test.ts b/src/server/services/agentSignal/services/maintenance/__tests__/nightlySchedule.test.tsnew file mode 100644index 00000000000..124f1126ebc--- /dev/null+++ b/src/server/services/agentSignal/services/maintenance/__tests__/nightlySchedule.test.ts@@ -0,0 +1,210 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type { LobeChatDatabase } from '@/database/type';+import type { AgentSignalSourceEventInput } from '@/server/services/agentSignal/emitter';++import type {+ ListNightlyReviewAgentTargetsInput,+ ListNightlyReviewEligibleUsersInput,+ NightlyReviewAgentTarget,+ NightlyReviewEligibleUser,+} from '../nightlySchedule';+import {+ buildNightlyReviewSourceId,+ createNightlyReviewScheduleService,+ createServerNightlyReviewScheduleService,+} from '../nightlySchedule';++const mocks = vi.hoisted(() => ({+ enqueueAgentSignalSourceEvent: vi.fn(),+ listActiveAgentTargets: vi.fn(),+ listEligibleUsers: vi.fn(),+ modelConstructor: vi.fn(),+}));++vi.mock('@/database/models/agentSignal/nightlyReview', () => ({+ AgentSignalNightlyReviewModel: mocks.modelConstructor.mockImplementation(() => ({+ listActiveAgentTargets: mocks.listActiveAgentTargets,+ listEligibleUsers: mocks.listEligibleUsers,+ })),+}));++vi.mock('@/server/services/agentSignal/emitter', () => ({+ enqueueAgentSignalSourceEvent: mocks.enqueueAgentSignalSourceEvent,+}));++const createDeps = (now: Date) => ({+ enqueueSource: vi+ .fn<+ (input: AgentSignalSourceEventInput<'agent.nightly_review.requested'>) => Promise<unknown>+ >()+ .mockResolvedValue(undefined),+ listActiveAgentTargets: vi+ .fn<(input: ListNightlyReviewAgentTargetsInput) => Promise<NightlyReviewAgentTarget[]>>()+ .mockResolvedValue([{ agentId: 'agent-1' }]),+ listEligibleUsers: vi+ .fn<(input?: ListNightlyReviewEligibleUsersInput) => Promise<NightlyReviewEligibleUser[]>>()+ .mockResolvedValue([+ {+ createdAt: new Date('2026-01-01T00:00:00.000Z'),+ id: 'user-1',+ timezone: 'Asia/Shanghai',+ },+ ]),+ now: () => now,+});++beforeEach(() => {+ vi.clearAllMocks();+});++afterEach(() => {+ vi.useRealTimers();+});++describe('nightlyReviewScheduleService', () => {+ describe('dispatchNightlyReviewRequests', () => {+ it('enqueues Shanghai user nightly review sources with local day window', async () => {+ const deps = createDeps(new Date('2026-05-04T14:30:00.000Z'));+ const service = createNightlyReviewScheduleService(deps);++ const summary = await service.dispatchNightlyReviewRequests();++ expect(summary).toEqual({ enqueued: 1, skipped: 0 });+ expect(deps.listActiveAgentTargets).toHaveBeenCalledWith({+ limit: undefined,+ userId: 'user-1',+ windowEnd: new Date('2026-05-04T14:30:00.000Z'),+ windowStart: new Date('2026-05-03T16:00:00.000Z'),+ });+ expect(deps.enqueueSource).toHaveBeenCalledWith({+ payload: {+ agentId: 'agent-1',+ localDate: '2026-05-04',+ requestedAt: '2026-05-04T14:30:00.000Z',+ reviewWindowEnd: '2026-05-04T14:30:00.000Z',+ reviewWindowStart: '2026-05-03T16:00:00.000Z',+ timezone: 'Asia/Shanghai',+ userId: 'user-1',+ },+ sourceId: 'nightly-review:user-1:agent-1:2026-05-04',+ sourceType: 'agent.nightly_review.requested',+ timestamp: new Date('2026-05-04T14:30:00.000Z').getTime(),+ });+ });++ it('skips users outside the local night window without enqueueing', async () => {+ const deps = createDeps(new Date('2026-05-04T13:30:00.000Z'));+ const service = createNightlyReviewScheduleService(deps);++ const summary = await service.dispatchNightlyReviewRequests();++ expect(summary).toEqual({ enqueued: 0, skipped: 1 });+ expect(deps.listActiveAgentTargets).not.toHaveBeenCalled();+ expect(deps.enqueueSource).not.toHaveBeenCalled();+ });++ it('falls back to UTC for invalid timezone values without throwing', async () => {+ const deps = createDeps(new Date('2026-05-04T22:30:00.000Z'));+ deps.listEligibleUsers.mockResolvedValue([+ {+ createdAt: new Date('2026-01-01T00:00:00.000Z'),+ id: 'user-1',+ timezone: 'Invalid/Zone',+ },+ ]);+ const service = createNightlyReviewScheduleService(deps);++ await expect(service.dispatchNightlyReviewRequests()).resolves.toEqual({+ enqueued: 1,+ skipped: 0,+ });+ expect(deps.enqueueSource).toHaveBeenCalledWith(+ expect.objectContaining<+ Partial<AgentSignalSourceEventInput<'agent.nightly_review.requested'>>+ >({+ payload: expect.objectContaining({+ localDate: '2026-05-04',+ reviewWindowStart: '2026-05-04T00:00:00.000Z',+ timezone: 'UTC',+ }),+ sourceId: 'nightly-review:user-1:agent-1:2026-05-04',+ }),+ );+ });+ });++ describe('buildNightlyReviewSourceId', () => {+ it('produces a stable nightly review source id', () => {+ expect(+ buildNightlyReviewSourceId({+ agentId: 'agent-1',+ localDate: '2026-05-04',+ userId: 'user-1',+ }),+ ).toBe('nightly-review:user-1:agent-1:2026-05-04');+ });+ });++ describe('createServerNightlyReviewScheduleService', () => {+ it('calls the model methods and enqueues source payloads through the server adapter', async () => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date('2026-05-04T14:30:00.000Z'));+ mocks.listEligibleUsers.mockResolvedValue([+ {+ createdAt: new Date('2026-01-01T00:00:00.000Z'),+ id: 'user-1',+ timezone: 'Asia/Shanghai',+ },+ ]);+ mocks.listActiveAgentTargets.mockResolvedValue([{ agentId: 'agent-1' }]);+ mocks.enqueueAgentSignalSourceEvent.mockResolvedValue({+ accepted: true,+ scopeKey: 'user-1:agent-1',+ workflowRunId: 'workflow-1',+ });+ const db = {} as unknown as LobeChatDatabase;+ const service = createServerNightlyReviewScheduleService(db);++ const summary = await service.dispatchNightlyReviewRequests({+ cursor: { createdAt: new Date('2026-01-01T00:00:00.000Z'), id: 'cursor-user' },+ limit: 10,+ targetLimit: 3,+ whitelist: ['user-1'],+ });++ expect(summary).toEqual({ enqueued: 1, skipped: 0 });+ expect(mocks.modelConstructor).toHaveBeenCalledWith(db);+ expect(mocks.listEligibleUsers).toHaveBeenCalledWith({+ cursor: { createdAt: new Date('2026-01-01T00:00:00.000Z'), id: 'cursor-user' },+ limit: 10,+ whitelist: ['user-1'],+ });+ expect(mocks.listActiveAgentTargets).toHaveBeenCalledWith('user-1', {+ limit: 3,+ windowEnd: new Date('2026-05-04T14:30:00.000Z'),+ windowStart: new Date('2026-05-03T16:00:00.000Z'),+ });+ expect(mocks.enqueueAgentSignalSourceEvent).toHaveBeenCalledWith(+ {+ payload: {+ agentId: 'agent-1',+ localDate: '2026-05-04',+ requestedAt: '2026-05-04T14:30:00.000Z',+ reviewWindowEnd: '2026-05-04T14:30:00.000Z',+ reviewWindowStart: '2026-05-03T16:00:00.000Z',+ timezone: 'Asia/Shanghai',+ userId: 'user-1',+ },+ sourceId: 'nightly-review:user-1:agent-1:2026-05-04',+ sourceType: 'agent.nightly_review.requested',+ timestamp: new Date('2026-05-04T14:30:00.000Z').getTime(),+ },+ {+ agentId: 'agent-1',+ userId: 'user-1',+ },+ );+ });+ });+});diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/planner.test.ts b/src/server/services/agentSignal/services/maintenance/__tests__/planner.test.tsnew file mode 100644index 00000000000..53c496b311e--- /dev/null+++ b/src/server/services/agentSignal/services/maintenance/__tests__/planner.test.ts@@ -0,0 +1,400 @@+import { describe, expect, it } from 'vitest';++import { createMaintenancePlannerService } from '../planner';+import { MaintenanceApplyMode, MaintenanceReviewScope, MaintenanceRisk } from '../types';++describe('maintenancePlannerService', () => {+ /**+ * @example+ * A high-confidence explicit preference with evidence becomes an auto-apply memory action.+ */+ it('normalizes an evidence-backed memory draft into an executable action', () => {+ const planner = createMaintenancePlannerService();++ const plan = planner.plan({+ draft: {+ actions: [+ {+ actionType: 'write_memory',+ confidence: 0.94,+ evidenceRefs: [+ {+ id: 'msg-1',+ summary: 'User explicitly asked for concise PR summaries',+ type: 'message',+ },+ ],+ policyHints: {+ evidenceStrength: 'strong',+ persistence: 'stable',+ sensitivity: 'normal',+ userExplicitness: 'explicit',+ },+ rationale: 'The user stated a stable preference that should affect future responses.',+ target: { topicIds: ['topic-1'] },+ value: { content: 'User prefers concise PR summaries.' },+ },+ ],+ findings: [+ {+ evidenceRefs: [{ id: 'msg-1', type: 'message' }],+ severity: 'medium',+ summary: 'Stable preference found',+ },+ ],+ summary: 'One stable preference should be remembered.',+ },+ reviewScope: MaintenanceReviewScope.Nightly,+ sourceId: 'nightly-review:user-1:agent-1:2026-05-04',+ userId: 'user-1',+ });++ expect(plan.actions).toHaveLength(1);+ expect(plan.actions[0]).toMatchObject({+ actionType: 'write_memory',+ applyMode: MaintenanceApplyMode.AutoApply,+ dedupeKey: 'memory:User prefers concise PR summaries.',+ idempotencyKey:+ 'nightly-review:user-1:agent-1:2026-05-04:write_memory:memory:User prefers concise PR summaries.',+ operation: {+ input: { content: 'User prefers concise PR summaries.', userId: 'user-1' },+ },+ risk: MaintenanceRisk.Low,+ });+ });++ /**+ * @example+ * A high-confidence inferred memory with evidence still cannot bypass memory mutation policy.+ */+ it('keeps inferred high-confidence memory drafts as proposals', () => {+ const planner = createMaintenancePlannerService();++ const plan = planner.plan({+ draft: {+ actions: [+ {+ actionType: 'write_memory',+ confidence: 0.94,+ evidenceRefs: [{ id: 'msg-1', summary: 'User might prefer Python.', type: 'message' }],+ policyHints: {+ evidenceStrength: 'medium',+ persistence: 'stable',+ sensitivity: 'normal',+ userExplicitness: 'inferred',+ },+ rationale: 'The user seemed to prefer Python for future tasks.',+ value: { content: 'User prefers Python.' },+ },+ ],+ findings: [],+ summary: 'Inferred preference candidate.',+ },+ reviewScope: MaintenanceReviewScope.Nightly,+ sourceId: 'nightly-review:user-1:agent-1:2026-05-04',+ userId: 'user-1',+ });++ expect(plan.actions[0]).toMatchObject({+ actionType: 'write_memory',+ applyMode: MaintenanceApplyMode.ProposalOnly,+ risk: MaintenanceRisk.Medium,+ });+ });++ /**+ * @example+ * Sensitive memory candidates stay out of automatic writes even with high reviewer confidence.+ */+ it('keeps sensitive high-confidence memory drafts as proposals', () => {+ const planner = createMaintenancePlannerService();++ const plan = planner.plan({+ draft: {+ actions: [+ {+ actionType: 'write_memory',+ confidence: 0.96,+ evidenceRefs: [+ { id: 'msg-1', summary: 'User mentioned health context.', type: 'message' },+ ],+ policyHints: {+ evidenceStrength: 'strong',+ persistence: 'stable',+ sensitivity: 'sensitive',+ userExplicitness: 'explicit',+ },+ rationale: 'The user explicitly mentioned a health detail.',+ value: { content: 'User has a health-related constraint.' },+ },+ ],+ findings: [],+ summary: 'Sensitive memory candidate.',+ },+ reviewScope: MaintenanceReviewScope.Nightly,+ sourceId: 'nightly-review:user-1:agent-1:2026-05-04',+ userId: 'user-1',+ });++ expect(plan.actions[0]).toMatchObject({+ actionType: 'write_memory',+ applyMode: MaintenanceApplyMode.ProposalOnly,+ risk: MaintenanceRisk.High,+ });+ });++ /**+ * @example+ * Skill creation requires explicit strong evidence instead of confidence alone.+ */+ it('keeps implicit skill creation drafts as proposals', () => {+ const planner = createMaintenancePlannerService();++ const plan = planner.plan({+ draft: {+ actions: [+ {+ actionType: 'create_skill',+ confidence: 0.93,+ evidenceRefs: [{ id: 'receipt-1', type: 'receipt' }],+ policyHints: {+ evidenceStrength: 'medium',+ mutationScope: 'small',+ userExplicitness: 'implicit',+ },+ rationale: 'A reusable workflow might be useful.',+ value: { bodyMarkdown: 'Use this workflow next time.', title: 'Workflow helper' },+ },+ ],+ findings: [],+ summary: 'Possible skill candidate.',+ },+ reviewScope: MaintenanceReviewScope.Nightly,+ sourceId: 'nightly-review:user-1:agent-1:2026-05-04',+ userId: 'user-1',+ });++ expect(plan.actions[0]).toMatchObject({+ actionType: 'create_skill',+ applyMode: MaintenanceApplyMode.ProposalOnly,+ risk: MaintenanceRisk.Medium,+ });+ });++ /**+ * @example+ * Agent-declared self-iteration intent remains eligible for automatic skill creation.+ */+ it('allows explicit self-iteration skill creation with strong evidence', () => {+ const planner = createMaintenancePlannerService();++ const plan = planner.plan({+ draft: {+ actions: [+ {+ actionType: 'create_skill',+ confidence: 0.94,+ evidenceRefs: [+ { id: 'source-1', type: 'source' },+ { id: 'receipt-1', type: 'receipt' },+ ],+ policyHints: {+ evidenceStrength: 'strong',+ mutationScope: 'small',+ userExplicitness: 'explicit',+ },+ rationale: 'The running agent explicitly requested a reusable skill.',+ value: { bodyMarkdown: 'Use this workflow next time.', title: 'Workflow helper' },+ },+ ],+ findings: [],+ summary: 'Explicit skill candidate.',+ },+ reviewScope: MaintenanceReviewScope.SelfIterationIntent,+ sourceId: 'self-iteration-intent:user-1:agent-1:topic:topic-1:tool-1',+ userId: 'user-1',+ });++ expect(plan.actions[0]).toMatchObject({+ actionType: 'create_skill',+ applyMode: MaintenanceApplyMode.AutoApply,+ operation: {+ input: { bodyMarkdown: 'Use this workflow next time.', title: 'Workflow helper' },+ },+ risk: MaintenanceRisk.Low,+ });+ });++ /**+ * @example+ * Repeated tool failures can justify a small targeted managed-skill refinement.+ */+ it('allows repeated-failure skill refinement with strong evidence', () => {+ const planner = createMaintenancePlannerService();++ const plan = planner.plan({+ draft: {+ actions: [+ {+ actionType: 'refine_skill',+ confidence: 0.91,+ evidenceRefs: [+ { id: 'tool-fail-1', type: 'tool_call' },+ { id: 'tool-fail-2', type: 'tool_call' },+ ],+ policyHints: {+ evidenceStrength: 'strong',+ mutationScope: 'small',+ userExplicitness: 'implicit',+ },+ rationale: 'Repeated release-note validation failures reveal a small missing step.',+ target: { skillDocumentId: 'skill-release-notes' },+ value: {+ patch: 'Add a checklist step to validate changelog sections before publishing.',+ skillDocumentId: 'skill-release-notes',+ },+ },+ ],+ findings: [],+ summary: 'Repeated skill gap.',+ },+ reviewScope: MaintenanceReviewScope.SelfReflection,+ sourceId: 'self-reflection:user-1:agent-1:task:task-1:failed_tool_count:2026-05-04',+ userId: 'user-1',+ });++ expect(plan.actions[0]).toMatchObject({+ actionType: 'refine_skill',+ applyMode: MaintenanceApplyMode.AutoApply,+ operation: {+ input: {+ patch: 'Add a checklist step to validate changelog sections before publishing.',+ skillDocumentId: 'skill-release-notes',+ },+ },+ risk: MaintenanceRisk.Low,+ });+ });++ /**+ * @example+ * Weak single-signal memory drafts are downgraded and cannot auto-write.+ */+ it('downgrades weak or evidence-free drafts to proposal or noop', () => {+ const planner = createMaintenancePlannerService();++ const plan = planner.plan({+ draft: {+ actions: [+ {+ actionType: 'write_memory',+ confidence: 0.51,+ evidenceRefs: [],+ rationale: 'Maybe the user likes dark UI.',+ value: { content: 'User likes dark UI.' },+ },+ ],+ findings: [],+ summary: 'Weak memory candidate.',+ },+ reviewScope: MaintenanceReviewScope.Nightly,+ sourceId: 'nightly-review:user-1:agent-1:2026-05-04',+ userId: 'user-1',+ });++ expect(plan.actions[0]).toMatchObject({+ actionType: 'write_memory',+ applyMode: MaintenanceApplyMode.Skip,+ risk: MaintenanceRisk.High,+ });+ });++ /**+ * @example+ * Self-reflection never auto-consolidates skills.+ */+ it('forces self-reflection consolidation drafts into proposal-only', () => {+ const planner = createMaintenancePlannerService();++ const plan = planner.plan({+ draft: {+ actions: [+ {+ actionType: 'consolidate_skill',+ confidence: 0.99,+ evidenceRefs: [+ { id: 'skill-a', type: 'agent_document' },+ { id: 'skill-b', type: 'agent_document' },+ ],+ rationale: 'Two skills overlap.',+ target: { skillDocumentId: 'skill-a' },+ value: { sourceSkillIds: ['skill-a', 'skill-b'] },+ },+ ],+ findings: [],+ summary: 'Overlap found.',+ },+ reviewScope: MaintenanceReviewScope.SelfReflection,+ sourceId:+ 'self-reflection:user-1:agent-1:task:task-1:failed_tool_count:2026-05-04T14:00:00.000Z:2026-05-04T14:30:00.000Z',+ userId: 'user-1',+ });++ expect(plan.actions[0]).toMatchObject({+ actionType: 'consolidate_skill',+ applyMode: MaintenanceApplyMode.ProposalOnly,+ risk: MaintenanceRisk.High,+ });+ });++ /**+ * @example+ * Planner caps auto-apply actions so one review cannot mutate too much.+ */+ it('caps automatic actions and skips overflow actions', () => {+ const planner = createMaintenancePlannerService({ maxAutoApplyActions: 1 });++ const plan = planner.plan({+ draft: {+ actions: [+ {+ actionType: 'write_memory',+ confidence: 0.95,+ evidenceRefs: [{ id: 'msg-1', type: 'message' }],+ policyHints: {+ evidenceStrength: 'strong',+ persistence: 'stable',+ sensitivity: 'normal',+ userExplicitness: 'explicit',+ },+ rationale: 'Preference A.',+ value: { content: 'User prefers A.' },+ },+ {+ actionType: 'write_memory',+ confidence: 0.95,+ evidenceRefs: [{ id: 'msg-2', type: 'message' }],+ policyHints: {+ evidenceStrength: 'strong',+ persistence: 'stable',+ sensitivity: 'normal',+ userExplicitness: 'explicit',+ },+ rationale: 'Preference B.',+ value: { content: 'User prefers B.' },+ },+ ],+ findings: [],+ summary: 'Two candidates.',+ },+ reviewScope: MaintenanceReviewScope.Nightly,+ sourceId: 'nightly-review:user-1:agent-1:2026-05-04',+ userId: 'user-1',+ });++ expect(plan.actions.map((action) => action.applyMode)).toEqual([+ MaintenanceApplyMode.AutoApply,+ MaintenanceApplyMode.ProposalOnly,+ ]);+ });+});diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/skill.test.ts b/src/server/services/agentSignal/services/maintenance/__tests__/skill.test.tsnew file mode 100644index 00000000000..e495a23b669--- /dev/null+++ b/src/server/services/agentSignal/services/maintenance/__tests__/skill.test.ts@@ -0,0 +1,54 @@+import { describe, expect, it, vi } from 'vitest';++import { createSkillManagementService } from '../skill';++describe('skillManagementService', () => {+ /**+ * @example+ * Writable managed skill documents may be refined automatically.+ */+ it('refines writable managed skills through the injected adapter', async () => {+ const refineSkill = vi+ .fn()+ .mockResolvedValue({ skillDocumentId: 'doc-1', summary: 'Refined skill.' });+ const service = createSkillManagementService({ refineSkill });++ await expect(+ service.refineSkill({+ evidenceRefs: [{ id: 'msg-1', type: 'message' }],+ idempotencyKey: 'source:refine_skill:skill:doc-1',+ input: {+ patch: 'Add checklist step for failed release note validation.',+ skillDocumentId: 'doc-1',+ userId: 'user-1',+ },+ }),+ ).resolves.toEqual({ skillDocumentId: 'doc-1', summary: 'Refined skill.' });++ expect(refineSkill).toHaveBeenCalledOnce();+ });++ /**+ * @example+ * Readonly builtin or marketplace skills are not mutated by this service.+ */+ it('rejects readonly skill targets before persistence', async () => {+ const refineSkill = vi.fn();+ const service = createSkillManagementService({ refineSkill });++ await expect(+ service.refineSkill({+ evidenceRefs: [{ id: 'builtin-skill', type: 'agent_document' }],+ idempotencyKey: 'source:refine_skill:skill:builtin',+ input: {+ patch: 'Change builtin skill.',+ skillDocumentId: 'builtin-skill',+ targetReadonly: true,+ userId: 'user-1',+ },+ }),+ ).rejects.toThrow('Skill target is readonly');++ expect(refineSkill).not.toHaveBeenCalled();+ });+});diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/types.test.ts b/src/server/services/agentSignal/services/maintenance/__tests__/types.test.tsnew file mode 100644index 00000000000..a211422f92e--- /dev/null+++ b/src/server/services/agentSignal/services/maintenance/__tests__/types.test.ts@@ -0,0 +1,103 @@+import { describe, expect, it } from 'vitest';++import {+ buildMaintenanceActionIdempotencyKey,+ buildNightlyReviewSourceId,+ buildSelfIterationIntentSourceId,+ buildSelfReflectionSourceId,+ isActionExecutable,+ MaintenanceActionStatus,+ MaintenanceApplyMode,+ MaintenanceReviewScope,+ ReviewRunStatus,+} from '../types';++describe('maintenance contracts', () => {+ /**+ * @example+ * buildNightlyReviewSourceId({ userId: 'u', agentId: 'a', localDate: '2026-05-04' })+ * returns 'nightly-review:u:a:2026-05-04'.+ */+ it('builds stable nightly review source ids', () => {+ expect(+ buildNightlyReviewSourceId({+ agentId: 'agent-1',+ localDate: '2026-05-04',+ userId: 'user-1',+ }),+ ).toBe('nightly-review:user-1:agent-1:2026-05-04');+ });++ /**+ * @example+ * buildSelfReflectionSourceId({ scopeType: 'task', scopeId: 'task-1' }) includes the scope.+ */+ it('builds stable self-reflection source ids', () => {+ expect(+ buildSelfReflectionSourceId({+ agentId: 'agent-1',+ reason: 'failed_tool_count',+ scopeId: 'task-1',+ scopeType: 'task',+ userId: 'user-1',+ windowEnd: '2026-05-04T14:30:00.000Z',+ windowStart: '2026-05-04T14:00:00.000Z',+ }),+ ).toBe(+ 'self-reflection:user-1:agent-1:task:task-1:failed_tool_count:2026-05-04T14:00:00.000Z:2026-05-04T14:30:00.000Z',+ );+ });++ /**+ * @example+ * buildSelfIterationIntentSourceId({ toolCallId: 'call-1' }) includes the tool call id.+ */+ it('builds stable self-iteration intent source ids', () => {+ expect(+ buildSelfIterationIntentSourceId({+ agentId: 'agent-1',+ scopeId: 'topic-1',+ scopeType: 'topic',+ toolCallId: 'tool-call-1',+ userId: 'user-1',+ }),+ ).toBe('self-iteration-intent:user-1:agent-1:topic:topic-1:tool-call-1');+ });++ /**+ * @example+ * buildMaintenanceActionIdempotencyKey({ sourceId, actionType, dedupeKey })+ * returns a stable action-specific idempotency key.+ */+ it('builds action idempotency keys from source and action identity', () => {+ expect(+ buildMaintenanceActionIdempotencyKey({+ actionType: 'refine_skill',+ dedupeKey: 'skill:agent-doc-1',+ sourceId: 'source-1',+ }),+ ).toBe('source-1:refine_skill:skill:agent-doc-1');+ });++ /**+ * @example+ * isActionExecutable({ applyMode: 'auto_apply' }) returns true.+ */+ it('identifies executable action modes', () => {+ expect(isActionExecutable(MaintenanceApplyMode.AutoApply)).toBe(true);+ expect(isActionExecutable(MaintenanceApplyMode.ProposalOnly)).toBe(false);+ expect(isActionExecutable(MaintenanceApplyMode.Skip)).toBe(false);+ });++ /**+ * @example+ * Status constants remain stable for persisted receipts and observability.+ */+ it('keeps persisted status and scope string values stable', () => {+ expect(MaintenanceReviewScope.Nightly).toBe('nightly');+ expect(MaintenanceReviewScope.SelfReflection).toBe('self_reflection');+ expect(MaintenanceReviewScope.SelfIterationIntent).toBe('self_iteration_intent');+ expect(ReviewRunStatus.PartiallyApplied).toBe('partially_applied');+ expect(MaintenanceActionStatus.Proposed).toBe('proposed');+ });+});diff --git a/src/server/services/agentSignal/services/maintenance/brief.ts b/src/server/services/agentSignal/services/maintenance/brief.tsnew file mode 100644index 00000000000..480fcb8bf44--- /dev/null+++ b/src/server/services/agentSignal/services/maintenance/brief.ts@@ -0,0 +1,287 @@+import { BriefModel } from '@/database/models/brief';+import type { NewBrief } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';++import type { EvidenceRef, MaintenanceReviewRunResult } from './types';+import { MaintenanceActionStatus, ReviewRunStatus } from './types';++const NIGHTLY_REVIEW_BRIEF_TRIGGER = 'agent-signal:nightly-review';++interface MaintenanceBriefActionCounts {+ /** Number of actions applied to durable resources. */+ applied: number;+ /** Number of actions that failed after planning or execution. */+ failed: number;+ /** Number of actions left as user-visible proposals. */+ proposed: number;+ /** Number of actions skipped by planner or executor policy. */+ skipped: number;+}++/** Metadata stored with Agent Signal maintenance Daily Briefs. */+export interface MaintenanceBriefMetadata {+ /** Per-action status counts used by UI filters and eval assertions. */+ actionCounts: MaintenanceBriefActionCounts;+ /** Evidence refs retained from reviewer/planner context for audit drilldown. */+ evidenceRefs: EvidenceRef[];+ /** User-local review date in YYYY-MM-DD form. */+ localDate: string;+ /** Coarse user-visible outcome selected by the projection service. */+ outcome: 'applied' | 'error' | 'proposal';+ /** Durable receipt ids linked to this brief. */+ receiptIds: string[];+ /** Review source id that produced this brief. */+ sourceId?: string;+ /** IANA timezone used for the nightly review window. */+ timezone: string;+ /** Review window end ISO timestamp. */+ windowEnd: string;+ /** Review window start ISO timestamp. */+ windowStart: string;+}++/** Create payload for a maintenance Daily Brief. */+export type MaintenanceBriefProjection = Omit<NewBrief, 'id' | 'userId'> & {+ metadata: MaintenanceBriefMetadata;+ trigger: typeof NIGHTLY_REVIEW_BRIEF_TRIGGER;+};++/** Input used to project one nightly maintenance result to a Daily Brief payload. */+export interface ProjectNightlyReviewBriefInput {+ /** Agent reviewed by the nightly maintenance run. */+ agentId: string;+ /** Evidence refs retained from the review or source handler. */+ evidenceRefs?: EvidenceRef[];+ /** User-local date reviewed by the nightly run. */+ localDate: string;+ /** Executor result for the nightly maintenance run. */+ result: MaintenanceReviewRunResult;+ /** Review window end ISO timestamp. */+ reviewWindowEnd: string;+ /** Review window start ISO timestamp. */+ reviewWindowStart: string;+ /** IANA timezone used for nightly scheduling. */+ timezone: string;+ /** User that owns the agent and brief. */+ userId: string;+}++/** Gate checks required before applying a pending maintenance proposal. */+export interface CanApplyMaintenanceProposalInput {+ /** Checks whether the target agent still allows self-iteration mutations. */+ checkAgentGate: () => boolean | Promise<boolean>;+ /** Checks whether server-side feature gates still allow proposal application. */+ checkServerGate: () => boolean | Promise<boolean>;+ /** Checks whether the current user still enables self-iteration. */+ checkUserGate: () => boolean | Promise<boolean>;+}++/** Result of proposal apply gate re-checks. */+export interface MaintenanceProposalApplyGateResult {+ /** Whether the caller may apply the proposal mutation. */+ allowed: boolean;+ /** Machine-readable blocked reason when `allowed` is false. */+ reason?: 'agent_gate_disabled' | 'server_gate_disabled' | 'user_gate_disabled';+}++/** Input used to decide whether an existing maintenance proposal stays visible. */+export interface MaintenanceProposalVisibilityInput {+ /** Current self-iteration setting. Does not hide already-created proposals. */+ selfIterationEnabled: boolean;+ /** Proposal resolution state. */+ status: 'dismissed' | 'pending' | 'resolved';+ /** Brief trigger namespace. */+ trigger?: string | null;+}++const countActions = (result: MaintenanceReviewRunResult): MaintenanceBriefActionCounts => {+ const counts: MaintenanceBriefActionCounts = {+ applied: 0,+ failed: 0,+ proposed: 0,+ skipped: 0,+ };++ for (const action of result.actions) {+ if (action.status === MaintenanceActionStatus.Applied) counts.applied += 1;+ if (action.status === MaintenanceActionStatus.Failed) counts.failed += 1;+ if (action.status === MaintenanceActionStatus.Proposed && action.receiptId) {+ counts.proposed += 1;+ }+ if (+ action.status === MaintenanceActionStatus.Skipped ||+ action.status === MaintenanceActionStatus.Deduped+ ) {+ counts.skipped += 1;+ }+ }++ return counts;+};++const getReceiptIds = (result: MaintenanceReviewRunResult) => [+ ...(result.summaryReceiptId ? [result.summaryReceiptId] : []),+ ...result.actions.flatMap((action) => (action.receiptId ? [action.receiptId] : [])),+];++const getOutcome = (+ result: MaintenanceReviewRunResult,+ counts: MaintenanceBriefActionCounts,+): MaintenanceBriefMetadata['outcome'] | undefined => {+ if (counts.proposed > 0) return 'proposal';+ if (counts.applied > 0) return 'applied';+ if (counts.failed > 0 || result.status === ReviewRunStatus.Failed) return 'error';++ return;+};++const createBriefCopy = (+ outcome: MaintenanceBriefMetadata['outcome'],+ counts: MaintenanceBriefActionCounts,+) => {+ if (outcome === 'proposal') {+ return {+ priority: 'normal' as const,+ summary: `${counts.proposed} maintenance proposal${counts.proposed === 1 ? '' : 's'} need review.`,+ title: 'Agent self-review proposal',+ type: 'decision' as const,+ };+ }++ if (outcome === 'error') {+ return {+ priority: 'normal' as const,+ summary: 'Agent self-review could not finish all maintenance actions.',+ title: 'Agent self-review needs attention',+ type: 'error' as const,+ };+ }++ return {+ priority: 'info' as const,+ summary: `${counts.applied} maintenance update${counts.applied === 1 ? '' : 's'} applied.`,+ title: 'Agent self-review updated resources',+ type: 'insight' as const,+ };+};++/**+ * Creates projection helpers for Agent Signal maintenance Daily Briefs.+ *+ * Use when:+ * - Nightly review handlers need to create user-visible brief payloads+ * - Proposal apply paths need to re-check current gates before mutation+ *+ * Expects:+ * - Maintenance execution has already finished and receipts have been attempted first+ * - Callers persist the returned brief payload through `BriefModel.create`+ *+ * Returns:+ * - Pure projection helpers with no database writes+ */+export const createBriefMaintenanceService = () => ({+ /**+ * Checks whether a pending maintenance proposal can be applied right now.+ *+ * Use when:+ * - A user approves a previously-created maintenance proposal+ * - Current feature/user/agent gates must be honored at apply time+ *+ * Expects:+ * - Gate checks are side-effect free and return current server truth+ *+ * Returns:+ * - `allowed: true` only when every gate passes+ */+ canApplyMaintenanceProposal: async (+ input: CanApplyMaintenanceProposalInput,+ ): Promise<MaintenanceProposalApplyGateResult> => {+ if (!(await input.checkServerGate())) return { allowed: false, reason: 'server_gate_disabled' };+ if (!(await input.checkUserGate())) return { allowed: false, reason: 'user_gate_disabled' };+ if (!(await input.checkAgentGate())) return { allowed: false, reason: 'agent_gate_disabled' };++ return { allowed: true };+ },++ /**+ * Keeps already-created proposal briefs visible independently from current gates.+ *+ * Use when:+ * - Daily Brief lists decide whether to show pending Agent Signal proposals+ * - Self-iteration has been disabled after proposal creation+ *+ * Expects:+ * - The caller separately blocks proposal application with `canApplyMaintenanceProposal`+ *+ * Returns:+ * - `true` for pending Agent Signal nightly proposals+ */+ isMaintenanceProposalVisible: (input: MaintenanceProposalVisibilityInput) =>+ input.trigger === NIGHTLY_REVIEW_BRIEF_TRIGGER && input.status === 'pending',++ /**+ * Projects one nightly review execution result into a Daily Brief create payload.+ *+ * Use when:+ * - Nightly review handlers have already executed maintenance actions+ * - Noop reviews should remain silent while applied/proposal/error outcomes surface+ *+ * Expects:+ * - `result.actions` contains executor-order action results+ * - `reviewWindowStart` and `reviewWindowEnd` are ISO strings from the scheduler+ *+ * Returns:+ * - A Daily Brief create payload, or `undefined` for pure noop outcomes+ */+ projectNightlyReviewBrief: (+ input: ProjectNightlyReviewBriefInput,+ ): MaintenanceBriefProjection | undefined => {+ const actionCounts = countActions(input.result);+ const outcome = getOutcome(input.result, actionCounts);++ if (!outcome) return;++ const copy = createBriefCopy(outcome, actionCounts);++ return {+ agentId: input.agentId,+ metadata: {+ actionCounts,+ evidenceRefs: input.evidenceRefs ?? [],+ localDate: input.localDate,+ outcome,+ receiptIds: getReceiptIds(input.result),+ ...(input.result.sourceId ? { sourceId: input.result.sourceId } : {}),+ timezone: input.timezone,+ windowEnd: input.reviewWindowEnd,+ windowStart: input.reviewWindowStart,+ },+ priority: copy.priority,+ summary: copy.summary,+ title: copy.title,+ trigger: NIGHTLY_REVIEW_BRIEF_TRIGGER,+ type: copy.type,+ };+ },+});++/**+ * Creates the server Daily Brief writer backed by {@link BriefModel}.+ *+ * Use when:+ * - Agent Signal nightly review policy options are installed in the server runtime+ * - Eligible nightly outcomes must become real Daily Brief rows+ *+ * Expects:+ * - `db` and `userId` belong to the source-event owner+ *+ * Returns:+ * - A writer whose `writeDailyBrief` method calls `BriefModel.create`+ */+export const createServerMaintenanceBriefWriter = (db: LobeChatDatabase, userId: string) => {+ const model = new BriefModel(db, userId);++ return {+ writeDailyBrief: (brief: MaintenanceBriefProjection) => model.create(brief),+ };+};diff --git a/src/server/services/agentSignal/services/maintenance/executor.ts b/src/server/services/agentSignal/services/maintenance/executor.tsnew file mode 100644index 00000000000..fb69cc42dbe--- /dev/null+++ b/src/server/services/agentSignal/services/maintenance/executor.ts@@ -0,0 +1,201 @@+import type { MemoryMaintenanceWriteRequest, MemoryMaintenanceWriteResult } from './memory';+import type {+ SkillMaintenanceConsolidateRequest,+ SkillMaintenanceCreateRequest,+ SkillMaintenanceRefineRequest,+ SkillMaintenanceResult,+} from './skill';+import type {+ MaintenanceActionPlan,+ MaintenanceDomainOperation,+ MaintenancePlan,+ MaintenanceReviewRunResult,+} from './types';+import {+ isActionExecutable,+ MaintenanceActionStatus,+ MaintenanceApplyMode,+ ReviewRunStatus,+} from './types';++/** Operation handlers used by the maintenance executor for approved mutations. */+export interface MaintenanceOperationHandlers {+ /** Handles auto-apply memory operations. */+ memory: {+ /** Writes a memory maintenance request. */+ writeMemory: (request: MemoryMaintenanceWriteRequest) => Promise<MemoryMaintenanceWriteResult>;+ };+ /** Handles auto-apply skill operations. */+ skill: Partial<{+ /** Creates a managed skill. */+ createSkill: (request: SkillMaintenanceCreateRequest) => Promise<SkillMaintenanceResult>;+ /** Refines a managed skill. */+ refineSkill: (request: SkillMaintenanceRefineRequest) => Promise<SkillMaintenanceResult>;+ /** Consolidates managed skills. */+ consolidateSkill: (+ request: SkillMaintenanceConsolidateRequest,+ ) => Promise<SkillMaintenanceResult>;+ }>;+}++const toSkippedResult = (action: MaintenanceActionPlan) => ({+ idempotencyKey: action.idempotencyKey,+ status: MaintenanceActionStatus.Skipped,+ summary: 'Maintenance action was skipped by planner policy.',+});++const toProposedResult = (action: MaintenanceActionPlan) => ({+ idempotencyKey: action.idempotencyKey,+ status: MaintenanceActionStatus.Proposed,+ summary: action.rationale,+});++const toFailedResult = (action: MaintenanceActionPlan, error: unknown) => ({+ idempotencyKey: action.idempotencyKey,+ status: MaintenanceActionStatus.Failed,+ summary: error instanceof Error ? error.message : String(error),+});++const executeMemoryAction = async (+ handlers: MaintenanceOperationHandlers,+ action: MaintenanceActionPlan,+ operation: Extract<MaintenanceDomainOperation, { domain: 'memory' }>,+) => {+ const result = await handlers.memory.writeMemory({+ evidenceRefs: action.evidenceRefs,+ idempotencyKey: action.idempotencyKey,+ input: operation.input,+ });++ return {+ idempotencyKey: action.idempotencyKey,+ resourceId: result.memoryId,+ status: MaintenanceActionStatus.Applied,+ summary: result.summary,+ };+};++const executeSkillAction = async (+ handlers: MaintenanceOperationHandlers,+ action: MaintenanceActionPlan,+ operation: Extract<MaintenanceDomainOperation, { domain: 'skill' }>,+) => {+ if (operation.operation === 'create' && handlers.skill.createSkill) {+ const result = await handlers.skill.createSkill({+ evidenceRefs: action.evidenceRefs,+ idempotencyKey: action.idempotencyKey,+ input: operation.input,+ });++ return {+ idempotencyKey: action.idempotencyKey,+ resourceId: result.skillDocumentId,+ status: MaintenanceActionStatus.Applied,+ summary: result.summary,+ };+ }++ if (operation.operation === 'refine' && handlers.skill.refineSkill) {+ const result = await handlers.skill.refineSkill({+ evidenceRefs: action.evidenceRefs,+ idempotencyKey: action.idempotencyKey,+ input: operation.input,+ });++ return {+ idempotencyKey: action.idempotencyKey,+ resourceId: result.skillDocumentId,+ status: MaintenanceActionStatus.Applied,+ summary: result.summary,+ };+ }++ if (operation.operation === 'consolidate' && handlers.skill.consolidateSkill) {+ const result = await handlers.skill.consolidateSkill({+ evidenceRefs: action.evidenceRefs,+ idempotencyKey: action.idempotencyKey,+ input: operation.input,+ });++ return {+ idempotencyKey: action.idempotencyKey,+ resourceId: result.skillDocumentId,+ status: MaintenanceActionStatus.Applied,+ summary: result.summary,+ };+ }++ throw new Error('Skill operation adapter is required');+};++const executeAction = async (+ handlers: MaintenanceOperationHandlers,+ action: MaintenanceActionPlan,+) => {+ if (action.applyMode === MaintenanceApplyMode.Skip) {+ return toSkippedResult(action);+ }++ if (action.applyMode === MaintenanceApplyMode.ProposalOnly) {+ return toProposedResult(action);+ }++ if (!isActionExecutable(action.applyMode)) {+ return toSkippedResult(action);+ }++ if (!action.operation) {+ return toSkippedResult(action);+ }++ try {+ const { operation } = action;++ if (operation.domain === 'memory') {+ return await executeMemoryAction(handlers, action, operation);+ }++ return await executeSkillAction(handlers, action, operation);+ } catch (error) {+ return toFailedResult(action, error);+ }+};++const getReviewRunStatus = (actions: MaintenanceReviewRunResult['actions']) => {+ if (actions.some((action) => action.status === MaintenanceActionStatus.Failed)) {+ return actions.some((action) => action.status === MaintenanceActionStatus.Applied)+ ? ReviewRunStatus.PartiallyApplied+ : ReviewRunStatus.Failed;+ }++ return ReviewRunStatus.Completed;+};++/**+ * Creates an ordered executor for normalized maintenance plans.+ *+ * Use when:+ * - Source handlers need to apply a planner-approved maintenance plan+ * - Tests need a dry executor with injected memory and skill services+ *+ * Expects:+ * - Risk and apply modes have already been assigned by the planner+ * - Domain services validate payloads again before writing+ *+ * Returns:+ * - An executor that records per-action results and continues after failures+ */+export const createMaintenanceExecutorService = (handlers: MaintenanceOperationHandlers) => ({+ execute: async (plan: MaintenancePlan): Promise<MaintenanceReviewRunResult> => {+ const actions = [];++ for (const action of plan.actions) {+ actions.push(await executeAction(handlers, action));+ }++ return {+ actions,+ status: getReviewRunStatus(actions),+ };+ },+});diff --git a/src/server/services/agentSignal/services/maintenance/memory.ts b/src/server/services/agentSignal/services/maintenance/memory.tsnew file mode 100644index 00000000000..b0926d58983--- /dev/null+++ b/src/server/services/agentSignal/services/maintenance/memory.ts@@ -0,0 +1,113 @@+import type { EvidenceRef } from './types';++const UNSAFE_AUTOMATIC_MEMORY_PATTERNS = [+ /\bprobably\b/i,+ /\bmaybe\b/i,+ /\bmedical\b/i,+ /\bhealth\b/i,+ /\brelationship\b/i,+ /\bfinance\b/i,+];++/** Input required to write one maintenance memory candidate. */+export interface WriteMaintenanceMemoryInput {+ /** Candidate durable memory content. */+ content: string;+ /** User that owns the memory. */+ userId: string;+}++/** Request envelope for one maintenance memory write. */+export interface MemoryMaintenanceWriteRequest {+ /** Evidence supporting the memory write. */+ evidenceRefs: EvidenceRef[];+ /** Stable action idempotency key. */+ idempotencyKey: string;+ /** Domain payload for memory persistence. */+ input: WriteMaintenanceMemoryInput;+}++/** Result returned after a memory write adapter applies a candidate. */+export interface MemoryMaintenanceWriteResult {+ /** Durable memory id. */+ memoryId: string;+ /** Optional short persistence summary. */+ summary?: string;+}++/** Persistence adapter for maintenance memory writes. */+export interface MemoryMaintenanceWriter {+ /** Writes memory through the existing memory extraction/persistence stack. */+ writeMemory?: (input: {+ content: string;+ evidenceRefs: EvidenceRef[];+ idempotencyKey: string;+ userId: string;+ }) => Promise<MemoryMaintenanceWriteResult>;+}++/**+ * Error thrown when an injected same-turn adapter needs executor-style status mapping.+ */+export class MemoryMaintenanceActionError extends Error {+ /** Status that should be surfaced by the same-turn action handler. */+ status: 'failed' | 'skipped';++ /**+ * Creates a memory action status error.+ *+ * Use when:+ * - A legacy same-turn memory runner returns skipped or failed+ * - The shared memory service is used as the validation boundary+ *+ * Expects:+ * - `status` is not `applied`+ *+ * Returns:+ * - An error with a stable status for handler mapping+ */+ constructor(message: string, status: 'failed' | 'skipped') {+ super(message);+ this.name = 'MemoryMaintenanceActionError';+ this.status = status;+ }+}++const assertSafeAutomaticMemory = (content: string) => {+ if (UNSAFE_AUTOMATIC_MEMORY_PATTERNS.some((pattern) => pattern.test(content))) {+ throw new Error('Memory candidate is not safe for automatic write');+ }+};++/**+ * Creates a memory maintenance service.+ *+ * Use when:+ * - Nightly or self-reflection maintenance needs to write validated memory candidates+ * - Same-turn action handlers need a shared validation boundary before persistence+ *+ * Expects:+ * - Server callers inject an adapter backed by the existing memory stack+ * - Planner has already decided the action may be attempted+ *+ * Returns:+ * - A service that validates automatic memory candidates before delegating persistence+ */+export const createMemoryMaintenanceService = (writer: MemoryMaintenanceWriter = {}) => ({+ writeMemory: async (+ request: MemoryMaintenanceWriteRequest,+ ): Promise<MemoryMaintenanceWriteResult> => {+ assertSafeAutomaticMemory(request.input.content);++ if (!writer.writeMemory) {+ throw new Error('Memory write adapter is required');+ }++ return writer.writeMemory({+ content: request.input.content,+ evidenceRefs: request.evidenceRefs,+ idempotencyKey: request.idempotencyKey,+ userId: request.input.userId,+ });+ },+});diff --git a/src/server/services/agentSignal/services/maintenance/nightlyCollector.ts b/src/server/services/agentSignal/services/maintenance/nightlyCollector.tsnew file mode 100644index 00000000000..bebd251bea6--- /dev/null+++ b/src/server/services/agentSignal/services/maintenance/nightlyCollector.ts@@ -0,0 +1,447 @@+import type { EvidenceRef } from './types';++const DEFAULT_MAX_TOPICS = 30;+const DEFAULT_MAX_MANAGED_SKILLS = 20;+const DEFAULT_MAX_RELEVANT_MEMORIES = 20;++const HIGH_SIGNAL_REASON_ORDER = [+ 'failure',+ 'negative_feedback',+ 'correction',+ 'failed_tool',+ 'receipt',+] as const;++const HIGH_SIGNAL_SCORE_WEIGHTS = {+ correction: 3000,+ failed_tool: 4000,+ failure: 4500,+ negative_feedback: 5000,+ receipt: 1500,+} as const satisfies Record<NightlyReviewHighSignalReason, number>;++const RAW_ATTRIBUTE_KEYS = new Set([+ 'messages',+ 'rawmessages',+ 'rawtranscript',+ 'rawtranscripts',+ 'transcript',+ 'transcripts',+]);++/** High-signal reason labels emitted for nightly topic ranking. */+export type NightlyReviewHighSignalReason = (typeof HIGH_SIGNAL_REASON_ORDER)[number];++/**+ * Input shared by nightly review collector read adapters.+ *+ * Use when:+ * - Digest data sources need the same user-agent review window+ * - Tests need to assert simple read inputs without DB coupling+ *+ * Expects:+ * - Review windows are ISO strings from the source event payload+ *+ * Returns:+ * - A bounded read request for one nightly review collection pass+ */+export interface NightlyReviewReadInput {+ /** Stable agent id being reviewed. */+ agentId: string;+ /** Maximum summaries to return from the read adapter. */+ limit?: number;+ /** Review window end as an ISO string. */+ reviewWindowEnd: string;+ /** Review window start as an ISO string. */+ reviewWindowStart: string;+ /** Stable user id owning the agent. */+ userId: string;+}++/** Input for listing digest-ish topic activity rows. */+export interface ListTopicActivityInput extends NightlyReviewReadInput {}++/** Input for listing managed skill summaries. */+export interface ListManagedSkillsInput extends NightlyReviewReadInput {}++/** Input for listing relevant memory summaries. */+export interface ListRelevantMemoriesInput extends NightlyReviewReadInput {}++/** Digest evidence counters and ids that can make a topic high-signal. */+export interface NightlyReviewTopicSignalFields {+ /** Number of correction events or correction-like markers in the topic. */+ correctionCount?: number;+ /** Stable ids for correction messages or operations. */+ correctionIds?: string[];+ /** Stable ids for failed tool calls. */+ failedToolCallIds?: string[];+ /** Number of failed tool calls in the topic. */+ failedToolCount?: number;+ /** Number of failure events in the topic. */+ failureCount?: number;+ /** Stable ids for failure messages, operations, or tasks. */+ failureIds?: string[];+ /** Whether the digest source already classified this topic as correction-bearing. */+ hasCorrection?: boolean;+ /** Whether the digest source already classified this topic as failed-tool-bearing. */+ hasFailedTool?: boolean;+ /** Whether the digest source already classified this topic as failure-bearing. */+ hasFailure?: boolean;+ /** Whether the digest source already classified this topic as negative-feedback-bearing. */+ hasNegativeFeedback?: boolean;+ /** Whether the digest source already classified this topic as receipt-bearing. */+ hasReceipt?: boolean;+ /** Number of negative feedback events in the topic. */+ negativeFeedbackCount?: number;+ /** Stable ids for negative feedback messages or reactions. */+ negativeFeedbackIds?: string[];+ /** Number of receipt events connected to the topic. */+ receiptCount?: number;+ /** Stable ids for receipt records. */+ receiptIds?: string[];+}++/** Topic digest row returned by the injected topic activity boundary. */+export interface NightlyReviewTopicActivityRow extends NightlyReviewTopicSignalFields {+ /** Optional digest metadata that callers may pass through to reviewers. */+ attributes?: Record<string, unknown>;+ /** Evidence refs from upstream digest construction. Preserved when provided. */+ evidenceRefs?: EvidenceRef[];+ /** Stable topic id. */+ id?: string;+ /** Last topic activity as an ISO string, used only as a deterministic tie-breaker. */+ lastActivityAt?: string;+ /** Total digest message count. Raw messages must not be included in collector output. */+ messageCount?: number;+ /** Raw transcript payloads from upstream sources. These are intentionally stripped. */+ rawMessages?: readonly unknown[];+ /** Digest summary safe to pass into review context. */+ summary?: string;+ /** Stable task ids represented by this topic digest. */+ taskIds?: string[];+ /** Human-readable digest title. */+ title?: string;+ /** Stable topic id when the source distinguishes row id from topic id. */+ topicId?: string;+}++/** Managed skill summary returned by the injected skill boundary. */+export interface NightlyReviewManagedSkillSummary {+ /** Optional digest metadata for reviewer context. */+ attributes?: Record<string, unknown>;+ /** Short skill description. */+ description?: string;+ /** Managed skill document id. */+ documentId?: string;+ /** Stable skill name. */+ name: string;+ /** Whether this skill is writable by maintenance flows. */+ readonly?: boolean;+ /** Last skill update as an ISO string. */+ updatedAt?: string;+}++/** Relevant memory summary returned by the injected memory boundary. */+export interface NightlyReviewRelevantMemorySummary {+ /** Optional digest metadata for reviewer context. */+ attributes?: Record<string, unknown>;+ /** Memory content summary or compact memory text. */+ content: string;+ /** Evidence refs already attached to this memory summary. */+ evidenceRefs?: EvidenceRef[];+ /** Stable memory id. */+ id: string;+ /** Last memory update as an ISO string. */+ updatedAt?: string;+}++/** Normalized topic digest emitted in nightly review context. */+export interface NightlyReviewTopicDigest extends Omit<+ NightlyReviewTopicActivityRow,+ 'rawMessages'+> {+ /** Evidence refs suitable for later non-noop draft actions. */+ evidenceRefs: EvidenceRef[];+ /** Ordered high-signal labels found on this topic. Empty for ordinary topics. */+ highSignalReasons: NightlyReviewHighSignalReason[];+ /** Deterministic collector score used for sorting digest topics. */+ reviewScore: number;+}++/** Read adapters used by the pure nightly review collector service. */+export interface NightlyReviewReadAdapters {+ /** Lists managed skill summaries for this agent and review window. */+ listManagedSkills: (input: ListManagedSkillsInput) => Promise<NightlyReviewManagedSkillSummary[]>;+ /** Lists relevant memory summaries for this agent and review window. */+ listRelevantMemories: (+ input: ListRelevantMemoriesInput,+ ) => Promise<NightlyReviewRelevantMemorySummary[]>;+ /** Lists digest-first topic activity rows for this agent and review window. */+ listTopicActivity: (input: ListTopicActivityInput) => Promise<NightlyReviewTopicActivityRow[]>;+}++/** Input for collecting one nightly review context. */+export interface CollectNightlyReviewContextInput {+ /** Stable agent id being reviewed. */+ agentId: string;+ /**+ * Maximum managed skill summaries in the returned context.+ *+ * @default 20+ */+ maxManagedSkills?: number;+ /**+ * Maximum relevant memory summaries in the returned context.+ *+ * @default 20+ */+ maxRelevantMemories?: number;+ /**+ * Maximum topic digests in the returned context.+ *+ * @default 30+ */+ maxTopics?: number;+ /** Review window end as an ISO string. */+ reviewWindowEnd: string;+ /** Review window start as an ISO string. */+ reviewWindowStart: string;+ /**+ * Optional upstream topic fetch budget before local ranking clips output.+ *+ * @default `maxTopics * 3`+ */+ topicFetchLimit?: number;+ /** Stable user id owning the agent. */+ userId: string;+}++/** Digest-first context consumed by nightly self-reflection reviewers. */+export interface NightlyReviewContext {+ /** Stable agent id being reviewed. */+ agentId: string;+ /** Managed skills relevant to the agent. */+ managedSkills: NightlyReviewManagedSkillSummary[];+ /** Memories relevant to the review window and agent. */+ relevantMemories: NightlyReviewRelevantMemorySummary[];+ /** Review window end as an ISO string. */+ reviewWindowEnd: string;+ /** Review window start as an ISO string. */+ reviewWindowStart: string;+ /** Ranked topic digests with evidence refs and no raw messages. */+ topics: NightlyReviewTopicDigest[];+ /** Stable user id owning the agent. */+ userId: string;+}++/** Nightly review collector service API. */+export interface NightlyReviewService {+ /**+ * Collects bounded digest context for one nightly self-reflection review.+ *+ * Use when:+ * - A nightly review source handler needs reviewer context+ * - The caller must avoid mutating memory, skills, maintenance state, or queues+ *+ * Expects:+ * - Dependencies return digest summaries instead of raw unbounded transcripts+ * - Review windows are already computed by the scheduler or source event+ *+ * Returns:+ * - A deterministic, bounded context containing topics, managed skills, and relevant memories+ */+ collectNightlyReviewContext: (+ input: CollectNightlyReviewContextInput,+ ) => Promise<NightlyReviewContext>;+}++const hasSignal = (count: number | undefined, flag: boolean | undefined) =>+ flag === true || (count ?? 0) > 0;++const getHighSignalReasons = (+ row: NightlyReviewTopicActivityRow,+): NightlyReviewHighSignalReason[] => {+ return HIGH_SIGNAL_REASON_ORDER.filter((reason) => {+ if (reason === 'failure') return hasSignal(row.failureCount, row.hasFailure);+ if (reason === 'negative_feedback') {+ return hasSignal(row.negativeFeedbackCount, row.hasNegativeFeedback);+ }+ if (reason === 'correction') return hasSignal(row.correctionCount, row.hasCorrection);+ if (reason === 'failed_tool') return hasSignal(row.failedToolCount, row.hasFailedTool);++ return hasSignal(row.receiptCount, row.hasReceipt);+ });+};++const getReasonCount = (+ row: NightlyReviewTopicActivityRow,+ reason: NightlyReviewHighSignalReason,+) => {+ if (reason === 'failure') return Math.max(row.failureCount ?? 0, row.hasFailure ? 1 : 0);+ if (reason === 'negative_feedback') {+ return Math.max(row.negativeFeedbackCount ?? 0, row.hasNegativeFeedback ? 1 : 0);+ }+ if (reason === 'correction') return Math.max(row.correctionCount ?? 0, row.hasCorrection ? 1 : 0);+ if (reason === 'failed_tool')+ return Math.max(row.failedToolCount ?? 0, row.hasFailedTool ? 1 : 0);++ return Math.max(row.receiptCount ?? 0, row.hasReceipt ? 1 : 0);+};++const scoreTopic = (+ row: NightlyReviewTopicActivityRow,+ reasons: NightlyReviewHighSignalReason[],+) => {+ return reasons.reduce(+ (score, reason) => score + HIGH_SIGNAL_SCORE_WEIGHTS[reason] * getReasonCount(row, reason),+ row.messageCount ?? 0,+ );+};++const pushUniqueRef = (refs: EvidenceRef[], ref: EvidenceRef) => {+ if (refs.some((existing) => existing.id === ref.id && existing.type === ref.type)) return;++ refs.push(ref);+};++const synthesizeEvidenceRefs = (row: NightlyReviewTopicActivityRow): EvidenceRef[] => {+ const refs: EvidenceRef[] = [];+ const topicId = row.topicId ?? row.id;++ if (topicId) pushUniqueRef(refs, { id: topicId, type: 'topic' });++ for (const taskId of row.taskIds ?? []) {+ pushUniqueRef(refs, { id: taskId, type: 'task' });+ }++ for (const failureId of row.failureIds ?? []) {+ pushUniqueRef(refs, { id: failureId, type: 'operation' });+ }++ for (const feedbackId of row.negativeFeedbackIds ?? []) {+ pushUniqueRef(refs, { id: feedbackId, type: 'message' });+ }++ for (const correctionId of row.correctionIds ?? []) {+ pushUniqueRef(refs, { id: correctionId, type: 'message' });+ }++ for (const toolCallId of row.failedToolCallIds ?? []) {+ pushUniqueRef(refs, { id: toolCallId, type: 'tool_call' });+ }++ for (const receiptId of row.receiptIds ?? []) {+ pushUniqueRef(refs, { id: receiptId, type: 'receipt' });+ }++ return refs;+};++const sanitizeTopicAttributes = (+ attributes: Record<string, unknown> | undefined,+): Record<string, unknown> | undefined => {+ if (!attributes) return undefined;++ const sanitizedAttributes = Object.fromEntries(+ Object.entries(attributes).filter(([key]) => !RAW_ATTRIBUTE_KEYS.has(key.toLowerCase())),+ );++ return Object.keys(sanitizedAttributes).length > 0 ? sanitizedAttributes : undefined;+};++const normalizeTopic = (row: NightlyReviewTopicActivityRow): NightlyReviewTopicDigest => {+ const { attributes, rawMessages: _rawMessages, ...digestRow } = row;+ const highSignalReasons = getHighSignalReasons(row);+ const sanitizedAttributes = sanitizeTopicAttributes(attributes);++ return {+ ...digestRow,+ ...(sanitizedAttributes ? { attributes: sanitizedAttributes } : {}),+ evidenceRefs:+ row.evidenceRefs && row.evidenceRefs.length > 0+ ? row.evidenceRefs+ : synthesizeEvidenceRefs(row),+ highSignalReasons,+ reviewScore: scoreTopic(row, highSignalReasons),+ };+};++const parseSortableTimestamp = (timestamp: string | undefined) => {+ if (!timestamp) return 0;++ const parsed = Date.parse(timestamp);++ return Number.isFinite(parsed) ? parsed : 0;+};++const compareTopics = (left: NightlyReviewTopicDigest, right: NightlyReviewTopicDigest) => {+ const leftHighSignalBucket = left.highSignalReasons.length > 0 ? 1 : 0;+ const rightHighSignalBucket = right.highSignalReasons.length > 0 ? 1 : 0;++ if (leftHighSignalBucket !== rightHighSignalBucket) {+ return rightHighSignalBucket - leftHighSignalBucket;+ }++ if (left.reviewScore !== right.reviewScore) return right.reviewScore - left.reviewScore;++ const leftLastActivity = parseSortableTimestamp(left.lastActivityAt);+ const rightLastActivity = parseSortableTimestamp(right.lastActivityAt);++ if (leftLastActivity !== rightLastActivity) return rightLastActivity - leftLastActivity;++ return (left.topicId ?? left.id ?? '').localeCompare(right.topicId ?? right.id ?? '');+};++/**+ * Creates a pure nightly review collector service from digest read adapters.+ *+ * Use when:+ * - Source handlers need bounded review context before reviewer/planner execution+ * - Tests need deterministic topic ranking without server data adapters+ *+ * Expects:+ * - Read adapters do not enqueue sources or mutate memory/skills+ * - Topic rows are digest-first summaries; raw transcript fields are discarded if present+ *+ * Returns:+ * - A collector service with one context assembly method+ */+export const createNightlyReviewService = (+ readAdapters: NightlyReviewReadAdapters,+): NightlyReviewService => {+ return {+ collectNightlyReviewContext: async (input) => {+ const maxTopics = input.maxTopics ?? DEFAULT_MAX_TOPICS;+ const maxManagedSkills = input.maxManagedSkills ?? DEFAULT_MAX_MANAGED_SKILLS;+ const maxRelevantMemories = input.maxRelevantMemories ?? DEFAULT_MAX_RELEVANT_MEMORIES;+ const readInput = {+ agentId: input.agentId,+ reviewWindowEnd: input.reviewWindowEnd,+ reviewWindowStart: input.reviewWindowStart,+ userId: input.userId,+ };++ const [topicRows, managedSkills, relevantMemories] = await Promise.all([+ readAdapters.listTopicActivity({+ ...readInput,+ limit: input.topicFetchLimit ?? maxTopics * 3,+ }),+ readAdapters.listManagedSkills({+ ...readInput,+ limit: maxManagedSkills,+ }),+ readAdapters.listRelevantMemories({+ ...readInput,+ limit: maxRelevantMemories,+ }),+ ]);++ return {+ ...readInput,+ managedSkills: managedSkills.slice(0, maxManagedSkills),+ relevantMemories: relevantMemories.slice(0, maxRelevantMemories),+ topics: topicRows.map(normalizeTopic).sort(compareTopics).slice(0, maxTopics),+ };+ },+ };+};diff --git a/src/server/services/agentSignal/services/maintenance/nightlySchedule.ts b/src/server/services/agentSignal/services/maintenance/nightlySchedule.tsnew file mode 100644index 00000000000..62976575e91--- /dev/null+++ b/src/server/services/agentSignal/services/maintenance/nightlySchedule.ts@@ -0,0 +1,264 @@+import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';+import dayjs from 'dayjs';+import timezonePlugin from 'dayjs/plugin/timezone';+import utc from 'dayjs/plugin/utc';++import { AgentSignalNightlyReviewModel } from '@/database/models/agentSignal/nightlyReview';+import type { LobeChatDatabase } from '@/database/type';+import type { AgentSignalSourceEventInput } from '@/server/services/agentSignal/emitter';+import { enqueueAgentSignalSourceEvent } from '@/server/services/agentSignal/emitter';++import { buildNightlyReviewSourceId } from './types';++dayjs.extend(utc);+dayjs.extend(timezonePlugin);++const FALLBACK_TIMEZONE = 'UTC';+const NIGHT_WINDOW_START_HOUR = 22;+const NIGHT_WINDOW_END_HOUR = 23;++/** Active agent target returned by the nightly review scheduler data boundary. */+export interface NightlyReviewAgentTarget {+ /** Agent id that should receive one nightly review source event. */+ agentId: string;+}++/** User candidate returned by the nightly review scheduler data boundary. */+export interface NightlyReviewEligibleUser {+ /** User creation time used by stable scheduler pagination. */+ createdAt?: Date;+ /** Stable user id. */+ id: string;+ /** IANA timezone for local night-window evaluation. */+ timezone?: string | null;+}++/** Cursor for stable nightly review user pagination. */+export interface NightlyReviewScheduleCursor {+ /** User creation time used as the primary cursor key. */+ createdAt: Date;+ /** User id used as the tie-break cursor key. */+ id: string;+}++/** Options for listing users during one nightly review dispatch pass. */+export interface ListNightlyReviewEligibleUsersInput {+ /** Cursor returned by the previous scheduler page. */+ cursor?: NightlyReviewScheduleCursor;+ /** Maximum eligible users to return. */+ limit?: number;+ /** Optional allowlist for targeted backfills or tests. */+ whitelist?: string[];+}++/** Options for listing one user's active review targets in a UTC window. */+export interface ListNightlyReviewAgentTargetsInput {+ /** Maximum active agents to return. */+ limit?: number;+ /** User id whose active agents should be listed. */+ userId: string;+ /** Review window end in UTC. */+ windowEnd: Date;+ /** Review window start in UTC. */+ windowStart: Date;+}++/** Queue and read adapters used by the pure nightly review scheduler service. */+export interface NightlyReviewScheduleAdapters {+ /**+ * Enqueues one AgentSignal source event for later handler execution.+ *+ * @default Server adapter uses {@link enqueueAgentSignalSourceEvent}+ */+ enqueueSource: (+ input: AgentSignalSourceEventInput<'agent.nightly_review.requested'>,+ ) => Promise<unknown>;+ /** Lists active self-iteration agent targets for one user and review window. */+ listActiveAgentTargets: (+ input: ListNightlyReviewAgentTargetsInput,+ ) => Promise<NightlyReviewAgentTarget[]>;+ /** Lists user candidates eligible for nightly review scheduling. */+ listEligibleUsers: (+ input?: ListNightlyReviewEligibleUsersInput,+ ) => Promise<NightlyReviewEligibleUser[]>;+ /**+ * Supplies the scheduler dispatch time.+ *+ * @default Uses the current wall-clock time when omitted.+ */+ now?: () => Date;+}++/** Options for one nightly review dispatch pass. */+export interface DispatchNightlyReviewRequestsOptions extends ListNightlyReviewEligibleUsersInput {+ /** Maximum active agents to enqueue for each eligible in-window user. */+ targetLimit?: number;+}++/** Summary returned by one nightly review dispatch pass. */+export interface NightlyReviewScheduleSummary {+ /** Number of source events successfully requested for enqueue. */+ enqueued: number;+ /** Number of eligible users skipped because their local time is outside the night window. */+ skipped: number;+}++/** Nightly review scheduler service API. */+export interface NightlyReviewScheduleService {+ /**+ * Dispatches nightly review request sources for users currently in their local night window.+ *+ * Use when:+ * - A shared cron or QStash schedule performs one central dispatch pass+ * - Cron should only produce source events and leave review execution to AgentSignal handlers+ *+ * Expects:+ * - Adapters return users and targets without side effects except `enqueueSource`+ * - `now` is a UTC instant shared by all users in the pass+ *+ * Returns:+ * - A summary with enqueue and skip counts for observability+ */+ dispatchNightlyReviewRequests: (+ options?: DispatchNightlyReviewRequestsOptions,+ ) => Promise<NightlyReviewScheduleSummary>;+}++interface LocalNightWindow {+ localDate: string;+ reviewWindowStart: Date;+ timezone: string;+ withinWindow: boolean;+}++export { buildNightlyReviewSourceId } from './types';++const resolveTimezone = (timezone: string | null | undefined): string => {+ if (!timezone) return FALLBACK_TIMEZONE;++ try {+ new Intl.DateTimeFormat('en-US', { timeZone: timezone }).format();+ return timezone;+ } catch {+ return FALLBACK_TIMEZONE;+ }+};++const getLocalNightWindow = (now: Date, timezone: string | null | undefined): LocalNightWindow => {+ const resolvedTimezone = resolveTimezone(timezone);+ const localNow = dayjs(now).tz(resolvedTimezone);+ const localDate = localNow.format('YYYY-MM-DD');+ const localHour = localNow.hour();++ return {+ localDate,+ reviewWindowStart: dayjs.tz(localDate, resolvedTimezone).startOf('day').toDate(),+ timezone: resolvedTimezone,+ withinWindow: localHour >= NIGHT_WINDOW_START_HOUR && localHour <= NIGHT_WINDOW_END_HOUR,+ };+};++/**+ * Creates a pure nightly review scheduler service from queue and read adapters.+ *+ * Use when:+ * - Tests need deterministic time and mocked storage/queue adapters+ * - Server code needs a cron-safe service that emits only AgentSignal sources+ *+ * Expects:+ * - `listEligibleUsers` reads timezone fresh for each dispatch pass+ * - Invalid timezone values can be safely normalized to UTC+ *+ * Returns:+ * - A scheduler service with one dispatch method+ */+export const createNightlyReviewScheduleService = (+ adapters: NightlyReviewScheduleAdapters,+): NightlyReviewScheduleService => {+ return {+ dispatchNightlyReviewRequests: async (options = {}) => {+ const now = adapters.now?.() ?? new Date();+ const users = await adapters.listEligibleUsers({+ cursor: options.cursor,+ limit: options.limit,+ whitelist: options.whitelist,+ });+ let enqueued = 0;+ let skipped = 0;++ for (const user of users) {+ const localWindow = getLocalNightWindow(now, user.timezone);++ if (!localWindow.withinWindow) {+ skipped += 1;+ continue;+ }++ const targets = await adapters.listActiveAgentTargets({+ limit: options.targetLimit,+ userId: user.id,+ windowEnd: now,+ windowStart: localWindow.reviewWindowStart,+ });++ for (const target of targets) {+ await adapters.enqueueSource({+ payload: {+ agentId: target.agentId,+ localDate: localWindow.localDate,+ requestedAt: now.toISOString(),+ reviewWindowEnd: now.toISOString(),+ reviewWindowStart: localWindow.reviewWindowStart.toISOString(),+ timezone: localWindow.timezone,+ userId: user.id,+ },+ sourceId: buildNightlyReviewSourceId({+ agentId: target.agentId,+ localDate: localWindow.localDate,+ userId: user.id,+ }),+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentNightlyReviewRequested,+ timestamp: now.getTime(),+ });+ enqueued += 1;+ }+ }++ return { enqueued, skipped };+ },+ };+};++/**+ * Creates the server nightly review scheduler service.+ *+ * Use when:+ * - Cron or QStash dispatch code needs database-backed target discovery+ * - Server should enqueue AgentSignal source events without running review handlers inline+ *+ * Expects:+ * - `db` points at the main LobeChat database+ *+ * Returns:+ * - A scheduler service wired to {@link AgentSignalNightlyReviewModel} and AgentSignal enqueueing+ */+export const createServerNightlyReviewScheduleService = (+ db: LobeChatDatabase,+): NightlyReviewScheduleService => {+ const model = new AgentSignalNightlyReviewModel(db);++ return createNightlyReviewScheduleService({+ enqueueSource: (input) =>+ enqueueAgentSignalSourceEvent(input, {+ agentId: input.payload.agentId,+ userId: input.payload.userId,+ }),+ listActiveAgentTargets: ({ limit, userId, windowEnd, windowStart }) =>+ model.listActiveAgentTargets(userId, {+ limit,+ windowEnd,+ windowStart,+ }),+ listEligibleUsers: (input) => model.listEligibleUsers(input),+ });+};diff --git a/src/server/services/agentSignal/services/maintenance/planner.ts b/src/server/services/agentSignal/services/maintenance/planner.tsnew file mode 100644index 00000000000..bf9e377c961--- /dev/null+++ b/src/server/services/agentSignal/services/maintenance/planner.ts@@ -0,0 +1,312 @@+import type {+ MaintenanceActionDraft,+ MaintenanceActionPlan,+ MaintenanceDomainOperation,+ MaintenancePlan,+ MaintenancePlanRequest,+} from './types';+import {+ buildMaintenanceActionIdempotencyKey,+ MaintenanceApplyMode,+ MaintenanceReviewScope,+ MaintenanceRisk,+} from './types';++/** Options for deterministic maintenance action planning. */+export interface MaintenancePlannerOptions {+ /**+ * Maximum low-risk actions that may be auto-applied in one plan.+ *+ * @default 3+ */+ maxAutoApplyActions?: number;+ /**+ * Planner version recorded in emitted plans.+ *+ * @default 'self-reflect-maintenance-planner-v1'+ */+ plannerVersion?: string;+}++const LOW_RISK_CONFIDENCE_THRESHOLD = 0.8;+const MEMORY_AUTO_APPLY_CONFIDENCE_THRESHOLD = 0.85;+const SKILL_AUTO_APPLY_CONFIDENCE_THRESHOLD = 0.9;++const createDedupeKey = (draft: MaintenanceActionDraft) => {+ if (draft.actionType === 'write_memory') {+ const content =+ draft.value && typeof draft.value === 'object' && 'content' in draft.value+ ? draft.value.content+ : undefined;++ return `memory:${typeof content === 'string' ? content : draft.rationale}`;+ }++ if (draft.target?.skillDocumentId) {+ return `skill:${draft.target.skillDocumentId}`;+ }++ if (draft.target?.skillName) {+ return `skill:${draft.target.skillName}`;+ }++ return `${draft.actionType}:${draft.rationale}`;+};++const getRecordField = (value: unknown, key: string) => {+ if (!value || typeof value !== 'object') return undefined;++ return (value as Record<string, unknown>)[key];+};++const getStringField = (value: unknown, key: string) => {+ const field = getRecordField(value, key);++ return typeof field === 'string' && field.trim().length > 0 ? field.trim() : undefined;+};++const getStringArrayField = (value: unknown, key: string) => {+ const field = getRecordField(value, key);++ if (!Array.isArray(field)) return undefined;++ const strings = field.filter((item): item is string => typeof item === 'string');++ return strings.length === field.length && strings.length > 0 ? strings : undefined;+};++const getReadonlyField = (value: unknown) => {+ const field = getRecordField(value, 'targetReadonly') ?? getRecordField(value, 'readonly');++ return typeof field === 'boolean' ? field : undefined;+};++const getTargetReadonly = (draft: MaintenanceActionDraft) =>+ draft.target?.targetReadonly ?? getReadonlyField(draft.value);++const createOperation = (+ draft: MaintenanceActionDraft,+ request: MaintenancePlanRequest,+): MaintenanceDomainOperation | undefined => {+ if (draft.actionType === 'write_memory') {+ const content = getStringField(draft.value, 'content');++ if (!content) return undefined;++ return {+ domain: 'memory',+ input: { content, userId: request.userId },+ operation: 'write',+ };+ }++ if (draft.actionType === 'create_skill') {+ return {+ domain: 'skill',+ input: {+ bodyMarkdown:+ getStringField(draft.value, 'bodyMarkdown') ?? getStringField(draft.value, 'content'),+ description: getStringField(draft.value, 'description'),+ name: getStringField(draft.value, 'name'),+ targetReadonly: getTargetReadonly(draft),+ title: getStringField(draft.value, 'title'),+ userId: request.userId,+ },+ operation: 'create',+ };+ }++ if (draft.actionType === 'refine_skill') {+ const skillDocumentId =+ getStringField(draft.value, 'skillDocumentId') ?? draft.target?.skillDocumentId;++ if (!skillDocumentId) return undefined;++ return {+ domain: 'skill',+ input: {+ patch:+ getStringField(draft.value, 'patch') ??+ getStringField(draft.value, 'bodyMarkdown') ??+ getStringField(draft.value, 'content'),+ targetReadonly: getTargetReadonly(draft),+ skillDocumentId,+ userId: request.userId,+ },+ operation: 'refine',+ };+ }++ if (draft.actionType === 'consolidate_skill') {+ const canonicalSkillDocumentId =+ getStringField(draft.value, 'canonicalSkillDocumentId') ?? draft.target?.skillDocumentId;+ const sourceSkillIds = getStringArrayField(draft.value, 'sourceSkillIds');++ if (!canonicalSkillDocumentId || !sourceSkillIds) return undefined;++ return {+ domain: 'skill',+ input: {+ canonicalSkillDocumentId,+ targetReadonly: getTargetReadonly(draft),+ sourceSkillIds,+ userId: request.userId,+ },+ operation: 'consolidate',+ };+ }++ return undefined;+};++const isReadonlyDraftTarget = (draft: MaintenanceActionDraft) => Boolean(getTargetReadonly(draft));++const classifyMemoryPlan = (+ draft: MaintenanceActionDraft,+): Pick<MaintenanceActionPlan, 'applyMode' | 'risk'> => {+ if (draft.policyHints?.sensitivity === 'sensitive') {+ return { applyMode: MaintenanceApplyMode.ProposalOnly, risk: MaintenanceRisk.High };+ }++ const canAutoApply =+ draft.confidence >= MEMORY_AUTO_APPLY_CONFIDENCE_THRESHOLD &&+ draft.policyHints?.evidenceStrength === 'strong' &&+ draft.policyHints?.persistence === 'stable' &&+ draft.policyHints?.sensitivity === 'normal' &&+ draft.policyHints?.userExplicitness === 'explicit';++ if (!canAutoApply) {+ return { applyMode: MaintenanceApplyMode.ProposalOnly, risk: MaintenanceRisk.Medium };+ }++ return { applyMode: MaintenanceApplyMode.AutoApply, risk: MaintenanceRisk.Low };+};++const isStrongSmallSkillDraft = (draft: MaintenanceActionDraft) =>+ draft.confidence >= SKILL_AUTO_APPLY_CONFIDENCE_THRESHOLD &&+ draft.policyHints?.evidenceStrength === 'strong' &&+ draft.policyHints?.mutationScope === 'small';++const hasAutoApplySkillIntent = (draft: MaintenanceActionDraft) =>+ draft.policyHints?.userExplicitness === 'explicit' ||+ (draft.actionType === 'refine_skill' &&+ draft.policyHints?.userExplicitness === 'implicit' &&+ draft.evidenceRefs.length >= 2);++const classifySkillPlan = (+ draft: MaintenanceActionDraft,+ reviewScope: MaintenanceReviewScope,+): Pick<MaintenanceActionPlan, 'applyMode' | 'risk'> => {+ if (draft.actionType === 'consolidate_skill') {+ return { applyMode: MaintenanceApplyMode.ProposalOnly, risk: MaintenanceRisk.High };+ }++ if (isReadonlyDraftTarget(draft)) {+ return { applyMode: MaintenanceApplyMode.ProposalOnly, risk: MaintenanceRisk.High };+ }++ if (!isStrongSmallSkillDraft(draft) || !hasAutoApplySkillIntent(draft)) {+ return { applyMode: MaintenanceApplyMode.ProposalOnly, risk: MaintenanceRisk.Medium };+ }++ if (draft.actionType === 'refine_skill' && !draft.target?.skillDocumentId) {+ return { applyMode: MaintenanceApplyMode.ProposalOnly, risk: MaintenanceRisk.Medium };+ }++ if (+ draft.actionType === 'create_skill' &&+ reviewScope !== MaintenanceReviewScope.SelfIterationIntent+ ) {+ return { applyMode: MaintenanceApplyMode.ProposalOnly, risk: MaintenanceRisk.Medium };+ }++ return { applyMode: MaintenanceApplyMode.AutoApply, risk: MaintenanceRisk.Low };+};++const classifyInitialPlan = (+ draft: MaintenanceActionDraft,+ reviewScope: MaintenanceReviewScope,+): Pick<MaintenanceActionPlan, 'applyMode' | 'risk'> => {+ if (draft.evidenceRefs.length === 0 || draft.confidence < LOW_RISK_CONFIDENCE_THRESHOLD) {+ return { applyMode: MaintenanceApplyMode.Skip, risk: MaintenanceRisk.High };+ }++ if (draft.actionType === 'noop' || draft.actionType === 'proposal_only') {+ return { applyMode: MaintenanceApplyMode.ProposalOnly, risk: MaintenanceRisk.Medium };+ }++ if (draft.actionType === 'write_memory') {+ return classifyMemoryPlan(draft);+ }++ return classifySkillPlan(draft, reviewScope);+};++/**+ * Creates the deterministic self-reflection maintenance planner.+ *+ * Use when:+ * - Reviewer drafts need to become bounded executable action plans+ * - Source handlers need one policy boundary before executor mutation+ *+ * Expects:+ * - Reviewer output has already been parsed into `MaintenancePlanDraft`+ * - Domain services will perform final payload validation before writing+ *+ * Returns:+ * - A planner that emits `MaintenancePlan` without performing side effects+ */+export const createMaintenancePlannerService = (options: MaintenancePlannerOptions = {}) => {+ const maxAutoApplyActions = options.maxAutoApplyActions ?? 3;+ const plannerVersion = options.plannerVersion ?? 'self-reflect-maintenance-planner-v1';++ return {+ plan: (request: MaintenancePlanRequest): MaintenancePlan => {+ let autoApplyCount = 0;++ const actions = request.draft.actions.map((draft): MaintenanceActionPlan => {+ const dedupeKey = createDedupeKey(draft);+ const initialPlan = classifyInitialPlan(draft, request.reviewScope);+ const operation = createOperation(draft, request);+ const applyMode =+ initialPlan.applyMode === MaintenanceApplyMode.AutoApply &&+ (autoApplyCount >= maxAutoApplyActions || !operation)+ ? MaintenanceApplyMode.ProposalOnly+ : initialPlan.applyMode;++ if (applyMode === MaintenanceApplyMode.AutoApply) {+ autoApplyCount += 1;+ }++ return {+ actionType: draft.actionType,+ applyMode,+ confidence: draft.confidence,+ dedupeKey,+ evidenceRefs: draft.evidenceRefs,+ idempotencyKey: buildMaintenanceActionIdempotencyKey({+ actionType: draft.actionType,+ dedupeKey,+ sourceId: request.sourceId,+ }),+ operation,+ rationale: draft.rationale,+ risk:+ initialPlan.applyMode === MaintenanceApplyMode.AutoApply &&+ applyMode === MaintenanceApplyMode.ProposalOnly+ ? MaintenanceRisk.Medium+ : initialPlan.risk,+ target: draft.target,+ };+ });++ return {+ actions,+ localDate: request.localDate,+ plannerVersion,+ reviewScope: request.reviewScope,+ summary: request.draft.summary,+ };+ },+ };+};diff --git a/src/server/services/agentSignal/services/maintenance/serverRuntime.ts b/src/server/services/agentSignal/services/maintenance/serverRuntime.tsnew file mode 100644index 00000000000..0a722004838--- /dev/null+++ b/src/server/services/agentSignal/services/maintenance/serverRuntime.ts@@ -0,0 +1,680 @@+import { DEFAULT_MINI_SYSTEM_AGENT_ITEM } from '@lobechat/const';+import type { GenerateObjectSchema } from '@lobechat/model-runtime';+import { createAgentSignalNightlyReviewMessages } from '@lobechat/prompts';+import { RequestTrigger } from '@lobechat/types';+import { z } from 'zod';++import { AgentSignalNightlyReviewModel } from '@/database/models/agentSignal/nightlyReview';+import { AgentSignalReviewContextModel } from '@/database/models/agentSignal/reviewContext';+import type { LobeChatDatabase } from '@/database/type';+import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';+import { isAgentSignalEnabledForUser } from '@/server/services/agentSignal/featureGate';+import { runMemoryActionAgent } from '@/server/services/agentSignal/policies/analyzeIntent/actions/userMemory';+import type { CreateNightlyReviewSourceHandlerDependencies } from '@/server/services/agentSignal/policies/reviewNightly/nightlyReview';+import type { CreateSelfIterationIntentSourceHandlerDependencies } from '@/server/services/agentSignal/policies/reviewNightly/selfIterationIntent';+import type {+ CollectSelfReflectionContextInput,+ CreateSelfReflectionSourceHandlerDependencies,+ SelfReflectionReviewContext,+} from '@/server/services/agentSignal/policies/reviewNightly/selfReflection';+import { SkillManagementDocumentService } from '@/server/services/skillManagement';++import { AGENT_SIGNAL_DEFAULTS } from '../../constants';+import {+ createDurableSelfReflectionAccumulator,+ createProcedurePolicyOptions,+} from '../../procedure';+import { redisPolicyStateStore } from '../../store/adapters/redis/policyStateStore';+import { redisSourceEventStore } from '../../store/adapters/redis/sourceEventStore';+import { persistAgentSignalReceipts } from '../receiptService';+import { createSelfReflectionService } from '../selfReflection';+import { createMaintenanceExecutorService } from './executor';+import { createMemoryMaintenanceService } from './memory';+import type {+ NightlyReviewContext,+ NightlyReviewManagedSkillSummary,+ NightlyReviewRelevantMemorySummary,+ NightlyReviewTopicActivityRow,+} from './nightlyCollector';+import { createNightlyReviewService } from './nightlyCollector';+import { createMaintenancePlannerService } from './planner';+import { createSkillManagementService } from './skill';+import type { MaintenanceActionDraft, MaintenancePlanDraft } from './types';++// NOTICE:+// This schema is intentionally hand-authored for `generateObject` structured output.+// Zod-generated JSON Schema is not compatible enough here: strict model schemas need+// exact `required`, `additionalProperties`, enum, and nullable shapes. Keep the Zod+// parser below as the server-side validation boundary instead of deriving this schema.+const NIGHTLY_REVIEW_AGENT_SCHEMA = {+ name: 'agent_signal_nightly_self_review',+ schema: {+ additionalProperties: false,+ properties: {+ actions: {+ items: {+ additionalProperties: false,+ properties: {+ actionType: {+ enum: [+ 'write_memory',+ 'create_skill',+ 'refine_skill',+ 'consolidate_skill',+ 'noop',+ 'proposal_only',+ ],+ type: 'string',+ },+ confidence: { maximum: 1, minimum: 0, type: 'number' },+ evidenceRefs: {+ items: {+ additionalProperties: false,+ properties: {+ id: { type: 'string' },+ summary: { type: 'string' },+ type: {+ enum: [+ 'topic',+ 'message',+ 'operation',+ 'source',+ 'receipt',+ 'tool_call',+ 'task',+ 'agent_document',+ 'memory',+ ],+ type: 'string',+ },+ },+ required: ['id', 'type'],+ type: 'object',+ },+ type: 'array',+ },+ policyHints: {+ additionalProperties: false,+ properties: {+ evidenceStrength: { enum: ['weak', 'medium', 'strong'], type: 'string' },+ mutationScope: { enum: ['small', 'broad'], type: 'string' },+ persistence: { enum: ['stable', 'temporal'], type: 'string' },+ sensitivity: { enum: ['normal', 'sensitive'], type: 'string' },+ userExplicitness: { enum: ['explicit', 'implicit', 'inferred'], type: 'string' },+ },+ type: 'object',+ },+ rationale: { type: 'string' },+ target: {+ additionalProperties: false,+ properties: {+ memoryId: { type: 'string' },+ skillDocumentId: { type: 'string' },+ skillName: { type: 'string' },+ targetReadonly: { type: 'boolean' },+ taskIds: { items: { type: 'string' }, type: 'array' },+ topicIds: { items: { type: 'string' }, type: 'array' },+ },+ type: 'object',+ },+ value: { type: ['object', 'string', 'null'] },+ },+ required: ['actionType', 'confidence', 'evidenceRefs', 'rationale'],+ type: 'object',+ },+ type: 'array',+ },+ findings: {+ items: {+ additionalProperties: false,+ properties: {+ evidenceRefs: {+ items: {+ additionalProperties: false,+ properties: {+ id: { type: 'string' },+ summary: { type: 'string' },+ type: { type: 'string' },+ },+ required: ['id', 'type'],+ type: 'object',+ },+ type: 'array',+ },+ severity: { enum: ['high', 'low', 'medium'], type: 'string' },+ summary: { type: 'string' },+ },+ required: ['evidenceRefs', 'severity', 'summary'],+ type: 'object',+ },+ type: 'array',+ },+ summary: { type: 'string' },+ },+ required: ['actions', 'findings', 'summary'],+ type: 'object',+ },+ strict: true,+} satisfies GenerateObjectSchema;++// Runtime parser for model output after structured generation. This mirrors the+// model-facing schema above, but the two schemas serve different boundaries.+const EvidenceRefSchema = z.object({+ id: z.string(),+ summary: z.string().optional(),+ type: z.enum([+ 'topic',+ 'message',+ 'operation',+ 'source',+ 'receipt',+ 'tool_call',+ 'task',+ 'agent_document',+ 'memory',+ ]),+});++const MaintenanceActionDraftSchema = z.object({+ actionType: z.enum([+ 'write_memory',+ 'create_skill',+ 'refine_skill',+ 'consolidate_skill',+ 'noop',+ 'proposal_only',+ ]),+ confidence: z.number().min(0).max(1),+ evidenceRefs: z.array(EvidenceRefSchema),+ policyHints: z+ .object({+ evidenceStrength: z.enum(['weak', 'medium', 'strong']).optional(),+ mutationScope: z.enum(['small', 'broad']).optional(),+ persistence: z.enum(['stable', 'temporal']).optional(),+ sensitivity: z.enum(['normal', 'sensitive']).optional(),+ userExplicitness: z.enum(['explicit', 'implicit', 'inferred']).optional(),+ })+ .optional(),+ rationale: z.string(),+ target: z+ .object({+ memoryId: z.string().optional(),+ skillDocumentId: z.string().optional(),+ skillName: z.string().optional(),+ targetReadonly: z.boolean().optional(),+ taskIds: z.array(z.string()).optional(),+ topicIds: z.array(z.string()).optional(),+ })+ .optional(),+ value: z.unknown().optional(),+}) satisfies z.ZodType<MaintenanceActionDraft>;++const MaintenancePlanDraftSchema = z.object({+ actions: z.array(MaintenanceActionDraftSchema),+ findings: z.array(+ z.object({+ evidenceRefs: z.array(EvidenceRefSchema),+ severity: z.enum(['high', 'low', 'medium']),+ summary: z.string(),+ }),+ ),+ summary: z.string(),+}) satisfies z.ZodType<MaintenancePlanDraft>;++const getStringField = (value: unknown, key: string) => {+ if (!value || typeof value !== 'object') return undefined;++ const field = (value as Record<string, unknown>)[key];+ return typeof field === 'string' && field.trim().length > 0 ? field.trim() : undefined;+};++const createSkillNameFromTitle = (title: string | undefined) =>+ (title ?? 'agent-signal-skill')+ .toLowerCase()+ .replaceAll(/[^a-z0-9]+/g, '-')+ .replaceAll(/^-|-$/g, '')+ .slice(0, 48) || 'agent-signal-skill';++/**+ * Options for composing server maintenance policy handlers.+ */+export interface CreateServerMaintenancePolicyOptions {+ /** Agent id from the workflow payload, used as an extra ownership check. */+ agentId?: string;+ /** Database bound to the current workflow worker. */+ db: LobeChatDatabase;+ /**+ * User-level Agent Signal gate computed by workflow normalization.+ *+ * @default false+ */+ selfIterationEnabled?: boolean;+ /** User id from the workflow payload. */+ userId: string;+}++const createServerMaintenanceExecutor = (input: {+ agentId?: string;+ db: LobeChatDatabase;+ skillDocumentService: SkillManagementDocumentService;+ userId: string;+}) => {+ return createMaintenanceExecutorService({+ memory: createMemoryMaintenanceService({+ writeMemory: async ({ content, evidenceRefs, idempotencyKey }) => {+ const result = await runMemoryActionAgent(+ {+ agentId: input.agentId,+ message: content,+ reason: `Agent Signal maintenance memory candidate from ${evidenceRefs.length} evidence refs.`,+ },+ {+ db: input.db,+ userId: input.userId,+ },+ );++ if (result.status !== 'applied') {+ throw new Error(+ result.detail ?? 'Memory action agent did not apply a durable memory write.',+ );+ }++ return {+ memoryId: idempotencyKey,+ summary: result.detail ?? content,+ };+ },+ }),+ skill: createSkillManagementService({+ createSkill: async ({ input: skillInput }) => {+ const bodyMarkdown =+ getStringField(skillInput, 'bodyMarkdown') ?? getStringField(skillInput, 'content') ?? '';+ const title = getStringField(skillInput, 'title') ?? getStringField(skillInput, 'name');+ const result = await input.skillDocumentService.createSkill({+ agentId: input.agentId ?? '',+ bodyMarkdown,+ description: getStringField(skillInput, 'description') ?? 'Agent Signal managed skill.',+ name: createSkillNameFromTitle(getStringField(skillInput, 'name') ?? title),+ title: title ?? 'Agent Signal skill',+ });++ return {+ skillDocumentId: result.bundle.agentDocumentId,+ summary: `Created managed skill ${result.name}.`,+ };+ },+ refineSkill: async ({ input: skillInput }) => {+ const bodyMarkdown =+ getStringField(skillInput, 'bodyMarkdown') ??+ getStringField(skillInput, 'patch') ??+ getStringField(skillInput, 'content') ??+ '';+ const result = await input.skillDocumentService.replaceSkillIndex({+ agentId: input.agentId ?? '',+ agentDocumentId: skillInput.skillDocumentId,+ bodyMarkdown,+ description: getStringField(skillInput, 'description'),+ });++ if (!result) throw new Error('Skill target not found');++ return {+ skillDocumentId: result.bundle.agentDocumentId,+ summary: `Refined managed skill ${result.name}.`,+ };+ },+ }),+ });+};++const canRunMaintenanceReview = async (input: {+ agentId: string;+ expectedAgentId?: string;+ reviewContextModel: AgentSignalReviewContextModel;+ selfIterationEnabled: boolean;+}) => {+ if (!input.selfIterationEnabled) return false;+ if (input.expectedAgentId && input.agentId !== input.expectedAgentId) return false;++ return input.reviewContextModel.canAgentRunSelfIteration(input.agentId);+};++const runServerMaintenanceReviewAgent = async (+ db: LobeChatDatabase,+ userId: string,+ context: NightlyReviewContext | SelfReflectionReviewContext,+) => {+ const modelRuntime = await initModelRuntimeFromDB(+ db,+ userId,+ DEFAULT_MINI_SYSTEM_AGENT_ITEM.provider,+ );+ const result = await modelRuntime.generateObject(+ {+ messages: createAgentSignalNightlyReviewMessages(context),+ model: DEFAULT_MINI_SYSTEM_AGENT_ITEM.model,+ schema: NIGHTLY_REVIEW_AGENT_SCHEMA,+ },+ { metadata: { trigger: RequestTrigger.AgentSignal } },+ );++ return MaintenancePlanDraftSchema.parse(result);+};++const collectSelfReflectionContext = async (+ reviewContextModel: AgentSignalReviewContextModel,+ input: CollectSelfReflectionContextInput,+): Promise<SelfReflectionReviewContext> => {+ const topicIds =+ input.scopeType === 'topic' || input.topicId+ ? [input.topicId ?? input.scopeId].filter((value): value is string => Boolean(value))+ : [];+ const rows = topicIds.length+ ? await reviewContextModel.listSelfReflectionTopicActivity({+ agentId: input.agentId,+ topicId: topicIds[0],+ windowEnd: new Date(input.windowEnd),+ windowStart: new Date(input.windowStart),+ })+ : [];++ return {+ ...input,+ evidenceRefs: [+ {+ id: input.scopeId,+ type: input.scopeType,+ },+ ],+ topics: rows.map((row) => ({+ evidenceRefs: row.topicId ? [{ id: row.topicId, type: 'topic' }] : [],+ failedToolCount: row.failedToolCount,+ failureCount: row.failureCount,+ lastActivityAt: row.lastActivityAt?.toISOString(),+ messageCount: row.messageCount,+ summary: row.summary,+ title: row.title ?? undefined,+ topicId: row.topicId ?? undefined,+ })),+ };+};++/**+ * Creates server runtime handlers for the self-reflection source handler.+ *+ * Use when:+ * - The Agent Signal workflow consumes `agent.self_reflection.requested`+ * - Runtime policy composition needs scoped collection, reviewer, planner, executor, and receipts+ *+ * Expects:+ * - The source was emitted by the self-reflection request service+ * - The handler will re-check gates and idempotency before reviewer work+ *+ * Returns:+ * - Self-reflection handler options ready for `createDefaultAgentSignalPolicies`+ */+export const createServerSelfReflectionPolicyOptions = ({+ agentId,+ db,+ selfIterationEnabled = false,+ userId,+}: CreateServerMaintenancePolicyOptions): CreateSelfReflectionSourceHandlerDependencies => {+ const planner = createMaintenancePlannerService();+ const reviewContextModel = new AgentSignalReviewContextModel(db, userId);+ const skillDocumentService = new SkillManagementDocumentService(db, userId);+ const executor = createServerMaintenanceExecutor({+ agentId,+ db,+ skillDocumentService,+ userId,+ });++ return {+ acquireReviewGuard: (input) =>+ redisSourceEventStore.tryDedupe(+ `self-reflection-guard:${input.guardKey}`,+ AGENT_SIGNAL_DEFAULTS.receiptTtlSeconds,+ ),+ canRunReview: async (input) => {+ if (input.userId !== userId) return false;++ return canRunMaintenanceReview({+ agentId: input.agentId,+ expectedAgentId: agentId,+ reviewContextModel,+ selfIterationEnabled,+ });+ },+ collectContext: (input) => collectSelfReflectionContext(reviewContextModel, input),+ executePlan: (plan) => executor.execute(plan),+ planReviewOutput: (request) => planner.plan(request),+ runMaintenanceReviewAgent: (context) => runServerMaintenanceReviewAgent(db, userId, context),+ writeReceipt: async () => {},+ writeReceipts: (receipts) => persistAgentSignalReceipts(receipts),+ };+};++/**+ * Creates server runtime handlers for the agent-declared self-iteration intent source handler.+ *+ * Use when:+ * - The Agent Signal workflow consumes `agent.self_iteration_intent.declared`+ * - Runtime policy composition needs declared intents to pass through deterministic planning+ *+ * Expects:+ * - The source was emitted by `declareSelfIterationIntent`+ * - The handler will re-check gates and idempotency before execution+ *+ * Returns:+ * - Self-iteration intent handler options ready for `createDefaultAgentSignalPolicies`+ */+export const createServerSelfIterationIntentPolicyOptions = ({+ agentId,+ db,+ selfIterationEnabled = false,+ userId,+}: CreateServerMaintenancePolicyOptions): CreateSelfIterationIntentSourceHandlerDependencies => {+ const planner = createMaintenancePlannerService();+ const reviewContextModel = new AgentSignalReviewContextModel(db, userId);+ const skillDocumentService = new SkillManagementDocumentService(db, userId);+ const executor = createServerMaintenanceExecutor({+ agentId,+ db,+ skillDocumentService,+ userId,+ });++ return {+ acquireReviewGuard: (input) =>+ redisSourceEventStore.tryDedupe(+ `self-iteration-intent-guard:${input.guardKey}`,+ AGENT_SIGNAL_DEFAULTS.receiptTtlSeconds,+ ),+ canRunReview: async (input) => {+ if (input.userId !== userId) return false;++ return canRunMaintenanceReview({+ agentId: input.agentId,+ expectedAgentId: agentId,+ reviewContextModel,+ selfIterationEnabled,+ });+ },+ enrichEvidence: async (input) => ({+ evidenceRefs: [+ {+ id: input.scopeId,+ type: input.scopeType,+ },+ ],+ }),+ executePlan: (plan) => executor.execute(plan),+ planReviewOutput: (request) => planner.plan(request),+ writeReceipt: async () => {},+ writeReceipts: (receipts) => persistAgentSignalReceipts(receipts),+ };+};++/**+ * Creates server procedure policy options with fast-loop self-reflection enabled.+ *+ * Use when:+ * - Workflow-owned Agent Signal runtimes process tool outcome sources+ * - Repeated tool failures should enqueue scoped self-reflection request sources+ *+ * Expects:+ * - The same Redis policy-state store is shared with procedure records and accumulators+ * - Feature gates are re-checked before the request source is enqueued+ *+ * Returns:+ * - Procedure policy options ready for `createAnalyzeIntentPolicy`+ */+export const createServerProcedurePolicyOptions = ({+ agentId,+ db,+ selfIterationEnabled = false,+ userId,+}: CreateServerMaintenancePolicyOptions) => {+ const reviewContextModel = new AgentSignalReviewContextModel(db, userId);++ return createProcedurePolicyOptions({+ policyStateStore: redisPolicyStateStore,+ selfReflection: {+ accumulator: createDurableSelfReflectionAccumulator({+ policyStateStore: redisPolicyStateStore,+ ttlSeconds: 7 * 24 * 60 * 60,+ }),+ getWindowStart: ({ decision, source }) =>+ decision.windowStart ?? new Date(source.timestamp).toISOString(),+ service: createSelfReflectionService({+ canRequestSelfReflection: async (input) => {+ if (input.userId !== userId) return false;++ return canRunMaintenanceReview({+ agentId: input.agentId,+ expectedAgentId: agentId,+ reviewContextModel,+ selfIterationEnabled,+ });+ },+ enqueueSource: async (event) => {+ const { enqueueAgentSignalSourceEvent } =+ await import('@/server/services/agentSignal/emitter');++ return enqueueAgentSignalSourceEvent(event, {+ agentId,+ userId,+ });+ },+ }),+ },+ ttlSeconds: 7 * 24 * 60 * 60,+ });+};++/**+ * Creates server runtime handlers for the nightly review source handler.+ *+ * Use when:+ * - The Agent Signal workflow consumes `agent.nightly_review.requested`+ * - Runtime policy composition needs collection, review, planning, execution, receipts, and brief writing+ *+ * Expects:+ * - The scheduler has already emitted a stable nightly source id+ * - The handler will re-check feature gates and idempotency before reviewer work+ *+ * Returns:+ * - Nightly review handler options ready for `createDefaultAgentSignalPolicies`+ */+export const createServerNightlyReviewPolicyOptions = ({+ agentId,+ db,+ selfIterationEnabled = false,+ userId,+}: CreateServerMaintenancePolicyOptions): CreateNightlyReviewSourceHandlerDependencies => {+ const planner = createMaintenancePlannerService();+ const nightlyReviewModel = new AgentSignalNightlyReviewModel(db);+ const reviewContextModel = new AgentSignalReviewContextModel(db, userId);+ const skillDocumentService = new SkillManagementDocumentService(db, userId);+ const collector = createNightlyReviewService({+ listManagedSkills: async ({ agentId: targetAgentId, limit = 20 }) => {+ const skills = await skillDocumentService.listSkills({ agentId: targetAgentId });++ return skills.slice(0, limit).map<NightlyReviewManagedSkillSummary>((skill) => ({+ description: skill.description,+ documentId: skill.bundle.agentDocumentId,+ name: skill.name,+ readonly: false,+ }));+ },+ listRelevantMemories: async ({ limit = 20 }) => {+ const rows = await reviewContextModel.listRelevantMemories({ limit });++ return rows.map<NightlyReviewRelevantMemorySummary>((row) => ({+ content: row.content,+ id: row.id,+ updatedAt: row.updatedAt.toISOString(),+ }));+ },+ listTopicActivity: async ({+ agentId: targetAgentId,+ limit = 90,+ reviewWindowEnd,+ reviewWindowStart,+ }) => {+ const rows = await reviewContextModel.listTopicActivity({+ agentId: targetAgentId,+ limit,+ windowEnd: new Date(reviewWindowEnd),+ windowStart: new Date(reviewWindowStart),+ });++ return rows.map<NightlyReviewTopicActivityRow>((row) => ({+ evidenceRefs: row.topicId ? [{ id: row.topicId, type: 'topic' }] : [],+ failedToolCount: row.failedToolCount,+ failureCount: row.failureCount,+ lastActivityAt: row.lastActivityAt.toISOString(),+ messageCount: row.messageCount,+ summary: row.summary,+ title: row.title ?? undefined,+ topicId: row.topicId ?? undefined,+ }));+ },+ });+ const executor = createServerMaintenanceExecutor({+ agentId,+ db,+ skillDocumentService,+ userId,+ });++ return {+ acquireReviewGuard: (input) =>+ redisSourceEventStore.tryDedupe(+ `nightly-review-guard:${input.guardKey}`,+ AGENT_SIGNAL_DEFAULTS.receiptTtlSeconds,+ ),+ canRunReview: async (input) => {+ if (!selfIterationEnabled) return false;+ if (input.userId !== userId) return false;+ if (agentId && input.agentId !== agentId) return false;+ if (!(await isAgentSignalEnabledForUser(db, userId))) return false;+ if (!(await reviewContextModel.canAgentRunSelfIteration(input.agentId))) return false;++ const targets = await nightlyReviewModel.listActiveAgentTargets(userId, {+ agentId: input.agentId,+ limit: 1,+ windowEnd: new Date(input.reviewWindowEnd),+ windowStart: new Date(input.reviewWindowStart),+ });++ return targets.length > 0;+ },+ collectContext: (input) => collector.collectNightlyReviewContext(input),+ executePlan: (plan) => executor.execute(plan),+ planReviewOutput: (request) => planner.plan(request),+ runMaintenanceReviewAgent: (context) => runServerMaintenanceReviewAgent(db, userId, context),+ writeReceipts: (receipts) => persistAgentSignalReceipts(receipts),+ };+};diff --git a/src/server/services/agentSignal/services/maintenance/skill.ts b/src/server/services/agentSignal/services/maintenance/skill.tsnew file mode 100644index 00000000000..b7f14b77b8a--- /dev/null+++ b/src/server/services/agentSignal/services/maintenance/skill.ts@@ -0,0 +1,151 @@+import type { EvidenceRef } from './types';++/** Shared fields for skill maintenance domain requests. */+export interface SkillMaintenanceBaseInput {+ /** Whether the resolved target is immutable because it is builtin, marketplace, or otherwise protected. */+ targetReadonly?: boolean;+ /** User that owns the writable managed skill. */+ userId: string;+}++/** Input for creating a managed skill. */+export interface CreateMaintenanceSkillInput extends SkillMaintenanceBaseInput {+ /** Skill body or authoring payload. */+ bodyMarkdown?: string;+ /** Optional description. */+ description?: string;+ /** Stable skill name. */+ name?: string;+ /** Optional title. */+ title?: string;+}++/** Input for refining an existing managed skill. */+export interface RefineMaintenanceSkillInput extends SkillMaintenanceBaseInput {+ /** Patch, replacement body, or maintainer payload. */+ patch?: string;+ /** Writable managed skill agent document id. */+ skillDocumentId: string;+}++/** Input for consolidating managed skills into a canonical skill. */+export interface ConsolidateMaintenanceSkillInput extends SkillMaintenanceBaseInput {+ /** Approval context that allows a consolidation mutation. */+ approval?: {+ /** Source of the approval decision. */+ source: 'proposal' | 'same_turn_feedback';+ };+ /** Canonical writable managed skill agent document id. */+ canonicalSkillDocumentId: string;+ /** Source managed skill ids used to build the canonical skill. */+ sourceSkillIds: string[];+}++/** Request envelope for creating one skill. */+export interface SkillMaintenanceCreateRequest {+ /** Evidence supporting the skill creation. */+ evidenceRefs: EvidenceRef[];+ /** Stable action idempotency key. */+ idempotencyKey: string;+ /** Domain payload. */+ input: CreateMaintenanceSkillInput;+}++/** Request envelope for refining one skill. */+export interface SkillMaintenanceRefineRequest {+ /** Evidence supporting the refinement. */+ evidenceRefs: EvidenceRef[];+ /** Stable action idempotency key. */+ idempotencyKey: string;+ /** Domain payload. */+ input: RefineMaintenanceSkillInput;+}++/** Request envelope for consolidating managed skills. */+export interface SkillMaintenanceConsolidateRequest {+ /** Evidence supporting the consolidation. */+ evidenceRefs: EvidenceRef[];+ /** Stable action idempotency key. */+ idempotencyKey: string;+ /** Domain payload. */+ input: ConsolidateMaintenanceSkillInput;+}++/** Result returned by skill maintenance adapters. */+export interface SkillMaintenanceResult {+ /** Affected writable managed skill document id. */+ skillDocumentId: string;+ /** Optional short persistence summary. */+ summary?: string;+}++/** Persistence adapters for managed skill maintenance operations. */+export interface SkillMaintenanceAdapters {+ /** Consolidates managed skills through the existing skill stack. */+ consolidateSkill?: (+ request: SkillMaintenanceConsolidateRequest,+ ) => Promise<SkillMaintenanceResult>;+ /** Creates managed skills through the existing skill stack. */+ createSkill?: (request: SkillMaintenanceCreateRequest) => Promise<SkillMaintenanceResult>;+ /** Refines managed skills through the existing skill stack. */+ refineSkill?: (request: SkillMaintenanceRefineRequest) => Promise<SkillMaintenanceResult>;+}++const assertWritableSkill = (targetReadonly: boolean | undefined) => {+ if (targetReadonly) {+ throw new Error('Skill target is readonly');+ }+};++const assertApprovedConsolidation = (input: ConsolidateMaintenanceSkillInput) => {+ if (!input.approval) {+ throw new Error('Skill consolidation requires proposal or explicit same-turn approval');+ }+};++/**+ * Creates a skill management maintenance service.+ *+ * Use when:+ * - Maintenance executor needs one skill domain validation boundary+ * - Same-turn skill actions need to share target immutability and consolidation guards+ *+ * Expects:+ * - Builtin and marketplace skills are marked `targetReadonly` before mutation+ * - Server callers inject adapters backed by the existing managed-skill stack+ *+ * Returns:+ * - A service that validates skill targets before delegating persistence+ */+export const createSkillManagementService = (adapters: SkillMaintenanceAdapters = {}) => ({+ consolidateSkill: async (+ request: SkillMaintenanceConsolidateRequest,+ ): Promise<SkillMaintenanceResult> => {+ assertWritableSkill(request.input.targetReadonly);+ assertApprovedConsolidation(request.input);++ if (!adapters.consolidateSkill) {+ throw new Error('Skill consolidate adapter is required');+ }++ return adapters.consolidateSkill(request);+ },+ createSkill: async (request: SkillMaintenanceCreateRequest): Promise<SkillMaintenanceResult> => {+ assertWritableSkill(request.input.targetReadonly);++ if (!adapters.createSkill) {+ throw new Error('Skill create adapter is required');+ }++ return adapters.createSkill(request);+ },+ refineSkill: async (request: SkillMaintenanceRefineRequest): Promise<SkillMaintenanceResult> => {+ assertWritableSkill(request.input.targetReadonly);++ if (!adapters.refineSkill) {+ throw new Error('Skill refine adapter is required');+ }++ return adapters.refineSkill(request);+ },+});diff --git a/src/server/services/agentSignal/services/maintenance/types.ts b/src/server/services/agentSignal/services/maintenance/types.tsnew file mode 100644index 00000000000..40968422a08--- /dev/null+++ b/src/server/services/agentSignal/services/maintenance/types.ts@@ -0,0 +1,276 @@+import type { WriteMaintenanceMemoryInput } from './memory';+import type {+ ConsolidateMaintenanceSkillInput,+ CreateMaintenanceSkillInput,+ RefineMaintenanceSkillInput,+} from './skill';++export enum MaintenanceReviewScope {+ Nightly = 'nightly',+ SelfIterationIntent = 'self_iteration_intent',+ SelfReflection = 'self_reflection',+}++export enum ReviewRunStatus {+ Collected = 'collected',+ Completed = 'completed',+ Deduped = 'deduped',+ Failed = 'failed',+ PartiallyApplied = 'partially_applied',+ Planned = 'planned',+ Skipped = 'skipped',+}++export type MaintenanceActionType =+ | 'write_memory'+ | 'create_skill'+ | 'refine_skill'+ | 'consolidate_skill'+ | 'noop'+ | 'proposal_only';++export enum MaintenanceApplyMode {+ AutoApply = 'auto_apply',+ ProposalOnly = 'proposal_only',+ Skip = 'skip',+}++export enum MaintenanceRisk {+ High = 'high',+ Low = 'low',+ Medium = 'medium',+}++export enum MaintenanceActionStatus {+ Applied = 'applied',+ Deduped = 'deduped',+ Failed = 'failed',+ Proposed = 'proposed',+ Skipped = 'skipped',+}++export interface EvidenceRef {+ id: string;+ summary?: string;+ type:+ | 'topic'+ | 'message'+ | 'operation'+ | 'source'+ | 'receipt'+ | 'tool_call'+ | 'task'+ | 'agent_document'+ | 'memory';+}++export interface MaintenanceDomainOperationCase<TDomain, TOperation, TInput> {+ domain: TDomain;+ input: TInput;+ operation: TOperation;+}++export type MaintenanceMemoryWriteOperation = MaintenanceDomainOperationCase<+ 'memory',+ 'write',+ WriteMaintenanceMemoryInput+>;++export type MaintenanceSkillCreateOperation = MaintenanceDomainOperationCase<+ 'skill',+ 'create',+ CreateMaintenanceSkillInput+>;++export type MaintenanceSkillRefineOperation = MaintenanceDomainOperationCase<+ 'skill',+ 'refine',+ RefineMaintenanceSkillInput+>;++export type MaintenanceSkillConsolidateOperation = MaintenanceDomainOperationCase<+ 'skill',+ 'consolidate',+ ConsolidateMaintenanceSkillInput+>;++export type MaintenanceDomainOperation =+ | MaintenanceMemoryWriteOperation+ | MaintenanceSkillConsolidateOperation+ | MaintenanceSkillCreateOperation+ | MaintenanceSkillRefineOperation;++export interface MaintenanceActionTarget {+ memoryId?: string;+ skillDocumentId?: string;+ skillName?: string;+ targetReadonly?: boolean;+ taskIds?: string[];+ topicIds?: string[];+}++export interface MaintenanceReviewFinding {+ evidenceRefs: EvidenceRef[];+ severity: 'high' | 'low' | 'medium';+ summary: string;+}++export interface MaintenanceActionPolicyHints {+ evidenceStrength?: 'medium' | 'strong' | 'weak';+ mutationScope?: 'broad' | 'small';+ persistence?: 'stable' | 'temporal';+ sensitivity?: 'normal' | 'sensitive';+ userExplicitness?: 'explicit' | 'implicit' | 'inferred';+}++export interface MaintenanceActionDraft<TValue = unknown> {+ actionType: MaintenanceActionType;+ confidence: number;+ evidenceRefs: EvidenceRef[];+ policyHints?: MaintenanceActionPolicyHints;+ rationale: string;+ target?: MaintenanceActionTarget;+ value?: TValue;+}++export interface MaintenancePlanDraft {+ actions: MaintenanceActionDraft[];+ findings: MaintenanceReviewFinding[];+ summary: string;+}++export interface MaintenancePlanRequest {+ draft: MaintenancePlanDraft;+ localDate?: string;+ reviewScope: MaintenanceReviewScope;+ sourceId: string;+ userId: string;+}++export interface MaintenanceActionPlan {+ actionType: MaintenanceActionType;+ applyMode: MaintenanceApplyMode;+ confidence: number;+ dedupeKey: string;+ evidenceRefs: EvidenceRef[];+ idempotencyKey: string;+ operation?: MaintenanceDomainOperation;+ rationale: string;+ risk: MaintenanceRisk;+ sourceActionId?: string;+ target?: MaintenanceActionTarget;+}++export interface MaintenancePlan {+ actions: MaintenanceActionPlan[];+ localDate?: string;+ plannerVersion: string;+ reviewScope: MaintenanceReviewScope;+ summary: string;+}++export interface MaintenanceActionResult {+ idempotencyKey: string;+ receiptId?: string;+ resourceId?: string;+ status: MaintenanceActionStatus;+ summary?: string;+}++export interface MaintenanceReviewRunResult {+ actions: MaintenanceActionResult[];+ briefId?: string;+ sourceId?: string;+ status: ReviewRunStatus;+ summaryReceiptId?: string;+}++export interface NightlyReviewSourceIdInput {+ agentId: string;+ localDate: string;+ userId: string;+}++export interface SelfReflectionSourceIdInput {+ agentId: string;+ reason: string;+ scopeId: string;+ scopeType: 'topic' | 'task' | 'operation';+ userId: string;+ windowEnd: string;+ windowStart: string;+}++export interface SelfIterationIntentSourceIdInput {+ agentId: string;+ scopeId: string;+ scopeType: 'operation' | 'topic';+ toolCallId: string;+ userId: string;+}++export interface MaintenanceActionIdempotencyInput {+ actionType: MaintenanceActionType;+ dedupeKey: string;+ sourceId: string;+}++/**+ * Builds the stable source id for one user-agent local nightly review.+ *+ * Before:+ * - `{ userId: "u", agentId: "a", localDate: "2026-05-04" }`+ *+ * After:+ * - `"nightly-review:u:a:2026-05-04"`+ */+export const buildNightlyReviewSourceId = (input: NightlyReviewSourceIdInput) =>+ `nightly-review:${input.userId}:${input.agentId}:${input.localDate}`;++/**+ * Builds the stable source id for one self-reflection trigger window.+ *+ * Before:+ * - `{ userId: "u", agentId: "a", scopeType: "task", scopeId: "t", reason: "failed", windowStart: "start", windowEnd: "end" }`+ *+ * After:+ * - `"self-reflection:u:a:task:t:failed:start:end"`+ */+export const buildSelfReflectionSourceId = (input: SelfReflectionSourceIdInput) =>+ [+ 'self-reflection',+ input.userId,+ input.agentId,+ input.scopeType,+ input.scopeId,+ input.reason,+ input.windowStart,+ input.windowEnd,+ ].join(':');++/**+ * Builds the stable source id for one runtime-declared maintenance intent.+ *+ * Before:+ * - `{ userId: "u", agentId: "a", scopeType: "topic", scopeId: "topic", toolCallId: "call" }`+ *+ * After:+ * - `"self-iteration-intent:u:a:topic:topic:call"`+ */+export const buildSelfIterationIntentSourceId = (input: SelfIterationIntentSourceIdInput) =>+ `self-iteration-intent:${input.userId}:${input.agentId}:${input.scopeType}:${input.scopeId}:${input.toolCallId}`;++/**+ * Builds a replay guard key for one planned maintenance action.+ *+ * Before:+ * - `{ sourceId: "source", actionType: "write_memory", dedupeKey: "memory:abc" }`+ *+ * After:+ * - `"source:write_memory:memory:abc"`+ */+export const buildMaintenanceActionIdempotencyKey = (input: MaintenanceActionIdempotencyInput) =>+ `${input.sourceId}:${input.actionType}:${input.dedupeKey}`;++export const isActionExecutable = (applyMode: MaintenanceApplyMode) =>+ applyMode === MaintenanceApplyMode.AutoApply;diff --git a/src/server/services/agentSignal/services/procedureStateService.ts b/src/server/services/agentSignal/services/procedureStateService.tsindex 137ac6a27d0..b7c352a2505 100644--- a/src/server/services/agentSignal/services/procedureStateService.ts+++ b/src/server/services/agentSignal/services/procedureStateService.ts@@ -1,7 +1,7 @@import {appendAndScoreProcedureAccumulatorRecord,appendProcedureAccumulatorRecord,-} from '../procedure/accumulator';+} from '../procedure/accumulators/procedure';import { AgentSignalProcedureInspector } from '../procedure/inspector';import { createProcedureMarkerKeysForRead } from '../procedure/keys';import {diff --git a/src/server/services/agentSignal/services/receiptService.ts b/src/server/services/agentSignal/services/receiptService.tsindex 302ec02202d..dc3cd13490d 100644--- a/src/server/services/agentSignal/services/receiptService.ts+++ b/src/server/services/agentSignal/services/receiptService.ts@@ -3,6 +3,43 @@ import type { AgentSignalSource, BaseAction, ExecutorResult } from '@lobechat/agimport { AGENT_SIGNAL_DEFAULTS } from '../constants';import { AGENT_SIGNAL_POLICY_ACTION_TYPES } from '../policies/types';import { redisReceiptStore } from '../store/adapters/redis/receiptStore';+import type {+ EvidenceRef,+ MaintenanceActionPlan,+ MaintenanceActionResult,+ MaintenanceActionType,+ MaintenancePlan,+ MaintenanceReviewRunResult,+} from './maintenance/types';+import {+ MaintenanceActionStatus,+ MaintenanceReviewScope,+ ReviewRunStatus,+} from './maintenance/types';++/** Metadata envelope used by maintenance receipts. */+export interface AgentSignalReceiptMetadata {+ /** Number of action results summarized by a review receipt. */+ actionCount?: number;+ /** Maintenance action status for action receipts. */+ actionStatus?: MaintenanceActionStatus;+ /** Maintenance action type for action receipts. */+ actionType?: MaintenanceActionType;+ /** Evidence refs used by the reviewer/planner. */+ evidenceRefs?: EvidenceRef[];+ /** User-local date for nightly receipts. */+ localDate?: string;+ /** Maintenance review scope that produced the receipt. */+ reviewScope?: MaintenanceReviewScope;+ /** Scoped self-reflection id for non-nightly review receipts. */+ scopeId?: string;+ /** Scoped self-reflection namespace for non-nightly review receipts. */+ scopeType?: string;+ /** Source type that produced the receipt. */+ sourceType?: string;+ /** IANA timezone used for nightly receipt projection. */+ timezone?: string;+}/*** User-visible Agent Signal receipt persisted for recent topic activity.@@ -19,7 +56,9 @@ export interface AgentSignalReceipt {/** Stable receipt id used as Redis member and payload key suffix. */id: string;/** User-facing durable outcome domain. */- kind: 'memory' | 'skill';+ kind: 'maintenance' | 'memory' | 'review' | 'skill';+ /** Structured metadata for audit, brief linking, and eval assertions. */+ metadata?: AgentSignalReceiptMetadata;/** Agent runtime operation that produced the receipt, when known. */operationId?: string;/** Source event id that triggered the receipt. */@@ -27,7 +66,7 @@ export interface AgentSignalReceipt {/** Source event type that triggered the receipt. */sourceType: string;/** User-facing terminal status. */- status: 'applied' | 'updated';+ status: 'applied' | 'completed' | 'failed' | 'proposed' | 'skipped' | 'updated';/** Snapshot of the resource affected when the receipt was produced. */target?: {/** Backing resource id for future navigation when still available. Skill ids use `documents.id`. */@@ -86,6 +125,73 @@ interface PersistAgentSignalReceiptsOptions {store?: AgentSignalReceiptStore;}+/** Input used to create one maintenance review summary receipt. */+export interface CreateReviewSummaryReceiptInput {+ /** Agent that owns the reviewed scope. */+ agentId: string;+ /** Millisecond timestamp for receipt ordering. */+ createdAt?: number;+ /** User-local date for nightly reviews. */+ localDate?: string;+ /** Normalized maintenance plan that was executed. */+ plan: MaintenancePlan;+ /** Aggregated executor result for the review. */+ result: MaintenanceReviewRunResult;+ /** Scoped review id for self-reflection and intent runs. */+ scopeId?: string;+ /** Scoped review namespace for self-reflection and intent runs. */+ scopeType?: string;+ /** Source id that triggered the review. */+ sourceId: string;+ /** Source type that triggered the review. */+ sourceType: string;+ /** IANA timezone for nightly reviews. */+ timezone?: string;+ /** Topic index id for topic-local receipts. Falls back to source id for day-level receipts. */+ topicId?: string;+ /** User that owns the reviewed agent. */+ userId: string;+}++/** Input used to create one maintenance action receipt. */+export interface CreateMaintenanceActionReceiptInput {+ /** Planner-normalized action. */+ action: MaintenanceActionPlan;+ /** Agent that owns the reviewed scope. */+ agentId: string;+ /** Millisecond timestamp for receipt ordering. */+ createdAt?: number;+ /** User-local date for nightly reviews. */+ localDate?: string;+ /** Executor result for the action. */+ result: MaintenanceActionResult;+ /** Review scope that produced this action. */+ reviewScope: MaintenanceReviewScope;+ /** Scoped review id for self-reflection and intent runs. */+ scopeId?: string;+ /** Scoped review namespace for self-reflection and intent runs. */+ scopeType?: string;+ /** Source id that triggered the review. */+ sourceId: string;+ /** Source type that triggered the review. */+ sourceType: string;+ /** IANA timezone for nightly reviews. */+ timezone?: string;+ /** Topic index id for topic-local receipts. Falls back to source id for day-level receipts. */+ topicId?: string;+ /** User that owns the reviewed agent. */+ userId: string;+}++/** Input used to create all receipts for one maintenance review run. */+export interface CreateMaintenanceReviewReceiptsInput extends Omit<+ CreateReviewSummaryReceiptInput,+ 'plan'+> {+ /** Normalized maintenance plan that was executed. */+ plan: MaintenancePlan;+}+const getPayloadString = (payload: Record<string, unknown>, key: string) => {const value = payload[key];@@ -105,7 +211,12 @@ const getReceiptTarget = (if (target && typeof target === 'object') {const payload = target as Record<string, unknown>;const title = typeof payload.title === 'string' ? payload.title.trim() : undefined;- const type = payload.type === 'memory' || payload.type === 'skill' ? payload.type : kind;+ const type =+ payload.type === 'memory' || payload.type === 'skill'+ ? payload.type+ : kind === 'skill'+ ? 'skill'+ : 'memory';if (title) {return {@@ -154,6 +265,174 @@ const toReceiptKind = (return;};+const getMaintenanceTopicId = (input: { sourceId: string; topicId?: string }) =>+ input.topicId ?? input.sourceId;++const getActionReceiptKind = (action: MaintenanceActionPlan): AgentSignalReceipt['kind'] =>+ action.operation?.domain ?? 'maintenance';++const getActionReceiptStatus = (+ status: MaintenanceActionStatus,+): AgentSignalReceipt['status'] | undefined => {+ if (status === MaintenanceActionStatus.Applied) return 'applied';+ if (status === MaintenanceActionStatus.Proposed) return 'proposed';++ return;+};++const getActionReceiptTitle = (action: MaintenanceActionPlan, result: MaintenanceActionResult) => {+ if (result.summary) return getClampedString(result.summary);+ if (action.actionType === 'write_memory') return 'Memory maintenance action';+ if (action.actionType === 'create_skill') return 'Skill creation proposal';+ if (action.actionType === 'refine_skill') return 'Skill refinement proposal';+ if (action.actionType === 'consolidate_skill') return 'Skill consolidation proposal';++ return 'Maintenance action';+};++/**+ * Creates one source-level receipt summarizing a maintenance review run.+ *+ * Use when:+ * - Nightly or scoped self-reflection handlers finish a maintenance review+ * - Receipts need one audit anchor before action-level receipts are linked to briefs+ *+ * Expects:+ * - `plan.reviewScope` is the authoritative review scope+ * - Topic-scoped reviews pass `topicId`; day-level reviews can omit it+ *+ * Returns:+ * - One stable summary receipt indexed by topic id or source id+ */+export const createReviewSummaryReceipt = (+ input: CreateReviewSummaryReceiptInput,+): AgentSignalReceipt => ({+ agentId: input.agentId,+ createdAt: input.createdAt ?? Date.now(),+ detail: input.plan.summary,+ id: `${input.sourceId}:review-summary`,+ kind: 'review',+ metadata: {+ actionCount: input.result.actions.length,+ evidenceRefs: input.plan.actions.flatMap((action) => action.evidenceRefs),+ ...(input.localDate ? { localDate: input.localDate } : {}),+ reviewScope: input.plan.reviewScope,+ ...(input.scopeId ? { scopeId: input.scopeId } : {}),+ ...(input.scopeType ? { scopeType: input.scopeType } : {}),+ sourceType: input.sourceType,+ ...(input.timezone ? { timezone: input.timezone } : {}),+ },+ sourceId: input.sourceId,+ sourceType: input.sourceType,+ status: input.result.status === ReviewRunStatus.Failed ? 'failed' : 'completed',+ title:+ input.plan.reviewScope === MaintenanceReviewScope.Nightly+ ? 'Nightly self-review completed'+ : 'Self-review completed',+ topicId: getMaintenanceTopicId(input),+ userId: input.userId,+});++/**+ * Creates one action-level maintenance receipt for applied or proposed actions.+ *+ * Use when:+ * - A maintenance action mutated a resource or produced a user-visible proposal+ * - Brief metadata needs durable receipt ids linked to individual outcomes+ *+ * Expects:+ * - The action/result pair share the same idempotency key+ * - Skipped, deduped, and failed actions are represented by the summary receipt only+ *+ * Returns:+ * - A stable action receipt, or `undefined` when no user-visible action receipt is needed+ */+export const createMaintenanceActionReceipt = (+ input: CreateMaintenanceActionReceiptInput,+): AgentSignalReceipt | undefined => {+ if (input.action.actionType === 'noop') return;++ const status = getActionReceiptStatus(input.result.status);+ if (!status) return;++ const kind = getActionReceiptKind(input.action);+ const title = getActionReceiptTitle(input.action, input.result);++ return {+ agentId: input.agentId,+ createdAt: input.createdAt ?? Date.now(),+ detail: input.action.rationale,+ id: `${input.action.idempotencyKey}:action`,+ kind,+ metadata: {+ actionStatus: input.result.status,+ actionType: input.action.actionType,+ evidenceRefs: input.action.evidenceRefs,+ ...(input.localDate ? { localDate: input.localDate } : {}),+ reviewScope: input.reviewScope,+ ...(input.scopeId ? { scopeId: input.scopeId } : {}),+ ...(input.scopeType ? { scopeType: input.scopeType } : {}),+ sourceType: input.sourceType,+ ...(input.timezone ? { timezone: input.timezone } : {}),+ },+ sourceId: input.sourceId,+ sourceType: input.sourceType,+ status,+ target: {+ ...(input.result.resourceId ? { id: input.result.resourceId } : {}),+ ...(input.result.summary ? { summary: input.result.summary } : {}),+ title,+ type: kind === 'skill' ? 'skill' : 'memory',+ },+ title,+ topicId: getMaintenanceTopicId(input),+ userId: input.userId,+ };+};++/**+ * Projects one review summary receipt plus applied/proposed action receipts.+ *+ * Use when:+ * - Source handlers need receipts before Daily Brief creation+ * - Tests need a single deterministic projection boundary+ *+ * Expects:+ * - `plan.actions` and `result.actions` share action idempotency keys+ *+ * Returns:+ * - Receipts ordered as summary first, then action results in executor order+ */+export const createMaintenanceReviewReceipts = (+ input: CreateMaintenanceReviewReceiptsInput,+): AgentSignalReceipt[] => {+ const actionByKey = new Map(input.plan.actions.map((action) => [action.idempotencyKey, action]));+ const actionReceipts = input.result.actions.flatMap((result) => {+ const action = actionByKey.get(result.idempotencyKey);+ if (!action) return [];++ const receipt = createMaintenanceActionReceipt({+ action,+ agentId: input.agentId,+ createdAt: input.createdAt,+ ...(input.localDate ? { localDate: input.localDate } : {}),+ result,+ reviewScope: input.plan.reviewScope,+ ...(input.scopeId ? { scopeId: input.scopeId } : {}),+ ...(input.scopeType ? { scopeType: input.scopeType } : {}),+ sourceId: input.sourceId,+ sourceType: input.sourceType,+ ...(input.topicId ? { topicId: input.topicId } : {}),+ ...(input.timezone ? { timezone: input.timezone } : {}),+ userId: input.userId,+ });++ return receipt ? [receipt] : [];+ });++ return [createReviewSummaryReceipt(input), ...actionReceipts];+};+/*** Projects terminal Agent Signal runtime results into user-visible receipts.*diff --git a/src/server/services/agentSignal/services/selfIterationIntent.ts b/src/server/services/agentSignal/services/selfIterationIntent.tsnew file mode 100644index 00000000000..ee537a4ead0--- /dev/null+++ b/src/server/services/agentSignal/services/selfIterationIntent.ts@@ -0,0 +1,243 @@+import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';++import type { AgentSignalSourceEventInput } from '@/server/services/agentSignal/emitter';++import type { EvidenceRef } from './maintenance/types';+import { buildSelfIterationIntentSourceId } from './maintenance/types';++type MaybePromise<TValue> = TValue | Promise<TValue>;++/** Actions that an agent may declare as self-iteration maintenance intent. */+export type SelfIterationIntentAction = 'write' | 'create' | 'refine' | 'consolidate' | 'proposal';++/** Maintenance target categories accepted from agent-declared intent. */+export type SelfIterationIntentKind = 'memory' | 'skill' | 'gap';++/** Evidence strength assigned to one accepted or rejected declaration. */+export type SelfIterationIntentStrength = 'strong' | 'weak';++/** Source event input emitted by the self-iteration intent declaration service. */+export type SelfIterationIntentSourceEventInput =+ AgentSignalSourceEventInput<'agent.self_iteration_intent.declared'>;++/** Input payload declared by the running agent through the self-iteration intent tool. */+export interface DeclareSelfIterationIntentPayload {+ /** Maintenance action the agent believes may be useful. */+ action: SelfIterationIntentAction;+ /** Agent confidence from 0 to 1. */+ confidence: number;+ /** Evidence references that justify the declaration. */+ evidenceRefs?: EvidenceRef[];+ /** Target category for the declaration. */+ kind: SelfIterationIntentKind;+ /** Existing memory id when the declaration targets a known memory. */+ memoryId?: string;+ /** Human-readable rationale from the agent. */+ reason: string;+ /** Existing skill id when the declaration targets a known skill. */+ skillId?: string;+ /** Short declaration summary for downstream review. */+ summary: string;+}++/** Input used to declare one agent-facing self-iteration intent source event. */+export interface DeclareSelfIterationIntentInput {+ /** Stable agent id associated with the running agent. */+ agentId: string;+ /** Agent-declared maintenance intent payload. */+ input: DeclareSelfIterationIntentPayload;+ /** Runtime operation id when the declaration belongs to a narrower operation scope. */+ operationId?: string;+ /** Caller-provided tool-call id. When omitted, the injected id generator is used. */+ toolCallId?: string;+ /** Current topic id for stable source ids and topic fallback scope. */+ topicId: string;+ /** Stable user id associated with the running agent. */+ userId: string;+}++/** Result returned after one declaration attempt. */+export interface DeclareSelfIterationIntentResult {+ /** Whether the declaration was accepted and emitted to the enqueue boundary. */+ accepted: boolean;+ /** Optional rejection reason when no source was enqueued. */+ reason?:+ | 'enqueue_gate_rejected'+ | 'intent_gate_rejected'+ | 'invalid_action'+ | 'invalid_confidence'+ | 'invalid_kind'+ | 'rate_limited';+ /** Stable source id built for accepted declarations when available. */+ sourceId?: string;+ /** Evidence strength assigned from confidence and evidence presence. */+ strength: SelfIterationIntentStrength;+}++/** Dependencies used by the pure self-iteration intent declaration service. */+export interface SelfIterationIntentServiceDependencies {+ /**+ * Optional declaration-level gate checked before source event construction crosses enqueue+ * boundaries.+ *+ * @default Allows declarations.+ */+ canDeclareIntent?: (input: DeclareSelfIterationIntentInput) => MaybePromise<boolean>;+ /**+ * Optional final gate for a fully built source event.+ *+ * @default Allows enqueueing.+ */+ canEnqueue?: (input: SelfIterationIntentSourceEventInput) => MaybePromise<boolean>;+ /** Enqueues one self-iteration intent source event. */+ enqueueSource: (input: SelfIterationIntentSourceEventInput) => Promise<unknown>;+ /** Creates a stable tool-call id when the caller did not provide one. */+ nextToolCallId: () => string;+}++/** Self-iteration intent source emission service API. */+export interface SelfIterationIntentService {+ /**+ * Emits one agent-declared self-iteration intent source event when validation and gates pass.+ *+ * Use when:+ * - A running chat or task agent wants to declare maintenance intent+ * - Callers need a source-event boundary without direct memory or skill mutation+ *+ * Expects:+ * - `topicId`, `agentId`, and `userId` identify the current running agent scope+ * - Downstream Agent Signal handlers own planning, review, and resource mutation decisions+ *+ * Returns:+ * - Source acceptance status, stable source id when emitted, and evidence strength+ */+ declareIntent: (+ input: DeclareSelfIterationIntentInput,+ ) => Promise<DeclareSelfIterationIntentResult>;+}++const DECLARATION_LIMIT_PER_SCOPE = 3;+const STRONG_CONFIDENCE_THRESHOLD = 0.75;++const validActions = new Set<SelfIterationIntentAction>([+ 'write',+ 'create',+ 'refine',+ 'consolidate',+ 'proposal',+]);+const validKinds = new Set<SelfIterationIntentKind>(['memory', 'skill', 'gap']);++const getStrength = (input: DeclareSelfIterationIntentPayload): SelfIterationIntentStrength => {+ if (!input.evidenceRefs?.length || input.confidence < STRONG_CONFIDENCE_THRESHOLD) {+ return 'weak';+ }++ return 'strong';+};++const getRateLimitScopeKey = (input: DeclareSelfIterationIntentInput) => {+ const scopeKey = input.operationId ? `operation:${input.operationId}` : `topic:${input.topicId}`;++ return `${input.userId}:${input.agentId}:${scopeKey}`;+};++const getIntentScope = (input: DeclareSelfIterationIntentInput) =>+ input.operationId+ ? ({+ scopeId: input.operationId,+ scopeKey: `operation:${input.operationId}`,+ scopeType: 'operation',+ } as const)+ : ({ scopeId: input.topicId, scopeKey: `topic:${input.topicId}`, scopeType: 'topic' } as const);++const isValidConfidence = (confidence: number) =>+ Number.isFinite(confidence) && confidence >= 0 && confidence <= 1;++/**+ * Creates a pure self-iteration intent declaration service.+ *+ * Use when:+ * - Runtime tool handlers need a DI-friendly source emission boundary+ * - Tests need deterministic tool-call ids, gates, and rate-limit state+ *+ * Expects:+ * - `enqueueSource` owns durable dedupe and async execution+ * - The service instance owns only in-memory fast-loop rate limiting+ *+ * Returns:+ * - A service that emits accepted declarations and never mutates memory or skill resources+ */+export const createSelfIterationIntentService = (+ deps: SelfIterationIntentServiceDependencies,+): SelfIterationIntentService => {+ const acceptedCounts = new Map<string, number>();++ return {+ declareIntent: async (input) => {+ if (!validActions.has(input.input.action)) {+ return { accepted: false, reason: 'invalid_action', strength: 'weak' };+ }++ if (!validKinds.has(input.input.kind)) {+ return { accepted: false, reason: 'invalid_kind', strength: 'weak' };+ }++ if (!isValidConfidence(input.input.confidence)) {+ return { accepted: false, reason: 'invalid_confidence', strength: 'weak' };+ }++ const strength = getStrength(input.input);++ if (deps.canDeclareIntent && !(await deps.canDeclareIntent(input))) {+ return { accepted: false, reason: 'intent_gate_rejected', strength };+ }++ const rateLimitScopeKey = getRateLimitScopeKey(input);+ const acceptedCount = acceptedCounts.get(rateLimitScopeKey) ?? 0;++ if (acceptedCount >= DECLARATION_LIMIT_PER_SCOPE) {+ return { accepted: false, reason: 'rate_limited', strength };+ }++ const toolCallId = input.toolCallId ?? deps.nextToolCallId();+ const intentScope = getIntentScope(input);+ const sourceId = buildSelfIterationIntentSourceId({+ agentId: input.agentId,+ scopeId: intentScope.scopeId,+ scopeType: intentScope.scopeType,+ toolCallId,+ userId: input.userId,+ });+ const sourceEvent: SelfIterationIntentSourceEventInput = {+ payload: {+ action: input.input.action,+ agentId: input.agentId,+ confidence: input.input.confidence,+ kind: input.input.kind,+ reason: input.input.reason,+ summary: input.input.summary,+ toolCallId,+ topicId: input.topicId,+ userId: input.userId,+ ...(input.input.evidenceRefs ? { evidenceRefs: input.input.evidenceRefs } : {}),+ ...(input.input.memoryId ? { memoryId: input.input.memoryId } : {}),+ ...(input.operationId ? { operationId: input.operationId } : {}),+ ...(input.input.skillId ? { skillId: input.input.skillId } : {}),+ },+ scopeKey: intentScope.scopeKey,+ sourceId,+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentSelfIterationIntentDeclared,+ };++ if (deps.canEnqueue && !(await deps.canEnqueue(sourceEvent))) {+ return { accepted: false, reason: 'enqueue_gate_rejected', sourceId, strength };+ }++ await deps.enqueueSource(sourceEvent);+ acceptedCounts.set(rateLimitScopeKey, acceptedCount + 1);++ return { accepted: true, sourceId, strength };+ },+ };+};diff --git a/src/server/services/agentSignal/services/selfReflection.ts b/src/server/services/agentSignal/services/selfReflection.tsnew file mode 100644index 00000000000..72ed6cee556--- /dev/null+++ b/src/server/services/agentSignal/services/selfReflection.ts@@ -0,0 +1,148 @@+import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';++import type { AgentSignalSourceEventInput } from '@/server/services/agentSignal/emitter';++import type { SelfReflectionRequestReason } from '../procedure/accumulators/selfReflection';+import { buildSelfReflectionSourceId } from './maintenance/types';++type MaybePromise<TValue> = TValue | Promise<TValue>;++/** Runtime scope supported by self-reflection source requests. */+export type SelfReflectionRequestScopeType = 'operation' | 'task' | 'topic';++/** Source event input emitted by the self-reflection request service. */+export type SelfReflectionSourceEventInput =+ AgentSignalSourceEventInput<'agent.self_reflection.requested'>;++/**+ * Input used to request one self-reflection source event.+ */+export interface RequestSelfReflectionInput {+ /** Stable agent id associated with the weak-signal window. */+ agentId: string;+ /** Runtime operation id when the request is scoped to an operation or references one. */+ operationId?: string;+ /** Threshold or policy reason that triggered reflection. */+ reason: SelfReflectionRequestReason;+ /** Topic, task, or operation id selected by the accumulator. */+ scopeId: string;+ /** Runtime scope family selected by the accumulator. */+ scopeType: SelfReflectionRequestScopeType;+ /** Task id when the request is scoped to or associated with a task. */+ taskId?: string;+ /** Topic id when the request is scoped to or associated with a topic. */+ topicId?: string;+ /** Stable user id associated with the weak-signal window. */+ userId: string;+ /** ISO timestamp for the end of the reflection window. */+ windowEnd: string;+ /** ISO timestamp for the beginning of the reflection window. */+ windowStart: string;+}++/** Result returned after a self-reflection request attempt. */+export interface RequestSelfReflectionResult {+ /** Whether the service called the source enqueue boundary. */+ enqueued: boolean;+ /** Optional skip reason when a gate rejected the request. */+ reason?: 'enqueue_gate_rejected' | 'request_gate_rejected';+ /** Stable source id built for this request when available. */+ sourceId?: string;+}++/** Dependencies used by the pure self-reflection source emission service. */+export interface SelfReflectionServiceDependencies {+ /**+ * Optional final gate for a fully built source event.+ *+ * @default Allows enqueueing.+ */+ canEnqueue?: (input: SelfReflectionSourceEventInput) => MaybePromise<boolean>;+ /**+ * Optional request-level gate checked before source event construction crosses enqueue boundaries.+ *+ * @default Allows requests.+ */+ canRequestSelfReflection?: (input: RequestSelfReflectionInput) => MaybePromise<boolean>;+ /** Enqueues one self-reflection source event. */+ enqueueSource: (input: SelfReflectionSourceEventInput) => Promise<unknown>;+}++/** Self-reflection source emission service API. */+export interface SelfReflectionService {+ /**+ * Emits one self-reflection source request when injected gates allow it.+ *+ * Use when:+ * - A runtime weak-signal accumulator crosses a self-reflection threshold+ * - Callers need source-event emission without DB writes or handler execution+ *+ * Expects:+ * - The input came from a real task, operation, or topic scoped runtime signal+ * - Source dedupe is handled by the Agent Signal enqueue/store path+ *+ * Returns:+ * - Whether the enqueue boundary was called and the stable source id when built+ */+ requestSelfReflection: (+ input: RequestSelfReflectionInput,+ ) => Promise<RequestSelfReflectionResult>;+}++/**+ * Creates a pure self-reflection source emission service.+ *+ * Use when:+ * - Tests need deterministic source ids and queue payloads+ * - Runtime integration wants DI-friendly feature gates and enqueue boundaries+ *+ * Expects:+ * - `enqueueSource` owns durable dedupe and async execution+ * - Optional gates are side-effect-light checks+ *+ * Returns:+ * - A service that calls `enqueueSource` at most once for each allowed request+ */+export const createSelfReflectionService = (+ deps: SelfReflectionServiceDependencies,+): SelfReflectionService => ({+ requestSelfReflection: async (input) => {+ if (deps.canRequestSelfReflection && !(await deps.canRequestSelfReflection(input))) {+ return { enqueued: false, reason: 'request_gate_rejected' };+ }++ const sourceId = buildSelfReflectionSourceId({+ agentId: input.agentId,+ reason: input.reason,+ scopeId: input.scopeId,+ scopeType: input.scopeType,+ userId: input.userId,+ windowEnd: input.windowEnd,+ windowStart: input.windowStart,+ });+ const sourceEvent: SelfReflectionSourceEventInput = {+ payload: {+ agentId: input.agentId,+ reason: input.reason,+ scopeId: input.scopeId,+ scopeType: input.scopeType,+ ...(input.operationId ? { operationId: input.operationId } : {}),+ ...(input.taskId ? { taskId: input.taskId } : {}),+ ...(input.topicId ? { topicId: input.topicId } : {}),+ userId: input.userId,+ windowEnd: input.windowEnd,+ windowStart: input.windowStart,+ },+ sourceId,+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentSelfReflectionRequested,+ };++ if (deps.canEnqueue && !(await deps.canEnqueue(sourceEvent))) {+ return { enqueued: false, reason: 'enqueue_gate_rejected', sourceId };+ }++ await deps.enqueueSource(sourceEvent);++ return { enqueued: true, sourceId };+ },+});diff --git a/src/server/services/agentSignal/services/types.ts b/src/server/services/agentSignal/services/types.tsindex a5376cdb8c2..a48b7f2ac39 100644--- a/src/server/services/agentSignal/services/types.ts+++ b/src/server/services/agentSignal/services/types.ts@@ -1,4 +1,4 @@-import type { ProcedureAccumulatorScoreResult } from '../procedure/accumulator';+import type { ProcedureAccumulatorScoreResult } from '../procedure/accumulators/procedure';import type { AgentSignalProcedureInspectionSnapshot } from '../procedure/inspector';import type { ProcedureMarkerKeyInput } from '../procedure/keys';import type {diff --git a/src/server/services/agentSignal/store/adapters/redis/receiptStore.ts b/src/server/services/agentSignal/store/adapters/redis/receiptStore.tsindex 1d61cb799ba..64edabed0c2 100644--- a/src/server/services/agentSignal/store/adapters/redis/receiptStore.ts+++ b/src/server/services/agentSignal/store/adapters/redis/receiptStore.ts@@ -10,6 +10,7 @@ const toReceiptHash = (receipt: AgentSignalReceipt): Record<string, string> => (detail: receipt.detail,id: receipt.id,kind: receipt.kind,+ ...(receipt.metadata ? { metadata: JSON.stringify(receipt.metadata) } : {}),...(receipt.operationId ? { operationId: receipt.operationId } : {}),sourceId: receipt.sourceId,sourceType: receipt.sourceType,@@ -42,15 +43,46 @@ const parseReceiptTarget = (value?: string): AgentSignalReceipt['target'] | unde}};+const parseReceiptMetadata = (value?: string): AgentSignalReceipt['metadata'] | undefined => {+ if (!value) return;++ try {+ const metadata = JSON.parse(value);++ return metadata && typeof metadata === 'object'+ ? (metadata as AgentSignalReceipt['metadata'])+ : undefined;+ } catch {+ return;+ }+};+const fromReceiptHash = (payload: Record<string, string>): AgentSignalReceipt | undefined => {const createdAt = Number(payload.createdAt);if (!payload.id || !payload.userId || !payload.agentId || !payload.topicId) return;- if (payload.kind !== 'memory' && payload.kind !== 'skill') return;- if (payload.status !== 'applied' && payload.status !== 'updated') return;+ if (+ payload.kind !== 'maintenance' &&+ payload.kind !== 'memory' &&+ payload.kind !== 'review' &&+ payload.kind !== 'skill'+ ) {+ return;+ }+ if (+ payload.status !== 'applied' &&+ payload.status !== 'completed' &&+ payload.status !== 'failed' &&+ payload.status !== 'proposed' &&+ payload.status !== 'skipped' &&+ payload.status !== 'updated'+ ) {+ return;+ }if (!Number.isFinite(createdAt)) return;const target = parseReceiptTarget(payload.target);+ const metadata = parseReceiptMetadata(payload.metadata);return {agentId: payload.agentId,@@ -59,6 +91,7 @@ const fromReceiptHash = (payload: Record<string, string>): AgentSignalReceipt |detail: payload.detail,id: payload.id,kind: payload.kind,+ ...(metadata ? { metadata } : {}),operationId: payload.operationId,sourceId: payload.sourceId,sourceType: payload.sourceType,diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.tsindex 09a763d29d1..a9fdc635ad1 100644--- a/src/server/services/aiAgent/index.ts+++ b/src/server/services/aiAgent/index.ts@@ -5,11 +5,12 @@ import { LobeAgentManifest } from '@lobechat/builtin-tool-lobe-agent';import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';import { MessageToolIdentifier } from '@lobechat/builtin-tool-message';import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';+import type { DeviceAttachment } from '@lobechat/builtin-tool-remote-device';+import { generateSystemPrompt, RemoteDeviceManifest } from '@lobechat/builtin-tool-remote-device';import {- type DeviceAttachment,- generateSystemPrompt,- RemoteDeviceManifest,-} from '@lobechat/builtin-tool-remote-device';+ injectSelfIterationIntentTool,+ shouldExposeSelfIterationIntentTool,+} from '@lobechat/builtin-tool-self-iteration';import { TaskIdentifier } from '@lobechat/builtin-tool-task';import { builtinTools, manualModeExcludeToolIds } from '@lobechat/builtin-tools';import { LOADING_FLAT } from '@lobechat/const';@@ -53,21 +54,19 @@ import { UserPersonaModel } from '@/database/models/userMemory/persona';import { toolsEnv } from '@/envs/tools';import { shouldEnableBuiltinSkill } from '@/helpers/skillFilters';import { signUserJWT } from '@/libs/trpc/utils/internalJwt';-import {- createServerAgentToolsEngine,- type EvalContext,- type ServerAgentToolsContext,-} from '@/server/modules/Mecha';-import { type ServerUserMemoryConfig } from '@/server/modules/Mecha/ContextEngineering/types';+import type { EvalContext, ServerAgentToolsContext } from '@/server/modules/Mecha';+import { createServerAgentToolsEngine } from '@/server/modules/Mecha';+import type { ServerUserMemoryConfig } from '@/server/modules/Mecha/ContextEngineering/types';import { AgentService } from '@/server/services/agent';import { AgentDocumentsService } from '@/server/services/agentDocuments';import type { AgentRuntimeServiceOptions } from '@/server/services/agentRuntime';import { AgentRuntimeService } from '@/server/services/agentRuntime';import { getAbortError, isAbortError, throwIfAborted } from '@/server/services/agentRuntime/abort';import { hookDispatcher } from '@/server/services/agentRuntime/hooks';-import { type AgentHook } from '@/server/services/agentRuntime/hooks/types';-import { type StepLifecycleCallbacks } from '@/server/services/agentRuntime/types';+import type { AgentHook } from '@/server/services/agentRuntime/hooks/types';+import type { StepLifecycleCallbacks } from '@/server/services/agentRuntime/types';import { enqueueAgentSignalSourceEvent } from '@/server/services/agentSignal';+import { isAgentSignalEnabledForUser } from '@/server/services/agentSignal/featureGate';import { DocumentService } from '@/server/services/document';import { FileService } from '@/server/services/file';import { KlavisService } from '@/server/services/klavis';@@ -146,6 +145,8 @@ interface InternalExecAgentParams extends ExecAgentParams {cronJobId?: string;/** Disable only local-system while preserving other tools. Useful for signal-only evals. */disableLocalSystem?: boolean;+ /** Disable the self-iteration declaration tool for reviewer/runtime paths. */+ disableSelfIterationIntentTool?: boolean;/** Disable all tools (no plugins, no system manifests). Useful for eval/benchmark scenarios. */disableTools?: boolean;/** Discord context for injecting channel/guild info into agent system message */@@ -866,7 +867,6 @@ export class AiAgentService {});tools = toolsResult.tools;-log('execAgent: enabled tool ids: %O', toolsResult.enabledToolIds);// Start with the scoped manifest map (pluginIds + defaultToolIds)@@ -950,6 +950,27 @@ export class AiAgentService {lobehubSkillManifests.length,klavisManifests.length,);++ const agentSelfIterationEnabled = agentConfig.chatConfig?.selfIteration?.enabled === true;+ const shouldCheckUserSelfIterationGate =+ agentSelfIterationEnabled && !params.disableSelfIterationIntentTool;+ if (+ shouldCheckUserSelfIterationGate &&+ shouldExposeSelfIterationIntentTool({+ agentSelfIterationEnabled,+ disableSelfIterationIntentTool: params.disableSelfIterationIntentTool,+ featureUserEnabled: await isAgentSignalEnabledForUser(this.db, this.userId),+ })+ ) {+ tools = tools ?? [];+ injectSelfIterationIntentTool({+ enabledToolIds: toolsResult.enabledToolIds,+ manifestMap: toolManifestMap,+ sourceMap: toolSourceMap,+ tools,+ });+ log('execAgent: injected self-iteration intent declaration tool');+ }}// Inject client function tools from Response APIdiff --git a/src/server/services/brief/index.test.ts b/src/server/services/brief/index.test.tsindex 7537a9e1310..72b79fa41c4 100644--- a/src/server/services/brief/index.test.ts+++ b/src/server/services/brief/index.test.ts@@ -61,6 +61,7 @@ describe('BriefService', () => {describe('enrichBriefsWithAgents', () => {beforeEach(() => {mockTaskModel.findByIds.mockResolvedValue([]);+ mockTaskModel.getTreeAgentIdsForTaskIds.mockResolvedValue({});});it('should return briefs with null agent when no taskIds and no agentIds', async () => {@@ -117,7 +118,7 @@ describe('BriefService', () => {});expect(result[1].taskStatus).toBe('paused');- expect(mockTaskModel.getTreeAgentIdsForTaskIds).not.toHaveBeenCalled();+ expect(mockTaskModel.getTreeAgentIdsForTaskIds).toHaveBeenCalledWith(['task-1', 'task-2']);expect(mockTaskModel.findByIds).toHaveBeenCalledWith(['task-1', 'task-2']);expect(mockAgentModel.getAgentAvatarsByIds).toHaveBeenCalledWith(expect.arrayContaining(['agent-a', 'agent-c']),@@ -167,6 +168,66 @@ describe('BriefService', () => {expect(result[0].taskStatus).toBe('paused');expect(mockAgentModel.getAgentAvatarsByIds).toHaveBeenCalledWith(['agent-gone']);});++ it('should enrich direct agent briefs without requiring a task id', async () => {+ const service = new BriefService(db, userId);++ const briefs = [+ {+ agentId: 'agent-direct',+ id: 'b1',+ taskId: null,+ title: 'Nightly self-review',+ trigger: 'agent-signal:nightly-review',+ },+ ] as any[];++ mockAgentModel.getAgentAvatarsByIds.mockResolvedValue([+ {+ avatar: '🤖',+ backgroundColor: '#fff',+ id: 'agent-direct',+ title: 'Reviewer Agent',+ },+ ]);++ const result = await service.enrichBriefsWithAgents(briefs);++ expect(result[0].agents).toEqual([+ {+ avatar: '🤖',+ backgroundColor: '#fff',+ id: 'agent-direct',+ title: 'Reviewer Agent',+ },+ ]);+ expect(result[0].taskStatus).toBeNull();+ expect(mockTaskModel.getTreeAgentIdsForTaskIds).not.toHaveBeenCalled();+ expect(mockTaskModel.findByIds).not.toHaveBeenCalled();+ expect(mockAgentModel.getAgentAvatarsByIds).toHaveBeenCalledWith(['agent-direct']);+ });++ it('should preserve direct-agent priority and deduplicate task-tree agents', async () => {+ const service = new BriefService(db, userId);++ const briefs = [+ { agentId: 'agent-a', id: 'b1', taskId: 'task-1', title: 'Brief 1' },+ ] as any[];++ mockTaskModel.getTreeAgentIdsForTaskIds.mockResolvedValue({+ 'task-1': ['agent-a', 'agent-b'],+ });+ mockTaskModel.findByIds.mockResolvedValue([{ id: 'task-1', status: 'scheduled' }]);++ mockAgentModel.getAgentAvatarsByIds.mockResolvedValue([+ { avatar: '🤖', backgroundColor: null, id: 'agent-a', title: 'Agent A' },+ { avatar: '🧠', backgroundColor: '#fff', id: 'agent-b', title: 'Agent B' },+ ]);++ const result = await service.enrichBriefsWithAgents(briefs);++ expect(result[0].agents.map((agent) => agent.id)).toEqual(['agent-a', 'agent-b']);+ });});describe('list', () => {diff --git a/src/server/services/brief/index.ts b/src/server/services/brief/index.tsindex b442e875800..4b1cb99c387 100644--- a/src/server/services/brief/index.ts+++ b/src/server/services/brief/index.ts@@ -16,6 +16,8 @@ export interface AgentAvatarInfo {export type BriefWithAgent = BriefItem & {/** Avatar of the agent that produced this brief; `null` when the brief has no `agentId` or the agent has been deleted. */agent: AgentAvatarInfo | null;+ /** Agents related to this brief, ordered with the direct producing agent before task-tree agents. */+ agents: AgentAvatarInfo[];/** Parent task's runtime status — `scheduled` marks a task parked between automated runs. */taskStatus: TaskStatus | null;};@@ -36,19 +38,27 @@ export class BriefService {}async enrichBriefsWithAgents(briefs: BriefItem[]): Promise<BriefWithAgent[]> {- const taskIds = briefs.map((b) => b.taskId).filter((id): id is string => id !== null);- const agentIds = [- ...new Set(briefs.map((b) => b.agentId).filter((id): id is string => Boolean(id))),+ const taskIds = [...new Set(briefs.map((b) => b.taskId).filter((id): id is string => !!id))];+ const directAgentIds = [+ ...new Set(briefs.map((b) => b.agentId).filter((id): id is string => !!id)),];-- if (taskIds.length === 0 && agentIds.length === 0) {- return briefs.map((brief) => ({ ...brief, agent: null, taskStatus: null }));+ if (taskIds.length === 0 && directAgentIds.length === 0) {+ return briefs.map((brief) => ({ ...brief, agent: null, agents: [], taskStatus: null }));}- const [taskRows, agentList] = await Promise.all([+ const emptyTreeAgentIdsByTaskId: Record<string, string[]> = {};+ const [taskRows, treeAgentIdsByTaskId] = await Promise.all([taskIds.length > 0 ? this.taskModel.findByIds(taskIds) : Promise.resolve([]),- agentIds.length > 0 ? this.agentModel.getAgentAvatarsByIds(agentIds) : Promise.resolve([]),+ taskIds.length > 0+ ? this.taskModel.getTreeAgentIdsForTaskIds(taskIds)+ : Promise.resolve(emptyTreeAgentIdsByTaskId),]);++ const agentIds = [+ ...new Set([...directAgentIds, ...Object.values(treeAgentIdsByTaskId).flat()]),+ ];+ const agentList =+ agentIds.length > 0 ? await this.agentModel.getAgentAvatarsByIds(agentIds) : [];const taskStatusMap = Object.fromEntries(taskRows.map((t) => [t.id, (t.status as TaskStatus) ?? null]),);@@ -56,11 +66,26 @@ export class BriefService {agentList.map((a) => [a.id, a]),);- return briefs.map((brief) => ({- ...brief,- agent: brief.agentId ? (agentMap[brief.agentId] ?? null) : null,- taskStatus: brief.taskId ? (taskStatusMap[brief.taskId] ?? null) : null,- }));+ return briefs.map((brief) => {+ const briefAgentIds = new Set<string>();+ if (brief.agentId) {+ briefAgentIds.add(brief.agentId);+ }+ if (brief.taskId) {+ for (const agentId of treeAgentIdsByTaskId[brief.taskId] ?? []) {+ briefAgentIds.add(agentId);+ }+ }++ return {+ ...brief,+ agent: brief.agentId ? (agentMap[brief.agentId] ?? null) : null,+ agents: [...briefAgentIds]+ .map((agentId) => agentMap[agentId])+ .filter((agent): agent is AgentAvatarInfo => Boolean(agent)),+ taskStatus: brief.taskId ? (taskStatusMap[brief.taskId] ?? null) : null,+ };+ });}async list(options?: { limit?: number; offset?: number; type?: string }) {diff --git a/src/server/services/toolExecution/serverRuntimes/__tests__/selfIterationIntent.test.ts b/src/server/services/toolExecution/serverRuntimes/__tests__/selfIterationIntent.test.tsnew file mode 100644index 00000000000..f99593ef134--- /dev/null+++ b/src/server/services/toolExecution/serverRuntimes/__tests__/selfIterationIntent.test.ts@@ -0,0 +1,154 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { enqueueAgentSignalSourceEvent } from '@/server/services/agentSignal';++import { selfIterationIntentRuntime } from '../selfIterationIntent';++vi.mock('@/server/services/agentSignal', () => ({+ enqueueAgentSignalSourceEvent: vi.fn(),+}));++const createInput = () => ({+ action: 'refine' as const,+ confidence: 0.91,+ evidenceRefs: [{ id: 'msg-1', type: 'message' as const }],+ kind: 'skill' as const,+ reason: 'The release workflow correction should become reusable.',+ summary: 'Refine the release workflow skill.',+});++describe('selfIterationIntentRuntime', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.mocked(enqueueAgentSignalSourceEvent).mockResolvedValue({+ accepted: true,+ scopeKey: 'topic:topic-1',+ workflowRunId: 'workflow-1',+ });+ });++ /**+ * @example+ * The runtime accepts a declaration through the enqueue boundary without mutating resources.+ */+ it('calls the enqueue boundary and returns accepted JSON content', async () => {+ const runtime = selfIterationIntentRuntime.factory({ toolManifestMap: {} });++ const result = await runtime.declareSelfIterationIntent(createInput(), {+ agentId: 'agent-1',+ operationId: 'operation-1',+ toolCallId: 'tool-call-1',+ toolManifestMap: {},+ topicId: 'topic-1',+ userId: 'user-1',+ });++ expect(result.success).toBe(true);+ expect(JSON.parse(result.content)).toEqual({+ accepted: true,+ reason: null,+ sourceId: 'self-iteration-intent:user-1:agent-1:operation:operation-1:tool-call-1',+ strength: 'strong',+ });+ expect(enqueueAgentSignalSourceEvent).toHaveBeenCalledWith(+ expect.objectContaining({+ payload: expect.objectContaining({+ agentId: 'agent-1',+ operationId: 'operation-1',+ toolCallId: 'tool-call-1',+ topicId: 'topic-1',+ userId: 'user-1',+ }),+ sourceId: 'self-iteration-intent:user-1:agent-1:operation:operation-1:tool-call-1',+ sourceType: 'agent.self_iteration_intent.declared',+ }),+ { agentId: 'agent-1', userId: 'user-1' },+ );+ });++ /**+ * @example+ * Missing runtime identity context returns a tool failure instead of enqueueing a source.+ */+ it('returns failure content when required context is missing', async () => {+ const runtime = selfIterationIntentRuntime.factory({ toolManifestMap: {} });++ const result = await runtime.declareSelfIterationIntent(createInput(), {+ agentId: 'agent-1',+ toolManifestMap: {},+ userId: 'user-1',+ });++ expect(result.success).toBe(false);+ expect(JSON.parse(result.content)).toEqual({+ accepted: false,+ reason: 'missing_context',+ required: ['agentId', 'userId', 'topicId'],+ });+ expect(enqueueAgentSignalSourceEvent).not.toHaveBeenCalled();+ });++ /**+ * @example+ * Rejected declarations still return a successful tool result so the agent can continue.+ */+ it('returns success true with accepted false for rejected service results', async () => {+ const runtime = selfIterationIntentRuntime.factory({ toolManifestMap: {} });++ const result = await runtime.declareSelfIterationIntent(+ { ...createInput(), confidence: 1.25 },+ {+ agentId: 'agent-1',+ toolManifestMap: {},+ topicId: 'topic-1',+ userId: 'user-1',+ },+ );++ expect(result.success).toBe(true);+ expect(JSON.parse(result.content)).toEqual({+ accepted: false,+ reason: 'invalid_confidence',+ sourceId: null,+ strength: 'weak',+ });+ expect(enqueueAgentSignalSourceEvent).not.toHaveBeenCalled();+ });++ /**+ * @example+ * The fourth accepted declaration across runtime factory calls returns rate_limited.+ */+ it('preserves declaration rate-limit state across runtime factory calls', async () => {+ for (const toolCallId of ['tool-call-1', 'tool-call-2', 'tool-call-3']) {+ const runtime = selfIterationIntentRuntime.factory({ toolManifestMap: {} });++ await expect(+ runtime.declareSelfIterationIntent(createInput(), {+ agentId: 'agent-1',+ toolCallId,+ toolManifestMap: {},+ topicId: 'topic-rate-limit',+ userId: 'user-1',+ }),+ ).resolves.toMatchObject({ success: true });+ }++ const runtime = selfIterationIntentRuntime.factory({ toolManifestMap: {} });+ const result = await runtime.declareSelfIterationIntent(createInput(), {+ agentId: 'agent-1',+ toolCallId: 'tool-call-4',+ toolManifestMap: {},+ topicId: 'topic-rate-limit',+ userId: 'user-1',+ });++ expect(JSON.parse(result.content)).toEqual({+ accepted: false,+ reason: 'rate_limited',+ sourceId: null,+ strength: 'strong',+ });+ expect(enqueueAgentSignalSourceEvent).toHaveBeenCalledTimes(3);+ });+});diff --git a/src/server/services/toolExecution/serverRuntimes/index.ts b/src/server/services/toolExecution/serverRuntimes/index.tsindex 62f1b4e3e70..dc224f7f934 100644--- a/src/server/services/toolExecution/serverRuntimes/index.ts+++ b/src/server/services/toolExecution/serverRuntimes/index.ts@@ -6,7 +6,7 @@* - Pre-instantiated runtimes (e.g., WebBrowsing - no per-request context needed)* - Per-request runtimes (e.g., CloudSandbox - needs topicId, userId)*/-import { type ToolExecutionContext } from '../types';+import type { ToolExecutionContext } from '../types';import { activatorRuntime } from './activator';import { agentDocumentsRuntime } from './agentDocuments';import { agentMarketplaceRuntime } from './agentMarketplace';@@ -22,12 +22,13 @@ import { memoryRuntime } from './memory';import { messageRuntime } from './message';import { notebookRuntime } from './notebook';import { remoteDeviceRuntime } from './remoteDevice';+import { selfIterationIntentRuntime } from './selfIterationIntent';import { skillManagementRuntime } from './skillManagement';import { skillsRuntime } from './skills';import { skillStoreRuntime } from './skillStore';import { taskRuntime } from './task';import { topicReferenceRuntime } from './topicReference';-import { type ServerRuntimeFactory, type ServerRuntimeRegistration } from './types';+import type { ServerRuntimeFactory, ServerRuntimeRegistration } from './types';import { userInteractionRuntime } from './userInteraction';import { webBrowsingRuntime } from './webBrowsing';import { webOnboardingRuntime } from './webOnboarding';@@ -71,6 +72,7 @@ registerRuntimes([webOnboardingRuntime,agentMarketplaceRuntime,lobeAgentRuntime,+ selfIterationIntentRuntime,]);// ==================== Registry API ====================diff --git a/src/server/services/toolExecution/serverRuntimes/selfIterationIntent.ts b/src/server/services/toolExecution/serverRuntimes/selfIterationIntent.tsnew file mode 100644index 00000000000..95a1e6b8014--- /dev/null+++ b/src/server/services/toolExecution/serverRuntimes/selfIterationIntent.ts@@ -0,0 +1,103 @@+import { SELF_ITERATION_INTENT_IDENTIFIER } from '@lobechat/builtin-tool-self-iteration';+import { nanoid } from '@lobechat/utils';++import { enqueueAgentSignalSourceEvent } from '@/server/services/agentSignal';+import type { DeclareSelfIterationIntentPayload } from '@/server/services/agentSignal/services/selfIterationIntent';+import { createSelfIterationIntentService } from '@/server/services/agentSignal/services/selfIterationIntent';++import type { ToolExecutionContext, ToolExecutionResult } from '../types';+import type { ServerRuntimeRegistration } from './types';++type SelfIterationIntentToolResultContent = {+ accepted: boolean;+ reason: null | string;+ sourceId: null | string;+ strength: 'strong' | 'weak';+};++const createJsonResult = (+ content: SelfIterationIntentToolResultContent,+ success: boolean,+): ToolExecutionResult => ({+ content: JSON.stringify(content),+ success,+});++const sharedSelfIterationIntentService = createSelfIterationIntentService({+ enqueueSource: (sourceEvent) =>+ enqueueAgentSignalSourceEvent(sourceEvent, {+ agentId: sourceEvent.payload.agentId,+ userId: sourceEvent.payload.userId,+ }),+ nextToolCallId: () => nanoid(),+});++/**+ * Server runtime for advisory self-iteration intent declarations.+ *+ * Use when:+ * - A running agent calls declareSelfIterationIntent+ * - The server should enqueue Agent Signal source events without mutating resources directly+ *+ * Expects:+ * - Tool execution context includes `agentId`, `userId`, and `topicId`+ * - `operationId` and `toolCallId` are used when present for stable source identity+ *+ * Returns:+ * - JSON tool content with accepted status, source id, strength, and rejection reason+ */+class SelfIterationIntentRuntime {+ declareSelfIterationIntent = async (+ input: DeclareSelfIterationIntentPayload,+ context: ToolExecutionContext,+ ): Promise<ToolExecutionResult> => {+ const { agentId, operationId, toolCallId, topicId, userId } = context;++ if (!agentId || !userId || !topicId) {+ return {+ content: JSON.stringify({+ accepted: false,+ reason: 'missing_context',+ required: ['agentId', 'userId', 'topicId'],+ }),+ success: false,+ };+ }++ const result = await sharedSelfIterationIntentService.declareIntent({+ agentId,+ input,+ operationId,+ toolCallId,+ topicId,+ userId,+ });++ return createJsonResult(+ {+ accepted: result.accepted,+ reason: result.reason ?? null,+ sourceId: result.sourceId ?? null,+ strength: result.strength,+ },+ true,+ );+ };+}++/**+ * Registers the self-iteration intent builtin server runtime.+ *+ * Use when:+ * - BuiltinToolsExecutor needs to resolve the injected declaration tool+ *+ * Expects:+ * - Per-call method validation handles required runtime context+ *+ * Returns:+ * - A lightweight runtime instance for the current execution+ */+export const selfIterationIntentRuntime: ServerRuntimeRegistration = {+ factory: () => new SelfIterationIntentRuntime(),+ identifier: SELF_ITERATION_INTENT_IDENTIFIER,+};diff --git a/src/server/workflows/agentSignal/__tests__/run.test.ts b/src/server/workflows/agentSignal/__tests__/run.test.tsindex 2ffad7827e1..57b455e25c1 100644--- a/src/server/workflows/agentSignal/__tests__/run.test.ts+++ b/src/server/workflows/agentSignal/__tests__/run.test.ts@@ -1,17 +1,16 @@// @vitest-environment node-import {- AGENT_SIGNAL_SOURCE_TYPES,- type AgentSignalSourceEvent,- type SourceAgentUserMessage,-} from '@lobechat/agent-signal/source';+import type { AgentSignalSourceEvent, SourceAgentUserMessage } from '@lobechat/agent-signal/source';+import { AGENT_SIGNAL_SOURCE_TYPES, createSourceEvent } from '@lobechat/agent-signal/source';import { agents, messages, threads, topics, users } from '@lobechat/database/schemas';import { getTestDB } from '@lobechat/database/test-utils';import { describe, expect, it, vi } from 'vitest';-import {- runAgentSignalWorkflow,- type RunAgentSignalWorkflowDeps,-} from '@/server/workflows/agentSignal/run';+import type { SelfReflectionReviewContext } from '@/server/services/agentSignal/policies/reviewNightly/selfReflection';+import { createProcedurePolicyOptions as createProcedurePolicyOptionsFixture } from '@/server/services/agentSignal/procedure';+import { MaintenanceReviewScope, ReviewRunStatus } from '@/server/services/agentSignal/services';+import type { AgentSignalPolicyStateStore } from '@/server/services/agentSignal/store/types';+import type { RunAgentSignalWorkflowDeps } from '@/server/workflows/agentSignal/run';+import { runAgentSignalWorkflow } from '@/server/workflows/agentSignal/run';import { uuid } from '@/utils/uuid';vi.mock('@/server/services/agentSignal/featureGate', () => ({@@ -25,6 +24,17 @@ const createWorkflowContext = <TPayload>(requestPayload: TPayload) => {};};+const createPolicyStateStore = (): AgentSignalPolicyStateStore => {+ const state = new Map<string, Record<string, string>>();++ return {+ readPolicyState: async (policyId, scopeKey) => state.get(`${policyId}:${scopeKey}`),+ writePolicyState: async (policyId, scopeKey, data) => {+ state.set(`${policyId}:${scopeKey}`, { ...state.get(`${policyId}:${scopeKey}`), ...data });+ },+ };+};+describe('runAgentSignalWorkflow', () => {it('bridges client.runtime.start into agent.user.message with serialized root-topic context', async () => {const db = await getTestDB();@@ -437,4 +447,290 @@ describe('runAgentSignalWorkflow', () => {'Later root message that should still be excluded from the threaded context.',);});++ it('installs nightly review policy dependencies only for nightly review sources', async () => {+ const db = await getTestDB();+ const userId = `eval_${uuid()}`;+ const agentId = `agent_${uuid()}`;+ const localDate = '2026-05-04';+ const sourceId = `nightly-review:${userId}:${agentId}:${localDate}`;+ const nightlyReviewPolicyOptions = {+ acquireReviewGuard: vi.fn(async () => true),+ canRunReview: vi.fn(async () => true),+ collectContext: vi.fn(async () => ({+ agentId,+ managedSkills: [],+ relevantMemories: [],+ reviewWindowEnd: '2026-05-04T14:30:00.000Z',+ reviewWindowStart: '2026-05-03T16:00:00.000Z',+ topics: [],+ userId,+ })),+ executePlan: vi.fn(async () => ({ actions: [], status: ReviewRunStatus.Completed })),+ planReviewOutput: vi.fn(() => ({+ actions: [],+ plannerVersion: 'test',+ reviewScope: MaintenanceReviewScope.Nightly,+ summary: 'Noop',+ })),+ runMaintenanceReviewAgent: vi.fn(async () => ({+ actions: [],+ findings: [],+ summary: 'Noop',+ })),+ };+ const createNightlyReviewPolicyOptions: NonNullable<+ RunAgentSignalWorkflowDeps['createNightlyReviewPolicyOptions']+ > = vi.fn(() => nightlyReviewPolicyOptions);+ const executeSourceEvent: NonNullable<RunAgentSignalWorkflowDeps['executeSourceEvent']> = vi.fn(+ async () => undefined,+ );+ const sourceEvent = createSourceEvent({+ payload: {+ agentId,+ localDate,+ requestedAt: '2026-05-04T14:30:00.000Z',+ reviewWindowEnd: '2026-05-04T14:30:00.000Z',+ reviewWindowStart: '2026-05-03T16:00:00.000Z',+ timezone: 'Asia/Shanghai',+ userId,+ },+ scopeKey: `agent:${agentId}`,+ sourceId,+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentNightlyReviewRequested,+ timestamp: Date.now(),+ });++ await runAgentSignalWorkflow(createWorkflowContext({ agentId, sourceEvent, userId }), {+ createNightlyReviewPolicyOptions,+ executeSourceEvent,+ getDb: async () => db,+ });++ expect(createNightlyReviewPolicyOptions).toHaveBeenCalledWith({+ agentId,+ db,+ selfIterationEnabled: true,+ userId,+ });+ expect(executeSourceEvent).toHaveBeenCalledWith(+ sourceEvent,+ expect.any(Object),+ expect.objectContaining({+ policyOptions: expect.objectContaining({+ nightlyReview: nightlyReviewPolicyOptions,+ skillManagement: {+ selfIterationEnabled: true,+ },+ }),+ }),+ );+ });++ it('installs self-reflection policy dependencies for self-reflection sources', async () => {+ const db = await getTestDB();+ const userId = `eval_${uuid()}`;+ const agentId = `agent_${uuid()}`;+ const sourceId = `self-reflection:${userId}:${agentId}:topic:topic-1:failed_tool_count:2026-05-04T14:30:00.000Z`;+ const selfReflectionContext: SelfReflectionReviewContext = {+ agentId,+ scopeId: 'topic-1',+ scopeType: 'topic',+ userId,+ windowEnd: '2026-05-04T14:30:00.000Z',+ windowStart: '2026-05-04T14:00:00.000Z',+ };+ const selfReflectionPolicyOptions = {+ acquireReviewGuard: vi.fn(async () => true),+ canRunReview: vi.fn(async () => true),+ collectContext: vi.fn(async () => selfReflectionContext),+ executePlan: vi.fn(async () => ({ actions: [], status: ReviewRunStatus.Completed })),+ planReviewOutput: vi.fn(() => ({+ actions: [],+ plannerVersion: 'test',+ reviewScope: MaintenanceReviewScope.SelfReflection,+ summary: 'Noop',+ })),+ runMaintenanceReviewAgent: vi.fn(async () => ({+ actions: [],+ findings: [],+ summary: 'Noop',+ })),+ writeReceipt: vi.fn(async () => {}),+ };+ const createSelfReflectionPolicyOptions: NonNullable<+ RunAgentSignalWorkflowDeps['createSelfReflectionPolicyOptions']+ > = vi.fn(() => selfReflectionPolicyOptions);+ const executeSourceEvent: NonNullable<RunAgentSignalWorkflowDeps['executeSourceEvent']> = vi.fn(+ async () => undefined,+ );+ const sourceEvent = createSourceEvent({+ payload: {+ agentId,+ reason: 'failed_tool_count',+ scopeId: 'topic-1',+ scopeType: 'topic',+ topicId: 'topic-1',+ userId,+ windowEnd: '2026-05-04T14:30:00.000Z',+ windowStart: '2026-05-04T14:00:00.000Z',+ },+ scopeKey: 'topic:topic-1',+ sourceId,+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentSelfReflectionRequested,+ timestamp: Date.now(),+ });++ await runAgentSignalWorkflow(createWorkflowContext({ agentId, sourceEvent, userId }), {+ createSelfReflectionPolicyOptions,+ executeSourceEvent,+ getDb: async () => db,+ });++ expect(createSelfReflectionPolicyOptions).toHaveBeenCalledWith({+ agentId,+ db,+ selfIterationEnabled: true,+ userId,+ });+ expect(executeSourceEvent).toHaveBeenCalledWith(+ sourceEvent,+ expect.any(Object),+ expect.objectContaining({+ policyOptions: expect.objectContaining({+ selfReflection: selfReflectionPolicyOptions,+ skillManagement: {+ selfIterationEnabled: true,+ },+ }),+ }),+ );+ });++ it('installs self-iteration intent policy dependencies for declared intent sources', async () => {+ const db = await getTestDB();+ const userId = `eval_${uuid()}`;+ const agentId = `agent_${uuid()}`;+ const sourceId = `self-iteration-intent:${userId}:${agentId}:topic:topic-1:tool-call-1`;+ const selfIterationIntentPolicyOptions = {+ acquireReviewGuard: vi.fn(async () => true),+ canRunReview: vi.fn(async () => true),+ executePlan: vi.fn(async () => ({ actions: [], status: ReviewRunStatus.Completed })),+ planReviewOutput: vi.fn(() => ({+ actions: [],+ plannerVersion: 'test',+ reviewScope: MaintenanceReviewScope.SelfIterationIntent,+ summary: 'Noop',+ })),+ writeReceipt: vi.fn(async () => {}),+ };+ const createSelfIterationIntentPolicyOptions: NonNullable<+ RunAgentSignalWorkflowDeps['createSelfIterationIntentPolicyOptions']+ > = vi.fn(() => selfIterationIntentPolicyOptions);+ const executeSourceEvent: NonNullable<RunAgentSignalWorkflowDeps['executeSourceEvent']> = vi.fn(+ async () => undefined,+ );+ const sourceEvent = createSourceEvent({+ payload: {+ action: 'refine',+ agentId,+ confidence: 0.9,+ evidenceRefs: [{ id: 'msg-1', type: 'message' }],+ kind: 'skill',+ reason: 'Reusable correction.',+ skillId: 'skill-1',+ summary: 'Refine release-note workflow.',+ toolCallId: 'tool-call-1',+ topicId: 'topic-1',+ userId,+ },+ scopeKey: 'topic:topic-1',+ sourceId,+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentSelfIterationIntentDeclared,+ timestamp: Date.now(),+ });++ await runAgentSignalWorkflow(createWorkflowContext({ agentId, sourceEvent, userId }), {+ createSelfIterationIntentPolicyOptions,+ executeSourceEvent,+ getDb: async () => db,+ });++ expect(createSelfIterationIntentPolicyOptions).toHaveBeenCalledWith({+ agentId,+ db,+ selfIterationEnabled: true,+ userId,+ });+ expect(executeSourceEvent).toHaveBeenCalledWith(+ sourceEvent,+ expect.any(Object),+ expect.objectContaining({+ policyOptions: expect.objectContaining({+ selfIterationIntent: selfIterationIntentPolicyOptions,+ skillManagement: {+ selfIterationEnabled: true,+ },+ }),+ }),+ );+ });++ it('installs procedure self-reflection dependencies for tool outcome sources', async () => {+ const db = await getTestDB();+ const userId = `eval_${uuid()}`;+ const agentId = `agent_${uuid()}`;+ const procedurePolicyOptions = createProcedurePolicyOptionsFixture({+ policyStateStore: createPolicyStateStore(),+ ttlSeconds: 60,+ });+ const createProcedurePolicyOptions: NonNullable<+ RunAgentSignalWorkflowDeps['createProcedurePolicyOptions']+ > = vi.fn(() => procedurePolicyOptions);+ const executeSourceEvent: NonNullable<RunAgentSignalWorkflowDeps['executeSourceEvent']> = vi.fn(+ async () => undefined,+ );+ const sourceEvent = createSourceEvent({+ payload: {+ agentId,+ domainKey: 'skill:tool-call',+ outcome: {+ status: 'failed',+ summary: 'Tool failed twice.',+ },+ tool: { apiName: 'writeFile', identifier: 'filesystem' },+ toolCallId: 'tool-call-1',+ topicId: 'topic-1',+ },+ scopeKey: 'topic:topic-1',+ sourceId: 'tool-outcome:filesystem:writeFile:failed:tool-call-1',+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.toolOutcomeFailed,+ timestamp: Date.now(),+ });++ await runAgentSignalWorkflow(createWorkflowContext({ agentId, sourceEvent, userId }), {+ createProcedurePolicyOptions,+ executeSourceEvent,+ getDb: async () => db,+ });++ expect(createProcedurePolicyOptions).toHaveBeenCalledWith({+ agentId,+ db,+ selfIterationEnabled: true,+ userId,+ });+ expect(executeSourceEvent).toHaveBeenCalledWith(+ sourceEvent,+ expect.any(Object),+ expect.objectContaining({+ policyOptions: expect.objectContaining({+ procedure: procedurePolicyOptions,+ skillManagement: {+ selfIterationEnabled: true,+ },+ }),+ }),+ );+ });});diff --git a/src/server/workflows/agentSignal/run.ts b/src/server/workflows/agentSignal/run.tsindex 6c7008050ed..3d186f408c8 100644--- a/src/server/workflows/agentSignal/run.ts+++ b/src/server/workflows/agentSignal/run.ts@@ -1,9 +1,15 @@+import type {+ SourceEventAgentUserMessage,+ SourceEventClientRuntimeStart,+} from '@lobechat/agent-signal/source';import {AGENT_SIGNAL_SOURCE_TYPES,- type AgentSignalSourceEvent,- type AgentSignalSourceType,- type SourceAgentUserMessage,- type SourceClientRuntimeStart,+ isAgentUserMessageSource,+ isClientRuntimeStartSource,+ isNightlyReviewSource,+ isSelfIterationIntentSource,+ isSelfReflectionSource,+ isToolOutcomeSource,} from '@lobechat/agent-signal/source';import type { ExecutionSnapshot, ISnapshotStore, StepSnapshot } from '@lobechat/agent-tracing';import { messages } from '@lobechat/database/schemas';@@ -26,6 +32,12 @@ import type { GeneratedAgentSignalEmissionResult } from '@/server/services/agentimport { executeAgentSignalSourceEvent } from '@/server/services/agentSignal/orchestrator';import { assembleFeedbackContext } from '@/server/services/agentSignal/policies/analyzeIntent/context/feedbackContextAssembler';import { createRedisRuntimeGuardBackend } from '@/server/services/agentSignal/runtime/backend/redisGuard';+import {+ createServerNightlyReviewPolicyOptions,+ createServerProcedurePolicyOptions,+ createServerSelfIterationIntentPolicyOptions,+ createServerSelfReflectionPolicyOptions,+} from '@/server/services/agentSignal/services/maintenance/serverRuntime';import type { AgentSignalWorkflowRunPayload } from './types';@@ -50,21 +62,16 @@ export interface AgentSignalWorkflowContext<TPayload = AgentSignalWorkflowRunPay/** Dependencies for executing one Agent Signal workflow payload. */export interface RunAgentSignalWorkflowDeps {+ createNightlyReviewPolicyOptions?: typeof createServerNightlyReviewPolicyOptions;+ createProcedurePolicyOptions?: typeof createServerProcedurePolicyOptions;createRuntimeGuardBackend?: typeof createRedisRuntimeGuardBackend;+ createSelfIterationIntentPolicyOptions?: typeof createServerSelfIterationIntentPolicyOptions;+ createSelfReflectionPolicyOptions?: typeof createServerSelfReflectionPolicyOptions;createSnapshotStore?: () => ISnapshotStore | null;executeSourceEvent?: typeof executeAgentSignalSourceEvent;getDb?: typeof getServerDB;}-/**- * One normalized workflow source event after ingress bridging.- *- * @param TSourceType - Concrete Agent Signal source type after normalization.- */-interface NormalizedWorkflowSourceEventInput<- TSourceType extends AgentSignalSourceType = AgentSignalSourceType,-> extends AgentSignalSourceEvent<TSourceType> {}-const buildWorkflowMetricAttributes = (sourceType: string,status: 'error' | 'generated' | 'invalid_payload' | 'no_emission',@@ -181,18 +188,6 @@ const persistWorkflowSnapshot = async (await store.save(snapshot);};-const isClientRuntimeStartSource = (- sourceEvent: AgentSignalWorkflowRunPayload['sourceEvent'],-): sourceEvent is NormalizedWorkflowSourceEventInput<SourceClientRuntimeStart['sourceType']> => {- return sourceEvent.sourceType === AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeStart;-};--const isAgentUserMessageSource = (- sourceEvent: AgentSignalWorkflowRunPayload['sourceEvent'],-): sourceEvent is NormalizedWorkflowSourceEventInput<SourceAgentUserMessage['sourceType']> => {- return sourceEvent.sourceType === AGENT_SIGNAL_SOURCE_TYPES.agentUserMessage;-};-/*** Rebuilds one `agent.user.message` source from the client runtime-start event.*@@ -209,11 +204,9 @@ const isAgentUserMessageSource = (* - Otherwise returns `undefined` so the original client source can continue unchanged*/const bridgeClientRuntimeStartToAgentUserMessage = async (- sourceEvent: NormalizedWorkflowSourceEventInput<SourceClientRuntimeStart['sourceType']>,+ sourceEvent: SourceEventClientRuntimeStart,input: { db: Awaited<ReturnType<typeof getServerDB>>; userId: string },-): Promise<- NormalizedWorkflowSourceEventInput<SourceAgentUserMessage['sourceType']> | undefined-> => {+): Promise<SourceEventAgentUserMessage | undefined> => {if (sourceEvent.payload.parentMessageType !== 'user') return undefined;if (typeof sourceEvent.payload.parentMessageId !== 'string') return undefined;@@ -246,7 +239,7 @@ const bridgeClientRuntimeStartToAgentUserMessage = async (};const buildFeedbackSourceSerializedContext = async (- sourceEvent: NormalizedWorkflowSourceEventInput<SourceAgentUserMessage['sourceType']>,+ sourceEvent: SourceEventAgentUserMessage,input: { db: Awaited<ReturnType<typeof getServerDB>>; userId: string },): Promise<string | undefined> => {if (typeof sourceEvent.payload.serializedContext === 'string') {@@ -434,6 +427,15 @@ export const runAgentSignalWorkflow = async (const getDb = deps.getDb ?? getServerDB;const executeSourceEvent = deps.executeSourceEvent ?? executeAgentSignalSourceEvent;+ const createNightlyReviewPolicyOptions =+ deps.createNightlyReviewPolicyOptions ?? createServerNightlyReviewPolicyOptions;+ const createSelfReflectionPolicyOptions =+ deps.createSelfReflectionPolicyOptions ?? createServerSelfReflectionPolicyOptions;+ const createSelfIterationIntentPolicyOptions =+ deps.createSelfIterationIntentPolicyOptions ??+ createServerSelfIterationIntentPolicyOptions;+ const createProcedurePolicyOptions =+ deps.createProcedurePolicyOptions ?? createServerProcedurePolicyOptions;const createGuardBackend =deps.createRuntimeGuardBackend ?? createRedisRuntimeGuardBackend;const snapshotStore = (deps.createSnapshotStore ?? createDefaultSnapshotStore)();@@ -471,6 +473,38 @@ export const runAgentSignalWorkflow = async ('agent_signal.workflow.execute',async (executeSpan) => {try {+ const nightlyReview = isNightlyReviewSource(normalizedSourceEvent)+ ? createNightlyReviewPolicyOptions({+ agentId: payload.agentId,+ db,+ selfIterationEnabled,+ userId: payload.userId,+ })+ : undefined;+ const selfReflection = isSelfReflectionSource(normalizedSourceEvent)+ ? createSelfReflectionPolicyOptions({+ agentId: payload.agentId,+ db,+ selfIterationEnabled,+ userId: payload.userId,+ })+ : undefined;+ const selfIterationIntent = isSelfIterationIntentSource(normalizedSourceEvent)+ ? createSelfIterationIntentPolicyOptions({+ agentId: payload.agentId,+ db,+ selfIterationEnabled,+ userId: payload.userId,+ })+ : undefined;+ const procedure = isToolOutcomeSource(normalizedSourceEvent)+ ? createProcedurePolicyOptions({+ agentId: payload.agentId,+ db,+ selfIterationEnabled,+ userId: payload.userId,+ })+ : undefined;const executionResult = await context.run(`agent-signal:execute:${normalizedSourceEvent.sourceType}:${normalizedSourceEvent.sourceId}`,() =>@@ -483,6 +517,10 @@ export const runAgentSignalWorkflow = async (},{policyOptions: {+ ...(nightlyReview ? { nightlyReview } : {}),+ ...(procedure ? { procedure } : {}),+ ...(selfIterationIntent ? { selfIterationIntent } : {}),+ ...(selfReflection ? { selfReflection } : {}),skillManagement: {selfIterationEnabled,},