🤯 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
♻️ refactor(agent-signal,prompts,database,builtin-tool-self-iteration): unified structure of service, unified tool, unified name and concepts (#14699)
Neko29db177524ff
diff --git a/packages/agent-signal/src/source/sourceEvent.test.ts b/packages/agent-signal/src/source/sourceEvent.test.tsindex 7494545b475..0cc7d5aae9a 100644--- a/packages/agent-signal/src/source/sourceEvent.test.ts+++ b/packages/agent-signal/src/source/sourceEvent.test.ts@@ -7,7 +7,7 @@ import {isAgentUserMessageSource,isClientRuntimeStartSource,isNightlyReviewSource,- isSelfIterationIntentSource,+ isSelfFeedbackIntentSource,isSelfReflectionSource,isToolOutcomeSource,} from './index';@@ -126,10 +126,10 @@ describe('AgentSignal source events', () => {/*** @example- * createSourceEvent({ sourceType: 'agent.self_iteration_intent.declared', sourceId, payload })+ * createSourceEvent({ sourceType: 'agent.self_feedback_intent.declared', sourceId, payload })* returns a topic scoped tool-declared source event.*/- it('creates a self-iteration intent event in the current topic scope', () => {+ it('creates a self-feedback intent event in the current topic scope', () => {const event = createSourceEvent({payload: {action: 'refine',@@ -142,13 +142,13 @@ describe('AgentSignal source events', () => {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,+ sourceId: 'self-feedback-intent:user-1:agent-1:topic:topic-1:tool-call-1',+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentSelfFeedbackIntentDeclared,timestamp: 789,});expect(event.scopeKey).toBe('topic:topic-1');- expect(event.sourceType).toBe('agent.self_iteration_intent.declared');+ expect(event.sourceType).toBe('agent.self_feedback_intent.declared');});/**@@ -203,7 +203,7 @@ describe('AgentSignal source events', () => {sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentSelfReflectionRequested,timestamp: 123,});- const selfIterationIntent = createSourceEvent({+ const selfFeedbackIntent = createSourceEvent({payload: {action: 'refine',agentId: 'agent-1',@@ -213,8 +213,8 @@ describe('AgentSignal source events', () => {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,+ sourceId: 'self-feedback-intent:user-1:agent-1:topic:topic-1:tool-call-1',+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentSelfFeedbackIntentDeclared,timestamp: 123,});const failedToolOutcome = createSourceEvent({@@ -231,7 +231,7 @@ describe('AgentSignal source events', () => {expect(isAgentUserMessageSource(agentUserMessage)).toBe(true);expect(isNightlyReviewSource(nightlyReview)).toBe(true);expect(isSelfReflectionSource(selfReflection)).toBe(true);- expect(isSelfIterationIntentSource(selfIterationIntent)).toBe(true);+ expect(isSelfFeedbackIntentSource(selfFeedbackIntent)).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 a952ae744eb..e3967212fd2 100644--- a/packages/agent-signal/src/source/sourceTypes.ts+++ b/packages/agent-signal/src/source/sourceTypes.ts@@ -6,7 +6,7 @@ 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',+ agentSelfFeedbackIntentDeclared: 'agent.self_feedback_intent.declared',agentSelfReflectionRequested: 'agent.self_reflection.requested',agentUserMessage: 'agent.user.message',botMessageMerged: 'bot.message.merged',@@ -55,7 +55,7 @@ export interface AgentSignalSourcePayloadMap {timezone: string;userId: string;};- [AGENT_SIGNAL_SOURCE_TYPES.agentSelfIterationIntentDeclared]: {+ [AGENT_SIGNAL_SOURCE_TYPES.agentSelfFeedbackIntentDeclared]: {action: 'write' | 'create' | 'refine' | 'consolidate' | 'proposal';agentId: string;confidence: number;@@ -235,9 +235,9 @@ export type SourceAgentNightlyReviewRequested =export type SourceAgentSelfReflectionRequested =AgentSignalSourceVariant<'agent.self_reflection.requested'>;-/** Agent-declared self-iteration intent source variant. */-export type SourceAgentSelfIterationIntentDeclared =- AgentSignalSourceVariant<'agent.self_iteration_intent.declared'>;+/** Agent-declared self-feedback intent source variant. */+export type SourceAgentSelfFeedbackIntentDeclared =+ AgentSignalSourceVariant<'agent.self_feedback_intent.declared'>;/** Runtime before-step source variant. */export type SourceRuntimeBeforeStep = AgentSignalSourceVariant<'runtime.before_step'>;@@ -288,9 +288,9 @@ export type SourceEventAgentNightlyReviewRequested =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 agent-declared self-feedback intent source event. */+export type SourceEventAgentSelfFeedbackIntentDeclared =+ AgentSignalSourceEvent<'agent.self_feedback_intent.declared'>;/** Normalized tool outcome source event. */export type SourceEventToolOutcome =@@ -415,21 +415,21 @@ export const isSelfReflectionSource = (};/**- * Narrows a source event to `agent.self_iteration_intent.declared`.+ * Narrows a source event to `agent.self_feedback_intent.declared`.** Use when:- * - Workflow policy composition needs self-iteration intent dependencies only for declared intents+ * - Workflow policy composition needs self-feedback 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+ * - Whether the source is an agent-declared self-feedback intent source*/-export const isSelfIterationIntentSource = (+export const isSelfFeedbackIntentSource = (source: AgentSignalSourceEvent,-): source is SourceEventAgentSelfIterationIntentDeclared => {- return source.sourceType === AGENT_SIGNAL_SOURCE_TYPES.agentSelfIterationIntentDeclared;+): source is SourceEventAgentSelfFeedbackIntentDeclared => {+ return source.sourceType === AGENT_SIGNAL_SOURCE_TYPES.agentSelfFeedbackIntentDeclared;};/**diff --git a/packages/builtin-tool-self-iteration/src/index.test.ts b/packages/builtin-tool-self-iteration/src/index.test.tsindex 29948ab9ca7..746477c0939 100644--- a/packages/builtin-tool-self-iteration/src/index.test.ts+++ b/packages/builtin-tool-self-iteration/src/index.test.ts@@ -2,12 +2,12 @@ import type { LobeToolManifest, OperationToolSet, ToolSource } from '@lobechat/cimport { describe, expect, it } from 'vitest';import {- injectSelfIterationIntentTool,- SELF_ITERATION_INTENT_API_NAME,- SELF_ITERATION_INTENT_IDENTIFIER,- SELF_ITERATION_INTENT_TOOL_NAME,- selfIterationIntentManifest,- shouldExposeSelfIterationIntentTool,+ injectSelfFeedbackIntentTool,+ SELF_FEEDBACK_INTENT_API_NAME,+ SELF_FEEDBACK_INTENT_IDENTIFIER,+ SELF_FEEDBACK_INTENT_TOOL_NAME,+ selfFeedbackIntentManifest,+ shouldExposeSelfFeedbackIntentTool,} from './index';interface ToolSetParts {@@ -24,28 +24,28 @@ const createToolSetParts = (): ToolSetParts => ({tools: [],});-describe('selfIterationIntentTool', () => {- describe('shouldExposeSelfIterationIntentTool', () => {+describe('selfFeedbackIntentTool', () => {+ describe('shouldExposeSelfFeedbackIntentTool', () => {/*** @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({+ shouldExposeSelfFeedbackIntentTool({agentSelfIterationEnabled: true,featureUserEnabled: true,}),).toBe(true);expect(- shouldExposeSelfIterationIntentTool({+ shouldExposeSelfFeedbackIntentTool({agentSelfIterationEnabled: false,featureUserEnabled: true,}),).toBe(false);expect(- shouldExposeSelfIterationIntentTool({+ shouldExposeSelfFeedbackIntentTool({agentSelfIterationEnabled: true,featureUserEnabled: false,}),@@ -58,21 +58,21 @@ describe('selfIterationIntentTool', () => {*/it('is hidden when disabled or reviewer role is set', () => {expect(- shouldExposeSelfIterationIntentTool({+ shouldExposeSelfFeedbackIntentTool({agentSelfIterationEnabled: true,disabled: true,featureUserEnabled: true,}),).toBe(false);expect(- shouldExposeSelfIterationIntentTool({+ shouldExposeSelfFeedbackIntentTool({agentSelfIterationEnabled: true,- disableSelfIterationIntentTool: true,+ disableSelfFeedbackIntentTool: true,featureUserEnabled: true,}),).toBe(false);expect(- shouldExposeSelfIterationIntentTool({+ shouldExposeSelfFeedbackIntentTool({agentSelfIterationEnabled: true,featureUserEnabled: true,reviewerRole: true,@@ -81,17 +81,17 @@ describe('selfIterationIntentTool', () => {});});- describe('selfIterationIntentManifest', () => {+ describe('selfFeedbackIntentManifest', () => {/*** @example- * The declaration schema exposes every field accepted by DeclareSelfIterationIntentPayload.+ * The declaration schema exposes every field accepted by DeclareSelfFeedbackIntentPayload.*/it('declares the expected input schema fields', () => {- const api = selfIterationIntentManifest.api[0];+ const api = selfFeedbackIntentManifest.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(selfFeedbackIntentManifest.identifier).toBe(SELF_FEEDBACK_INTENT_IDENTIFIER);+ expect(api.name).toBe(SELF_FEEDBACK_INTENT_API_NAME);expect(Object.keys(properties)).toEqual(['action','kind',@@ -113,7 +113,7 @@ describe('selfIterationIntentTool', () => {});});- describe('injectSelfIterationIntentTool', () => {+ describe('injectSelfFeedbackIntentTool', () => {/*** @example* The helper injects a builtin manifest, generated LLM tool, and enabled id.@@ -121,17 +121,17 @@ describe('selfIterationIntentTool', () => {it('injects the builtin tool parts with the generated tool name', () => {const toolSetParts = createToolSetParts();- const injected = injectSelfIterationIntentTool(toolSetParts);+ const injected = injectSelfFeedbackIntentTool(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.enabledToolIds).toContain(SELF_FEEDBACK_INTENT_IDENTIFIER);+ expect(toolSetParts.sourceMap[SELF_FEEDBACK_INTENT_IDENTIFIER]).toBe('builtin');+ expect(toolSetParts.manifestMap[SELF_FEEDBACK_INTENT_IDENTIFIER]).toBe(+ selfFeedbackIntentManifest,);expect(toolSetParts.tools).toContainEqual(expect.objectContaining({- function: expect.objectContaining({ name: SELF_ITERATION_INTENT_TOOL_NAME }),+ function: expect.objectContaining({ name: SELF_FEEDBACK_INTENT_TOOL_NAME }),type: 'function',}),);@@ -144,14 +144,14 @@ describe('selfIterationIntentTool', () => {it('does not duplicate tool parts when called twice', () => {const toolSetParts = createToolSetParts();- expect(injectSelfIterationIntentTool(toolSetParts)).toBe(true);- expect(injectSelfIterationIntentTool(toolSetParts)).toBe(false);+ expect(injectSelfFeedbackIntentTool(toolSetParts)).toBe(true);+ expect(injectSelfFeedbackIntentTool(toolSetParts)).toBe(false);expect(- toolSetParts.enabledToolIds.filter((id) => id === SELF_ITERATION_INTENT_IDENTIFIER),+ toolSetParts.enabledToolIds.filter((id) => id === SELF_FEEDBACK_INTENT_IDENTIFIER),).toHaveLength(1);expect(- toolSetParts.tools.filter((tool) => tool.function.name === SELF_ITERATION_INTENT_TOOL_NAME),+ toolSetParts.tools.filter((tool) => tool.function.name === SELF_FEEDBACK_INTENT_TOOL_NAME),).toHaveLength(1);});});diff --git a/packages/builtin-tool-self-iteration/src/index.ts b/packages/builtin-tool-self-iteration/src/index.tsindex b0328748ca3..dc022e77ffb 100644--- a/packages/builtin-tool-self-iteration/src/index.ts+++ b/packages/builtin-tool-self-iteration/src/index.ts@@ -1,12 +1,12 @@export {- injectSelfIterationIntentTool,- type SelfIterationIntentToolSetParts,- shouldExposeSelfIterationIntentTool,+ injectSelfFeedbackIntentTool,+ type SelfFeedbackIntentToolSetParts,+ shouldExposeSelfFeedbackIntentTool,} from './inject';-export { selfIterationIntentManifest } from './manifest';+export { selfFeedbackIntentManifest } from './manifest';export {- SELF_ITERATION_INTENT_API_NAME,- SELF_ITERATION_INTENT_IDENTIFIER,- SELF_ITERATION_INTENT_TOOL_NAME,- type ShouldExposeSelfIterationIntentToolOptions,+ SELF_FEEDBACK_INTENT_API_NAME,+ SELF_FEEDBACK_INTENT_IDENTIFIER,+ SELF_FEEDBACK_INTENT_TOOL_NAME,+ type ShouldExposeSelfFeedbackIntentToolOptions,} from './types';diff --git a/packages/builtin-tool-self-iteration/src/inject.ts b/packages/builtin-tool-self-iteration/src/inject.tsindex 4852167bdf9..c9097fcd312 100644--- a/packages/builtin-tool-self-iteration/src/inject.ts+++ b/packages/builtin-tool-self-iteration/src/inject.ts@@ -1,11 +1,11 @@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';+import { selfFeedbackIntentManifest } from './manifest';+import type { ShouldExposeSelfFeedbackIntentToolOptions } from './types';+import { SELF_FEEDBACK_INTENT_IDENTIFIER, SELF_FEEDBACK_INTENT_TOOL_NAME } from './types';/** Mutable operation tool-set parts that can receive the injected builtin tool. */-export interface SelfIterationIntentToolSetParts {+export interface SelfFeedbackIntentToolSetParts {/** Enabled tool identifiers persisted with the operation. */enabledToolIds: string[];/** Manifest map persisted with the operation. */@@ -16,18 +16,18 @@ export interface SelfIterationIntentToolSetParts {tools: OperationToolSet['tools'];}-const createSelfIterationIntentTool = () =>- selfIterationIntentManifest.api.map((api) => ({+const createSelfFeedbackIntentTool = () =>+ selfFeedbackIntentManifest.api.map((api) => ({function: {description: api.description,- name: SELF_ITERATION_INTENT_TOOL_NAME,+ name: SELF_FEEDBACK_INTENT_TOOL_NAME,parameters: api.parameters,},type: 'function' as const,}));/**- * Decides whether the self-iteration intent declaration tool should be visible.+ * Decides whether the self-feedback intent declaration tool should be visible.** Use when:* - Tests need a pure visibility predicate@@ -39,11 +39,11 @@ const createSelfIterationIntentTool = () =>* Returns:* - `true` only for ordinary running agents with all gates enabled*/-export const shouldExposeSelfIterationIntentTool = (- options: ShouldExposeSelfIterationIntentToolOptions,+export const shouldExposeSelfFeedbackIntentTool = (+ options: ShouldExposeSelfFeedbackIntentToolOptions,) => {if (!options.featureUserEnabled || !options.agentSelfIterationEnabled) return false;- if (options.disabled || options.disableSelfIterationIntentTool || options.reviewerRole) {+ if (options.disabled || options.disableSelfFeedbackIntentTool || options.reviewerRole) {return false;}@@ -51,11 +51,11 @@ export const shouldExposeSelfIterationIntentTool = (};/**- * Injects the self-iteration intent manifest and LLM tool into a tool set.+ * Injects the self-feedback 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+ * - The operation should expose advisory self-feedback intent as a builtin server tool** Expects:* - Caller has already checked visibility gates@@ -63,21 +63,21 @@ export const shouldExposeSelfIterationIntentTool = (* 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);+export const injectSelfFeedbackIntentTool = (toolSetParts: SelfFeedbackIntentToolSetParts) => {+ const wasAlreadyEnabled = toolSetParts.enabledToolIds.includes(SELF_FEEDBACK_INTENT_IDENTIFIER);const wasAlreadyVisible = toolSetParts.tools.some(- (tool) => tool.function.name === SELF_ITERATION_INTENT_TOOL_NAME,+ (tool) => tool.function.name === SELF_FEEDBACK_INTENT_TOOL_NAME,);- toolSetParts.manifestMap[SELF_ITERATION_INTENT_IDENTIFIER] = selfIterationIntentManifest;- toolSetParts.sourceMap[SELF_ITERATION_INTENT_IDENTIFIER] = 'builtin';+ toolSetParts.manifestMap[SELF_FEEDBACK_INTENT_IDENTIFIER] = selfFeedbackIntentManifest;+ toolSetParts.sourceMap[SELF_FEEDBACK_INTENT_IDENTIFIER] = 'builtin';if (!wasAlreadyEnabled) {- toolSetParts.enabledToolIds.push(SELF_ITERATION_INTENT_IDENTIFIER);+ toolSetParts.enabledToolIds.push(SELF_FEEDBACK_INTENT_IDENTIFIER);}if (!wasAlreadyVisible) {- toolSetParts.tools.push(...createSelfIterationIntentTool());+ toolSetParts.tools.push(...createSelfFeedbackIntentTool());}return !wasAlreadyEnabled || !wasAlreadyVisible;diff --git a/packages/builtin-tool-self-iteration/src/manifest.ts b/packages/builtin-tool-self-iteration/src/manifest.tsindex f622913c741..73b03fa05d5 100644--- a/packages/builtin-tool-self-iteration/src/manifest.ts+++ b/packages/builtin-tool-self-iteration/src/manifest.ts@@ -1,12 +1,12 @@import type { BuiltinToolManifest } from '@lobechat/types';-import { SELF_ITERATION_INTENT_API_NAME, SELF_ITERATION_INTENT_IDENTIFIER } from './types';+import { SELF_FEEDBACK_INTENT_API_NAME, SELF_FEEDBACK_INTENT_IDENTIFIER } from './types';/*** Self-iteration intent builtin tool manifest.** Use when:- * - A running agent may declare advisory maintenance intent+ * - A running agent may declare advisory self-feedback intent* - The runtime must expose a source-event boundary without direct resource mutation** Expects:@@ -15,22 +15,22 @@ import { SELF_ITERATION_INTENT_API_NAME, SELF_ITERATION_INTENT_IDENTIFIER } from* Returns:* - A manifest that can be registered as a hidden builtin tool*/-export const selfIterationIntentManifest = {+export const selfFeedbackIntentManifest = {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,+ 'Declare advisory self-feedback intent for future review. This only records intent and does not mutate memory or skills.',+ name: SELF_FEEDBACK_INTENT_API_NAME,parameters: {additionalProperties: false,properties: {action: {- description: 'Maintenance action the agent believes may be useful.',+ description: 'Self-iteration action the agent believes may be useful.',enum: ['write', 'create', 'refine', 'consolidate', 'proposal'],type: 'string',},kind: {- description: 'Maintenance target category for the declaration.',+ description: 'Self-iteration target category for the declaration.',enum: ['memory', 'skill', 'gap'],type: 'string',},@@ -41,11 +41,11 @@ export const selfIterationIntentManifest = {type: 'number',},summary: {- description: 'Short summary of the maintenance intent.',+ description: 'Short summary of the self-feedback intent.',type: 'string',},reason: {- description: 'Rationale for why this maintenance intent may be useful.',+ description: 'Rationale for why this self-feedback intent may be useful.',type: 'string',},evidenceRefs: {@@ -79,13 +79,13 @@ export const selfIterationIntentManifest = {},},],- identifier: SELF_ITERATION_INTENT_IDENTIFIER,+ identifier: SELF_FEEDBACK_INTENT_IDENTIFIER,meta: {description:- 'Let a running agent declare advisory self-iteration intent without mutating memory or skills directly.',- title: 'Self Iteration Intent',+ 'Let a running agent declare advisory self-feedback intent without mutating memory or skills directly.',+ title: 'Self Feedback 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.',+ 'Declare advisory self-feedback intent only when future self-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.tsindex 343ffb5d706..5926b3393e9 100644--- a/packages/builtin-tool-self-iteration/src/types.ts+++ b/packages/builtin-tool-self-iteration/src/types.ts@@ -1,20 +1,20 @@-/** Builtin identifier used to route self-iteration intent declarations. */-export const SELF_ITERATION_INTENT_IDENTIFIER = 'lobe-self-iteration-intent';+/** Builtin identifier used to route self-feedback intent declarations. */+export const SELF_FEEDBACK_INTENT_IDENTIFIER = 'lobe-self-feedback-intent';-/** Runtime API name used by the injected self-iteration intent tool. */-export const SELF_ITERATION_INTENT_API_NAME = 'declareSelfIterationIntent';+/** Runtime API name used by the injected self-feedback intent tool. */+export const SELF_FEEDBACK_INTENT_API_NAME = 'declareSelfFeedbackIntent';/** 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}`;+export const SELF_FEEDBACK_INTENT_TOOL_NAME = `${SELF_FEEDBACK_INTENT_IDENTIFIER}____${SELF_FEEDBACK_INTENT_API_NAME}`;/** Gate input used to decide whether the declaration tool may be exposed. */-export interface ShouldExposeSelfIterationIntentToolOptions {+export interface ShouldExposeSelfFeedbackIntentToolOptions {/** 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;+ disableSelfFeedbackIntentTool?: boolean;/** Server/user feature gate result, including user Labs eligibility. */featureUserEnabled: boolean;/** Reviewer paths must not receive the running-agent declaration tool. */diff --git a/packages/builtin-tools/src/identifiers.ts b/packages/builtin-tools/src/identifiers.tsindex 123eb86d00e..c01e0f6c253 100644--- a/packages/builtin-tools/src/identifiers.ts+++ b/packages/builtin-tools/src/identifiers.ts@@ -14,7 +14,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 { selfFeedbackIntentManifest } 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';@@ -37,7 +37,7 @@ export const builtinToolIdentifiers: string[] = [MemoryManifest.identifier,NotebookManifest.identifier,PageAgentManifest.identifier,- selfIterationIntentManifest.identifier,+ selfFeedbackIntentManifest.identifier,SkillsManifest.identifier,SkillStoreManifest.identifier,TopicReferenceManifest.identifier,diff --git a/packages/builtin-tools/src/index.ts b/packages/builtin-tools/src/index.tsindex ab95dc68801..3e5f01a9f98 100644--- a/packages/builtin-tools/src/index.ts+++ b/packages/builtin-tools/src/index.ts@@ -16,7 +16,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 { selfFeedbackIntentManifest } 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';@@ -123,8 +123,8 @@ export const builtinTools: LobeBuiltinTool[] = [{discoverable: false,hidden: true,- identifier: selfIterationIntentManifest.identifier,- manifest: selfIterationIntentManifest,+ identifier: selfFeedbackIntentManifest.identifier,+ manifest: selfFeedbackIntentManifest,type: 'builtin',},{diff --git a/packages/database/src/models/agentSignal/reviewContext.ts b/packages/database/src/models/agentSignal/reviewContext.tsindex 92e78b0b3c0..48b2145f79b 100644--- a/packages/database/src/models/agentSignal/reviewContext.ts+++ b/packages/database/src/models/agentSignal/reviewContext.ts@@ -136,7 +136,7 @@ export class AgentSignalReviewContextModel {.limit(options.limit);};- /** Lists grouped review-window tool activity for nightly maintenance context. */+ /** Lists grouped review-window tool activity for nightly self-iteration context. */listToolActivity = (options: ListAgentSignalActivityWindowOptions) => {const effectiveAgentId = sql<string>`COALESCE(${messages.agentId}, ${topics.agentId})`;@@ -158,7 +158,7 @@ export class AgentSignalReviewContextModel {`,sampleArgs: sql<string[]>`COALESCE(- jsonb_agg(DISTINCT left(${messagePlugins.arguments}::text, 500))+ jsonb_agg(DISTINCT left(${messagePlugins.arguments}::text, 2000))FILTER (WHERE ${messagePlugins.arguments} IS NOT NULL),'[]'::jsonb)@@ -197,7 +197,7 @@ export class AgentSignalReviewContextModel {.limit(20);};- /** Lists review-window agent document activity for nightly maintenance context. */+ /** Lists review-window agent document activity for nightly self-iteration context. */listDocumentActivity = (options: ListAgentSignalActivityWindowOptions) => {return this.db.select({diff --git a/packages/prompts/src/prompts/agentSignal/analyzeIntent/route.test.ts b/packages/prompts/src/prompts/agentSignal/analyzeIntent/route.test.tsindex 344125a8dc5..8c100cf1788 100644--- a/packages/prompts/src/prompts/agentSignal/analyzeIntent/route.test.ts+++ b/packages/prompts/src/prompts/agentSignal/analyzeIntent/route.test.ts@@ -10,7 +10,7 @@ import {describe('agent signal analyze-intent route prompt', () => {/*** @example- * Existing reusable checklist maintenance should route to skill, while prompt+ * Existing reusable checklist self-iteration should route to skill, while prompt* remains reserved for assistant self-rules.*/it('keeps prompt lane limited to assistant self-rules and routes reusable artifacts to skill', () => {diff --git a/packages/prompts/src/prompts/agentSignal/nightlyReview.test.ts b/packages/prompts/src/prompts/agentSignal/nightlyReview.test.tsindex 1ec58e2cf4e..6a6f9456b13 100644--- a/packages/prompts/src/prompts/agentSignal/nightlyReview.test.ts+++ b/packages/prompts/src/prompts/agentSignal/nightlyReview.test.ts@@ -8,9 +8,9 @@ import {describe('agent signal nightly review prompt', () => {/*** @example- * The prompt keeps automatic mutations constrained to explicit low-risk maintenance.+ * The prompt keeps automatic mutations constrained to explicit low-risk self-review.*/- it('documents the auto-apply boundary for nightly maintenance', () => {+ it('documents the auto-apply boundary for nightly self-review', () => {expect(AGENT_SIGNAL_NIGHTLY_REVIEW_SYSTEM_ROLE).toContain('Use noop for ordinary successful days',);@@ -30,12 +30,12 @@ describe('agent signal nightly review prompt', () => {/*** @example- * The prompt starts from maintenance signals and forbids model-side reclassification.+ * The prompt starts from structured self-review signals and forbids model-side reclassification.*/- it('documents the structured maintenance signal boundary', () => {- const [system] = createAgentSignalNightlyReviewMessages({ maintenanceSignals: [] });+ it('documents the structured self-review signal boundary', () => {+ const [system] = createAgentSignalNightlyReviewMessages({ selfReviewSignals: [] });- expect(system.content).toContain('Start from maintenanceSignals');+ expect(system.content).toContain('Start from selfReviewSignals');expect(system.content).toContain('proposalActivity');expect(system.content).toContain('Do not re-judge satisfaction');expect(system.content).toContain('Tool activity alone must not trigger skill consolidation');@@ -48,14 +48,14 @@ describe('agent signal nightly review prompt', () => {* @example* expect(prompt).toContain('write tools')*/- it('instructs nightly maintenance to use tools as the only mutation boundary', () => {- const prompt = createAgentSignalNightlyReviewMessages({ maintenanceSignals: [] })+ it('instructs nightly self-review to use tools as the only mutation boundary', () => {+ const prompt = createAgentSignalNightlyReviewMessages({ selfReviewSignals: [] }).map((message) => message.content).join('\n');expect(prompt).toContain('Mutations only count through write tools');expect(prompt).toContain(- 'this structured review may only emit candidate write actions for the server maintenance runtime',+ 'this structured review may only emit candidate write actions for the server self-review executor',);expect(prompt).toContain('Never infer intent with regexp, keyword lists, or hard-coded content heuristics',@@ -70,12 +70,12 @@ describe('agent signal nightly review prompt', () => {*/it('documents proposal lifecycle and mutation safety boundaries', () => {const [system] = createAgentSignalNightlyReviewMessages({- maintenanceSignals: [],+ selfReviewSignals: [],proposalActivity: { active: [] },});expect(system.content).toContain(- 'Existing maintenance proposals are state, not fresh evidence',+ 'Existing self-review proposals are state, not fresh evidence',);expect(system.content).toContain('Refresh a compatible pending proposal instead of creating a duplicate',@@ -90,7 +90,7 @@ describe('agent signal nightly review prompt', () => {expect(system.content).toContain('value.bodyMarkdown must contain the complete replacement Markdown body',);- expect(system.content).toContain('Proposal only: structural/destructive changes');+ expect(system.content).toContain('Self-review proposal only: structural/destructive changes');expect(system.content).toContain('Plan only mutations that can be routed through safe write tools',);diff --git a/packages/prompts/src/prompts/agentSignal/nightlyReview.ts b/packages/prompts/src/prompts/agentSignal/nightlyReview.tsindex 9fc4d653a84..3011e334462 100644--- a/packages/prompts/src/prompts/agentSignal/nightlyReview.ts+++ b/packages/prompts/src/prompts/agentSignal/nightlyReview.ts@@ -1,42 +1,42 @@-const TOOL_FIRST_MAINTENANCE_RULES = [- 'Role: maintenance operator, not summarizer.',- 'Mutations only count through write tools; this structured review may only emit candidate write actions for the server maintenance runtime.',+const TOOL_FIRST_SELF_ITERATION_RULES = [+ 'Role: self-review operator, not summarizer.',+ 'Mutations only count through write tools; this structured review may only emit candidate write actions for the server self-review executor.','Never infer intent with regexp, keyword lists, or hard-coded content heuristics.',- 'Use structured context only: maintenanceSignals, bounded evidence, read tool results, satisfaction, feedback, receipts, and proposal state.',+ 'Use structured context only: selfReviewSignals, bounded evidence, read tool results, satisfaction, feedback, receipts, and proposal state.','refine_skill requires complete replacement bodyMarkdown; do not emit patch-only or prose-only executable refinement payloads.','Auto-apply only safe writes: non-structural full-body refine_skill when fresh, or additive create_skill when absent, complete, scoped, and strongly supported.',- 'Proposal only: structural/destructive changes, active proposal refresh/supersede/close, deletion, move, rebind, split, merge, path/namespace/file-structure/activation changes. Use proposal_only only for non-actionable ideas or questions that should be retained, not applied.',+ 'Self-review proposal only: structural/destructive changes, active proposal refresh/supersede/close, deletion, move, rebind, split, merge, path/namespace/file-structure/activation changes. Use record_idea only for non-actionable ideas or questions that should be retained, not applied.',].join(' ');export const AGENT_SIGNAL_NIGHTLY_REVIEW_SYSTEM_ROLE = [- 'Review the bounded daily digest for one assistant. Return only safe maintenance actions.',- TOOL_FIRST_MAINTENANCE_RULES,- 'Start from maintenanceSignals; inspect other buckets only when cited or when confirming noop.',+ 'Review the bounded daily digest for one assistant. Return only safe self-review actions.',+ TOOL_FIRST_SELF_ITERATION_RULES,+ 'Start from selfReviewSignals; inspect other buckets only when cited or when confirming noop.','Use noop for ordinary successful days, weak/ambiguous evidence, or single-source telemetry; noop is silent and must not create a Daily Brief or proposal. Non-noop actions must cite digest evidenceRefs.','A durable_user_preference signal means the digest found explicit remember/future/preference language; it may produce write_memory when the candidate is stable, normal-sensitivity, and directly grounded in the cited topic or message.','Do not re-judge satisfaction, sentiment, or user intent; feedbackActivity is already judged evidence and is only one feature.','Tool activity alone must not trigger skill consolidation, creation, or refinement; it may support repeated workflow/failure signals only with document, feedback, topic, or receipt evidence.',- 'When maintenanceSignals include skill_document_with_tool_failure, inspect the cited skill documents and tool failures. If the cited evidence is related, return exactly one proposal_only or refine_skill action with the target skillDocumentId; do not return noop for related cited evidence.',- 'documentActivity.skillBucket and hintIsSkill:true are primary evidence for skill maintenance, not automatic authorization; generalDocumentBucket cannot independently trigger skill maintenance.',- 'Use proposalActivity for unresolved proposal refresh, stale proposal, duplicate proposal checks, suppress, supersede, expire, or lifecycle explanation. Existing maintenance proposals are state, not fresh evidence.',- 'Use receiptActivity for already-applied or dismissed maintenance outcomes. If a related pending proposal exists, prefer noop or explain that the existing proposal should remain pending.',+ 'When selfReviewSignals include skill_document_with_tool_failure, inspect the cited skill documents and tool failures. If the cited evidence is related, return exactly one record_idea or refine_skill action with the target skillDocumentId; do not return noop for related cited evidence.',+ 'documentActivity.skillBucket and hintIsSkill:true are primary evidence for skill self-review, not automatic authorization; generalDocumentBucket cannot independently trigger skill self-review.',+ 'Use proposalActivity for unresolved proposal refresh, stale proposal, duplicate proposal checks, suppress, supersede, expire, or lifecycle explanation. Existing self-review proposals are state, not fresh evidence.',+ 'Use receiptActivity for already-applied or dismissed self-iteration outcomes. If a related pending proposal exists, prefer noop or explain that the existing proposal should remain pending.','Refresh a compatible pending proposal instead of creating a duplicate when new evidence supports the same target and action.','Supersede an incompatible pending proposal when the same proposalKey now needs a materially different operation.',- 'Do not use old proposal content as the only evidence for a mutation; every non-noop action must cite fresh maintenanceSignals or supporting buckets.',+ 'Do not use old proposal content as the only evidence for a mutation; every non-noop action must cite fresh selfReviewSignals or supporting buckets.','If a related proposal is stale or expired, do not apply it. Either return noop or create a fresh proposal only when current evidence supports it.','Broad in-document rewrites can be auto-applied when they preserve resource identity, file structure, binding, activation path, and target freshness.','For auto-applied skill refinement, value.bodyMarkdown must contain the complete replacement Markdown body without YAML frontmatter. Do not put instruction-only text in patch for automatic refinement.','Plan only mutations that can be routed through safe write tools; every write tool performs freshness and idempotency checks and emits a receipt.','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 should be proposal_only unless the evidence shows explicit maintenance intent and a small targeted change. Skill refinement can be auto-applied for explicit small changes or broad in-document rewrites that preserve resource identity. Consolidation must be proposed with a frozen consolidate_skill operation and must not be auto-applied.',+ '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 record_idea or noop.',+ 'Skill creation should be a self-review proposal unless the evidence shows explicit self-feedback intent and a small targeted change. Skill refinement can be auto-applied for explicit small changes or broad in-document rewrites that preserve resource identity. Consolidation must be proposed with a frozen consolidate_skill operation and must not be auto-applied.',].join(' ');/**- * Builds model messages for Agent Signal nightly maintenance review.+ * Builds model messages for Agent Signal nightly self-review.** Use when:- * - A server reviewer asks the model to convert a bounded digest into maintenance drafts+ * - A server reviewer asks the model to convert a bounded digest into self-review drafts* - Tests need the stable prompt contract without importing server runtime code** Expects:diff --git a/src/features/Conversation/ChatList/components/AgentSignalReceiptList.tsx b/src/features/Conversation/ChatList/components/AgentSignalReceiptList.tsxindex 3a0282c715a..c4a6a07e22d 100644--- a/src/features/Conversation/ChatList/components/AgentSignalReceiptList.tsx+++ b/src/features/Conversation/ChatList/components/AgentSignalReceiptList.tsx@@ -2,7 +2,7 @@import { createStaticStyles } from 'antd-style';import type { LucideIcon } from 'lucide-react';-import { Brain, ClipboardCheck, FileText, Wrench } from 'lucide-react';+import { Brain, ClipboardCheck, FileText } from 'lucide-react';import { memo, useCallback } from 'react';import { useTranslation } from 'react-i18next';@@ -26,7 +26,6 @@ const styles = createStaticStyles(({ css }) => ({}));const RECEIPT_ICON_BY_KIND = {- maintenance: Wrench,memory: Brain,review: ClipboardCheck,skill: FileText,diff --git a/src/server/routers/lambda/brief.ts b/src/server/routers/lambda/brief.tsindex 36131002f20..811f450ebe9 100644--- a/src/server/routers/lambda/brief.ts+++ b/src/server/routers/lambda/brief.ts@@ -6,7 +6,7 @@ import { TaskModel } from '@/database/models/task';import { authedProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { AgentSignalSelfReviewBriefService } from '@/server/services/agentSignal/services/briefs/selfReview';-import { NIGHTLY_REVIEW_BRIEF_TRIGGER } from '@/server/services/agentSignal/services/maintenance/brief';+import { NIGHTLY_REVIEW_BRIEF_TRIGGER } from '@/server/services/agentSignal/services/selfIteration/review/brief';import { BriefService } from '@/server/services/brief';const briefProcedure = authedProcedure.use(serverDatabase);diff --git a/src/server/services/agentSignal/__tests__/orchestrator.test.ts b/src/server/services/agentSignal/__tests__/orchestrator.test.tsindex e7330565df1..7c3b5b266ce 100644--- a/src/server/services/agentSignal/__tests__/orchestrator.test.ts+++ b/src/server/services/agentSignal/__tests__/orchestrator.test.ts@@ -5,13 +5,9 @@ import { BriefModel } from '@/database/models/brief';import type { AgentSignalEmitOptions } from '../emitter';import { withServerAgentSignalPolicyDefaults } from '../orchestrator';-import { createBriefMaintenanceService } from '../services/maintenance/brief';-import type { NightlyReviewContext } from '../services/maintenance/nightlyCollector';-import {- MaintenanceActionStatus,- MaintenanceReviewScope,- ReviewRunStatus,-} from '../services/maintenance/types';+import { createBriefSelfReviewService } from '../services/selfIteration/review/brief';+import type { NightlyReviewContext } from '../services/selfIteration/review/collect';+import { ActionStatus, ReviewRunStatus, Scope } from '../services/selfIteration/types';const createNightlyReviewContext = (): NightlyReviewContext => ({agentId: 'agent-1',@@ -26,7 +22,7 @@ const createNightlyReviewContext = (): NightlyReviewContext => ({notSatisfied: [],satisfied: [],},- maintenanceSignals: [],+ selfReviewSignals: [],managedSkills: [],proposalActivity: {active: [],@@ -46,6 +42,7 @@ const createNightlyReviewContext = (): NightlyReviewContext => ({relevantMemories: [],reviewWindowEnd: '2026-05-04T14:30:00.000Z',reviewWindowStart: '2026-05-03T16:00:00.000Z',+ selfFeedbackCandidates: [],toolActivity: [],topics: [],userId: 'user-1',@@ -57,7 +54,7 @@ const createNightlyReviewOptions = (): NonNullable<acquireReviewGuard: vi.fn(async () => true),canRunReview: vi.fn(async () => true),collectContext: vi.fn(async () => createNightlyReviewContext()),- runMaintenanceReviewAgent: vi.fn(async () => ({+ runSelfReviewAgent: vi.fn(async () => ({execution: {actions: [],status: ReviewRunStatus.Completed,@@ -65,7 +62,7 @@ const createNightlyReviewOptions = (): NonNullable<projectionPlan: {actions: [],plannerVersion: 'test',- reviewScope: MaintenanceReviewScope.Nightly,+ reviewScope: Scope.Nightly,summary: 'Quiet night.',},})),@@ -100,7 +97,7 @@ describe('Agent Signal orchestrator policy defaults', () => {id: 'brief-1',metadata: {},priority: 'info',- summary: '1 maintenance update applied.',+ summary: '1 self-iteration update applied.',title: 'Agent self-review updated resources',trigger: 'agent-signal:nightly-review',type: 'insight',@@ -112,7 +109,7 @@ describe('Agent Signal orchestrator policy defaults', () => {},{ db: {} as never, userId: 'user-1' },);- const brief = createBriefMaintenanceService().projectNightlyReviewBrief({+ const brief = createBriefSelfReviewService().projectNightlyReviewBrief({agentId: 'agent-1',localDate: '2026-05-04',result: {@@ -120,7 +117,7 @@ describe('Agent Signal orchestrator policy defaults', () => {{idempotencyKey: 'source:write_memory:memory:concise',receiptId: 'receipt-1',- status: MaintenanceActionStatus.Applied,+ status: ActionStatus.Applied,summary: 'Saved concise PR summary preference.',},],diff --git a/src/server/services/agentSignal/orchestrator.ts b/src/server/services/agentSignal/orchestrator.tsindex ad1552c70bb..56bc41bdf73 100644--- a/src/server/services/agentSignal/orchestrator.ts+++ b/src/server/services/agentSignal/orchestrator.ts@@ -22,8 +22,8 @@ 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 { createServerSelfReviewBriefWriter } from './services/selfIteration/review/brief';import { emitSourceEvent } from './sources';import { redisPolicyStateStore } from './store/adapters/redis/policyStateStore';import type { AgentSignalReceiptStore, AgentSignalSourceEventStore } from './store/types';@@ -92,7 +92,7 @@ const buildRuntimeOrchestrationResult = (};/**- * Adds server defaults to optional Agent Signal maintenance policy options.+ * Adds server defaults to optional Agent Signal self-iteration policy options.** Use when:* - A caller already installed nightly review options but omitted the brief writer@@ -112,7 +112,7 @@ export const withServerAgentSignalPolicyDefaults = (return policyOptions;}- const briefWriter = createServerMaintenanceBriefWriter(context.db, context.userId);+ const briefWriter = createServerSelfReviewBriefWriter(context.db, context.userId);return {...policyOptions,@@ -144,7 +144,7 @@ const createPolicyOptions = (classifierDiagnostics: policyOptions?.classifierDiagnostics,nightlyReview: policyOptions?.nightlyReview,procedure: procedurePolicyOptions,- selfIterationIntent: policyOptions?.selfIterationIntent,+ selfFeedbackIntent: policyOptions?.selfFeedbackIntent,selfReflection: policyOptions?.selfReflection,userMemory: {db: context.db,diff --git a/src/server/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts b/src/server/services/agentSignal/policies/analyzeIntent/actions/skillManagement.tsindex e501d090d22..189f7e4a67c 100644--- a/src/server/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts+++ b/src/server/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts@@ -55,7 +55,7 @@ import type {import type { RuntimeProcessorContext } from '../../../runtime/context';import { defineActionHandler } from '../../../runtime/middleware';-import { createSkillManagementService } from '../../../services/maintenance/skill';+import { createSkillManagementService } from '../../../services/selfIteration/tools/shared';import type { ProcedureStateService } from '../../../services/types';import { hasAppliedActionIdempotency, markAppliedActionIdempotency } from '../../actionIdempotency';import type { ActionSkillManagementHandle, AgentSignalFeedbackEvidence } from '../../types';@@ -1504,7 +1504,7 @@ const runMaintainerWorkflow = async (let updatedSkill: SkillDetail | SkillSummary = canonical;try {- const skillMaintenanceService = createSkillManagementService({+ const selfIterationSkillService = createSkillManagementService({consolidateSkill: async () => {if (workflowResult.rename?.newName || workflowResult.rename?.newTitle) {updatedSkill =@@ -1560,7 +1560,7 @@ const runMaintainerWorkflow = async (});if (decision.action === 'consolidate') {- await skillMaintenanceService.consolidateSkill({+ await selfIterationSkillService.consolidateSkill({evidenceRefs: [],idempotencyKey: `same-turn-skill:${canonical.bundle.agentDocumentId}`,input: {@@ -1571,7 +1571,7 @@ const runMaintainerWorkflow = async (},});} else {- await skillMaintenanceService.refineSkill({+ await selfIterationSkillService.refineSkill({evidenceRefs: [],idempotencyKey: `same-turn-skill:${canonical.bundle.agentDocumentId}`,input: {@@ -1658,7 +1658,7 @@ const runCreateWorkflow = async (try {let createdSkill: SkillDetail | undefined;- const skillMaintenanceService = createSkillManagementService({+ const selfIterationSkillService = createSkillManagementService({createSkill: async () => {const skill = await service.createSkill({agentId,@@ -1676,7 +1676,7 @@ const runCreateWorkflow = async (};},});- await skillMaintenanceService.createSkill({+ await selfIterationSkillService.createSkill({evidenceRefs: [],idempotencyKey: `same-turn-skill:create:${authored.name}`,input: {diff --git a/src/server/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts b/src/server/services/agentSignal/policies/analyzeIntent/actions/userMemory.tsindex 81566e097ea..9247cdbedc1 100644--- a/src/server/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts+++ b/src/server/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts@@ -26,9 +26,9 @@ import { AgentService } from '@/server/services/agent';import type { RuntimeProcessorContext } from '../../../runtime/context';import { defineActionHandler } from '../../../runtime/middleware';import {- createMemoryMaintenanceService,- MemoryMaintenanceActionError,-} from '../../../services/maintenance/memory';+ createMemoryService,+ MemoryActionError,+} from '../../../services/selfIteration/tools/shared';import { hasAppliedActionIdempotency, markAppliedActionIdempotency } from '../../actionIdempotency';import type {ActionUserMemoryHandle,@@ -421,7 +421,7 @@ export const handleUserMemoryAction = async (topicId: typeof action.payload.topicId === 'string' ? action.payload.topicId : undefined,};const runner = options.memoryActionRunner ?? ((input) => runMemoryActionAgent(input, options));- const memoryService = createMemoryMaintenanceService({+ const memoryService = createMemoryService({writeMemory: async () => {const result = await runner(runnerInput);@@ -432,7 +432,7 @@ export const handleUserMemoryAction = async (};}- throw new MemoryMaintenanceActionError(+ throw new MemoryActionError(result.detail ?? 'Memory action agent did not apply a durable memory write.',result.status,);@@ -453,7 +453,7 @@ export const handleUserMemoryAction = async (status: 'applied',})).catch((error: unknown): MemoryAgentActionResult => {- if (error instanceof MemoryMaintenanceActionError) {+ if (error instanceof MemoryActionError) {return {detail: error.message,status: error.status,diff --git a/src/server/services/agentSignal/policies/index.ts b/src/server/services/agentSignal/policies/index.tsindex de5282b6407..fc3cdee622b 100644--- a/src/server/services/agentSignal/policies/index.ts+++ b/src/server/services/agentSignal/policies/index.ts@@ -25,7 +25,7 @@ export interface CreateDefaultAgentSignalPoliciesOptions extends CreateFeedbackDfeedbackSatisfactionJudge?: CreateFeedbackSatisfactionJudgePolicyOptions;nightlyReview?: CreateReviewNightlyPolicyOptions['nightlyReview'];procedure?: CreateAnalyzeIntentPolicyOptions['procedure'];- selfIterationIntent?: CreateReviewNightlyPolicyOptions['selfIterationIntent'];+ selfFeedbackIntent?: CreateReviewNightlyPolicyOptions['selfFeedbackIntent'];selfReflection?: CreateReviewNightlyPolicyOptions['selfReflection'];skillIntentClassifier?: CreateAnalyzeIntentPolicyOptions['skillIntentClassifier'];skillManagement?: SkillManagementActionHandlerOptions;@@ -41,21 +41,21 @@ const DEFAULT_AGENT_SIGNAL_POLICY_FACTORIES: DefaultAgentSignalPolicyFactory[] =(options) =>createReviewNightlyPolicy({nightlyReview: options.nightlyReview,- selfIterationIntent: options.selfIterationIntent,+ selfFeedbackIntent: options.selfFeedbackIntent,selfReflection: options.selfReflection,}),];/**- * Creates the default Agent Signal policy stack with optional maintenance source handlers.+ * Creates the default Agent Signal policy stack with optional self-iteration 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+ * - Callers want to opt into nightly self-review, self-reflection, or self-feedback handlers* with explicit handler options** Expects:- * - Optional maintenance options are complete bundles for their source handlers+ * - Optional self-iteration options are complete bundles for their source handlers* - Missing optional options mean the corresponding source handler is not installed** Returns:diff --git a/src/server/services/agentSignal/policies/reviewNightly/__tests__/selfIterationIntent.test.ts b/src/server/services/agentSignal/policies/reviewNightly/__tests__/selfIterationIntent.test.tsdeleted file mode 100644index f423b5f4957..00000000000--- a/src/server/services/agentSignal/policies/reviewNightly/__tests__/selfIterationIntent.test.ts+++ /dev/null@@ -1,574 +0,0 @@-// @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/index.ts b/src/server/services/agentSignal/policies/reviewNightly/index.tsindex 1d39e7859f1..2261e361a50 100644--- a/src/server/services/agentSignal/policies/reviewNightly/index.ts+++ b/src/server/services/agentSignal/policies/reviewNightly/index.ts@@ -1,11 +1,11 @@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';+import type { CreateSelfFeedbackIntentSourceHandlerDependencies } from '../../services/selfIteration/feedback/handler';+import { createSelfFeedbackIntentSourcePolicyHandler } from '../../services/selfIteration/feedback/handler';+import type { CreateSelfReflectionSourceHandlerDependencies } from '../../services/selfIteration/reflection/handler';+import { createSelfReflectionSourcePolicyHandler } from '../../services/selfIteration/reflection/handler';+import type { CreateNightlyReviewSourceHandlerDependencies } from '../../services/selfIteration/review/handler';+import { createNightlyReviewSourcePolicyHandler } from '../../services/selfIteration/review/handler';const createOptionalSourceHandler = <TOptions>(options: TOptions | undefined,@@ -13,23 +13,23 @@ const createOptionalSourceHandler = <TOptions>() => (options ? [create(options)] : []);/**- * Options for composing review-nightly maintenance source handlers.+ * Options for composing review-nightly self-iteration source handlers.*/export interface CreateReviewNightlyPolicyOptions {/** Optional nightly review source handler options. */nightlyReview?: CreateNightlyReviewSourceHandlerDependencies;- /** Optional self-iteration intent source handler options. */- selfIterationIntent?: CreateSelfIterationIntentSourceHandlerDependencies;+ /** Optional self-feedback intent source handler options. */+ selfFeedbackIntent?: CreateSelfFeedbackIntentSourceHandlerDependencies;/** Optional self-reflection source handler options. */selfReflection?: CreateSelfReflectionSourceHandlerDependencies;}/**- * Creates the Agent Signal policy slice for deferred maintenance reviews.+ * Creates the Agent Signal policy slice for deferred self-iteration 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+ * - Runtime creation wants self-reflection or self-feedback intent handlers in the same domain** Expects:* - Each optional handler option bundle is complete for its corresponding source handler@@ -45,14 +45,14 @@ export const createReviewNightlyPolicy = (...createOptionalSourceHandler(options.nightlyReview, createNightlyReviewSourcePolicyHandler),...createOptionalSourceHandler(options.selfReflection, createSelfReflectionSourcePolicyHandler),...createOptionalSourceHandler(- options.selfIterationIntent,- createSelfIterationIntentSourcePolicyHandler,+ options.selfFeedbackIntent,+ createSelfFeedbackIntentSourcePolicyHandler,),];return handlers.length > 0 ? [defineAgentSignalHandlers(handlers)] : [];};-export * from './nightlyReview';-export * from './selfIterationIntent';-export * from './selfReflection';+export * from '../../services/selfIteration/feedback/handler';+export * from '../../services/selfIteration/reflection/handler';+export * from '../../services/selfIteration/review/handler';diff --git a/src/server/services/agentSignal/policies/reviewNightly/selfIterationIntent.ts b/src/server/services/agentSignal/policies/reviewNightly/selfIterationIntent.tsdeleted file mode 100644index 7834df86bd5..00000000000--- a/src/server/services/agentSignal/policies/reviewNightly/selfIterationIntent.ts+++ /dev/null@@ -1,668 +0,0 @@-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/services/__tests__/receiptService.selfReflect.test.ts b/src/server/services/agentSignal/services/__tests__/receiptService.selfReflect.test.tsindex 7b0cb218797..6d3022a7086 100644--- a/src/server/services/agentSignal/services/__tests__/receiptService.selfReflect.test.ts+++ b/src/server/services/agentSignal/services/__tests__/receiptService.selfReflect.test.ts@@ -2,21 +2,15 @@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';+import { createReviewSummaryReceipt, createSelfReviewActionReceipt } from '../receiptService';+import type { ActionResult, Plan } from '../selfIteration/types';+import { ActionStatus, ApplyMode, ReviewRunStatus, Risk, Scope } from '../selfIteration/types';const nightlyPlan = {actions: [{actionType: 'write_memory',- applyMode: MaintenanceApplyMode.AutoApply,+ applyMode: ApplyMode.AutoApply,confidence: 0.93,dedupeKey: 'memory:concise',evidenceRefs: [{ id: 'topic-1', summary: 'User prefers concise summaries.', type: 'topic' }],@@ -27,23 +21,23 @@ const nightlyPlan = {operation: 'write',},rationale: 'Stable preference found in the review window.',- risk: MaintenanceRisk.Low,+ risk: Risk.Low,target: { topicIds: ['topic-1'] },},],localDate: '2026-05-04',plannerVersion: 'test-planner',- reviewScope: MaintenanceReviewScope.Nightly,+ reviewScope: Scope.Nightly,summary: 'Saved one stable preference.',-} satisfies MaintenancePlan;+} satisfies Plan;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,+ status: ActionStatus.Applied,summary: 'Memory written.',-} satisfies MaintenanceActionResult;+} satisfies ActionResult;describe('createReviewSummaryReceipt', () => {/**@@ -78,7 +72,7 @@ describe('createReviewSummaryReceipt', () => {expect(receipt.metadata).toMatchObject({actionCount: 1,localDate: '2026-05-04',- reviewScope: MaintenanceReviewScope.Nightly,+ reviewScope: Scope.Nightly,sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentNightlyReviewRequested,timezone: 'Asia/Shanghai',});@@ -92,7 +86,7 @@ describe('createReviewSummaryReceipt', () => {const receipt = createReviewSummaryReceipt({agentId: 'agent-1',createdAt: 1_700_000,- plan: { ...nightlyPlan, reviewScope: MaintenanceReviewScope.SelfReflection },+ plan: { ...nightlyPlan, reviewScope: Scope.SelfReflection },result: { actions: [actionResult], status: ReviewRunStatus.Completed },scopeId: 'topic-1',scopeType: 'topic',@@ -104,26 +98,26 @@ describe('createReviewSummaryReceipt', () => {expect(receipt.topicId).toBe('topic-1');expect(receipt.metadata).toMatchObject({- reviewScope: MaintenanceReviewScope.SelfReflection,+ reviewScope: Scope.SelfReflection,scopeId: 'topic-1',scopeType: 'topic',});});});-describe('createMaintenanceActionReceipt', () => {+describe('createSelfReviewActionReceipt', () => {/*** @example- * Applied and proposed maintenance actions become durable action receipts.+ * Applied and proposed self-review actions become durable action receipts.*/- it('projects applied maintenance actions with action metadata and target resource', () => {- const receipt = createMaintenanceActionReceipt({+ it('projects applied self-review actions with action metadata and target resource', () => {+ const receipt = createSelfReviewActionReceipt({action: nightlyPlan.actions[0],agentId: 'agent-1',createdAt: 1_700_001,localDate: '2026-05-04',result: actionResult,- reviewScope: MaintenanceReviewScope.Nightly,+ reviewScope: Scope.Nightly,sourceId: 'nightly-review:user-1:agent-1:2026-05-04',sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentNightlyReviewRequested,timezone: 'Asia/Shanghai',@@ -142,27 +136,27 @@ describe('createMaintenanceActionReceipt', () => {},});expect(receipt?.metadata).toMatchObject({- actionStatus: MaintenanceActionStatus.Applied,+ actionStatus: ActionStatus.Applied,actionType: 'write_memory',localDate: '2026-05-04',- reviewScope: MaintenanceReviewScope.Nightly,+ reviewScope: Scope.Nightly,});});/*** @example- * Skipped maintenance actions do not create action receipts.+ * Skipped self-review actions do not create action receipts.*/it('does not project skipped action receipts', () => {expect(- createMaintenanceActionReceipt({+ createSelfReviewActionReceipt({action: nightlyPlan.actions[0],agentId: 'agent-1',result: {idempotencyKey: actionResult.idempotencyKey,- status: MaintenanceActionStatus.Skipped,+ status: ActionStatus.Skipped,},- reviewScope: MaintenanceReviewScope.Nightly,+ reviewScope: Scope.Nightly,sourceId: 'nightly-review:user-1:agent-1:2026-05-04',sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentNightlyReviewRequested,userId: 'user-1',diff --git a/src/server/services/agentSignal/services/__tests__/selfIterationIntent.test.ts b/src/server/services/agentSignal/services/__tests__/selfFeedbackIntent.test.tssimilarity index 83%rename from src/server/services/agentSignal/services/__tests__/selfIterationIntent.test.tsrename to src/server/services/agentSignal/services/__tests__/selfFeedbackIntent.test.tsindex 681f2809ee7..70c94b657e0 100644--- a/src/server/services/agentSignal/services/__tests__/selfIterationIntent.test.ts+++ b/src/server/services/agentSignal/services/__tests__/selfFeedbackIntent.test.ts@@ -2,8 +2,8 @@ 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';+import type { SelfFeedbackIntentAction, SelfFeedbackIntentKind } from '../selfFeedbackIntent';+import { createSelfFeedbackIntentService } from '../selfFeedbackIntent';const createStrongIntentInput = () => ({action: 'refine' as const,@@ -18,19 +18,19 @@ const createEnqueueSource = () =>vi.fn<(- input: AgentSignalSourceEventInput<'agent.self_iteration_intent.declared'>,+ input: AgentSignalSourceEventInput<'agent.self_feedback_intent.declared'>,) => Promise<unknown>>().mockResolvedValue({ enqueued: true });-describe('selfIterationIntent', () => {+describe('selfFeedbackIntent', () => {/*** @example- * declareSelfIterationIntent emits a source and does not mutate resources.+ * declareSelfFeedbackIntent emits a source and does not mutate resources.*/it('emits declared intent source events', async () => {const enqueueSource = createEnqueueSource();- const service = createSelfIterationIntentService({+ const service = createSelfFeedbackIntentService({enqueueSource,nextToolCallId: () => 'tool-call-1',});@@ -44,7 +44,7 @@ describe('selfIterationIntent', () => {expect(result).toEqual({accepted: true,- sourceId: 'self-iteration-intent:user-1:agent-1:topic:topic-1:tool-call-1',+ sourceId: 'self-feedback-intent:user-1:agent-1:topic:topic-1:tool-call-1',strength: 'strong',});expect(enqueueSource).toHaveBeenCalledWith({@@ -61,8 +61,8 @@ describe('selfIterationIntent', () => {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',+ sourceId: 'self-feedback-intent:user-1:agent-1:topic:topic-1:tool-call-1',+ sourceType: 'agent.self_feedback_intent.declared',});});@@ -71,7 +71,7 @@ describe('selfIterationIntent', () => {* Empty evidence is accepted as a source but marked weak for downstream downgrade.*/it('marks evidence-poor declarations as weak', async () => {- const service = createSelfIterationIntentService({+ const service = createSelfFeedbackIntentService({enqueueSource: createEnqueueSource(),nextToolCallId: () => 'tool-call-1',});@@ -98,7 +98,7 @@ describe('selfIterationIntent', () => {*/it('rate limits after three accepted declarations in one topic scope', async () => {const enqueueSource = createEnqueueSource();- const service = createSelfIterationIntentService({+ const service = createSelfFeedbackIntentService({enqueueSource,nextToolCallId: vi.fn()@@ -138,7 +138,7 @@ describe('selfIterationIntent', () => {it('uses explicit toolCallId without calling nextToolCallId', async () => {const nextToolCallId = vi.fn(() => 'generated-tool-call');const enqueueSource = createEnqueueSource();- const service = createSelfIterationIntentService({+ const service = createSelfFeedbackIntentService({enqueueSource,nextToolCallId,});@@ -152,7 +152,7 @@ describe('selfIterationIntent', () => {userId: 'user-1',}),).resolves.toMatchObject({- sourceId: 'self-iteration-intent:user-1:agent-1:topic:topic-1:explicit-tool-call',+ sourceId: 'self-feedback-intent:user-1:agent-1:topic:topic-1:explicit-tool-call',});expect(nextToolCallId).not.toHaveBeenCalled();@@ -164,7 +164,7 @@ describe('selfIterationIntent', () => {*/it('rejects invalid action kind and confidence declarations', async () => {const enqueueSource = createEnqueueSource();- const service = createSelfIterationIntentService({+ const service = createSelfFeedbackIntentService({enqueueSource,nextToolCallId: () => 'tool-call-1',});@@ -174,7 +174,7 @@ describe('selfIterationIntent', () => {agentId: 'agent-1',input: {...createStrongIntentInput(),- action: 'delete' as unknown as SelfIterationIntentAction,+ action: 'delete' as unknown as SelfFeedbackIntentAction,},topicId: 'topic-1',userId: 'user-1',@@ -185,7 +185,7 @@ describe('selfIterationIntent', () => {agentId: 'agent-1',input: {...createStrongIntentInput(),- kind: 'preference' as unknown as SelfIterationIntentKind,+ kind: 'preference' as unknown as SelfFeedbackIntentKind,},topicId: 'topic-1',userId: 'user-1',@@ -207,7 +207,7 @@ describe('selfIterationIntent', () => {agentId: 'agent-1',input: {...createStrongIntentInput(),- action: 'delete' as unknown as SelfIterationIntentAction,+ action: 'delete' as unknown as SelfFeedbackIntentAction,confidence: Number.NaN,},topicId: 'topic-1',@@ -223,7 +223,7 @@ describe('selfIterationIntent', () => {*/it('uses operationId as the rate-limit scope when present', async () => {const enqueueSource = createEnqueueSource();- const service = createSelfIterationIntentService({+ const service = createSelfFeedbackIntentService({enqueueSource,nextToolCallId: vi.fn()@@ -258,7 +258,7 @@ describe('selfIterationIntent', () => {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',+ sourceId: 'self-feedback-intent:user-1:agent-1:operation:operation-1:op-tool-call-1',scopeKey: 'operation:operation-1',}),);@@ -270,7 +270,7 @@ describe('selfIterationIntent', () => {*/it('includes operation or topic scope identity in source ids', async () => {const enqueueSource = createEnqueueSource();- const service = createSelfIterationIntentService({+ const service = createSelfFeedbackIntentService({enqueueSource,nextToolCallId: () => 'shared-tool-call',});@@ -290,10 +290,10 @@ describe('selfIterationIntent', () => {});expect(operationResult.sourceId).toBe(- 'self-iteration-intent:user-1:agent-1:operation:operation-1:shared-tool-call',+ 'self-feedback-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',+ 'self-feedback-intent:user-1:agent-1:topic:topic-1:shared-tool-call',);expect(operationResult.sourceId).not.toBe(topicResult.sourceId);});@@ -304,12 +304,12 @@ describe('selfIterationIntent', () => {*/it('honors declaration and enqueue gates', async () => {const enqueueSource = createEnqueueSource();- const blockedDeclarationService = createSelfIterationIntentService({+ const blockedDeclarationService = createSelfFeedbackIntentService({canDeclareIntent: vi.fn().mockResolvedValue(false),enqueueSource,nextToolCallId: () => 'tool-call-1',});- const blockedEnqueueService = createSelfIterationIntentService({+ const blockedEnqueueService = createSelfFeedbackIntentService({canEnqueue: vi.fn().mockResolvedValue(false),enqueueSource,nextToolCallId: () => 'tool-call-1',@@ -337,7 +337,7 @@ describe('selfIterationIntent', () => {).resolves.toEqual({accepted: false,reason: 'enqueue_gate_rejected',- sourceId: 'self-iteration-intent:user-1:agent-1:topic:topic-1:tool-call-1',+ sourceId: 'self-feedback-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/briefs/selfReview.test.ts b/src/server/services/agentSignal/services/briefs/selfReview.test.tsindex 082771da1cc..6c698196ee5 100644--- a/src/server/services/agentSignal/services/briefs/selfReview.test.ts+++ b/src/server/services/agentSignal/services/briefs/selfReview.test.ts@@ -8,8 +8,8 @@ import {AgentSignalSelfReviewBriefService,type AgentSignalSelfReviewBriefServiceOptions,} from '@/server/services/agentSignal/services/briefs/selfReview';-import { NIGHTLY_REVIEW_BRIEF_TRIGGER } from '@/server/services/agentSignal/services/maintenance/brief';-import { MaintenanceRisk } from '@/server/services/agentSignal/services/maintenance/types';+import { NIGHTLY_REVIEW_BRIEF_TRIGGER } from '@/server/services/agentSignal/services/selfIteration/review/brief';+import { Risk } from '@/server/services/agentSignal/services/selfIteration/types';const mockCanAgentRunSelfIteration = vi.hoisted(() => vi.fn());const mockIsAgentSignalEnabledForUser = vi.hoisted(() => vi.fn());@@ -53,7 +53,7 @@ vi.mock('@/server/services/agentSignal/featureGate', () => ({}));vi.mock('@/server/services/agentSignal/services/receiptService', () => ({- createMaintenanceReviewReceipts: vi.fn(() => []),+ createSelfReviewReceipts: vi.fn(() => []),persistAgentSignalReceipts: mockPersistAgentSignalReceipts,}));@@ -86,7 +86,7 @@ describe('AgentSignalSelfReviewBriefService', () => {evidenceRefs: [],idempotencyKey: 'nightly:refine:adoc_1',rationale: 'Refine a managed skill.',- risk: MaintenanceRisk.Medium,+ risk: Risk.Medium,},],createdAt: '2026-05-09T00:00:00.000Z',@@ -98,6 +98,13 @@ describe('AgentSignalSelfReviewBriefService', () => {updatedAt: '2026-05-09T00:00:00.000Z',version: 1 as const,};+ const proposalBriefMetadata = (proposal: unknown = proposalMetadata) => ({+ agentSignal: {+ nightlySelfReview: {+ selfReviewProposal: proposal,+ },+ },+ });beforeEach(() => {vi.clearAllMocks();@@ -119,16 +126,16 @@ describe('AgentSignalSelfReviewBriefService', () => {mockWriteWindow.mockResolvedValue(undefined);});- const resolveWithMaintenanceProposal = async (+ const resolveWithSelfReviewProposal = async (id: string,options?: { action?: string; comment?: string },- maintenanceProposalResolver?: AgentSignalSelfReviewBriefServiceOptions['maintenanceProposalResolver'],+ selfReviewProposalResolver?: AgentSignalSelfReviewBriefServiceOptions['selfReviewProposalResolver'],) => {const brief = (await mockBriefModel.findById(id)) as BriefItem | null;if (!brief) return null;return new AgentSignalSelfReviewBriefService(db, userId, {- maintenanceProposalResolver,+ selfReviewProposalResolver,}).resolve(brief, options);};@@ -136,25 +143,25 @@ describe('AgentSignalSelfReviewBriefService', () => {* @example* expect(mockBriefModel.resolve).toHaveBeenCalledWith('proposal-1', { action: 'approve' });*/- it('applies a pending maintenance proposal before resolving an approved brief', async () => {- const maintenanceProposalResolver = vi.fn().mockResolvedValue({+ it('applies a pending self-review proposal before resolving an approved brief', async () => {+ const selfReviewProposalResolver = vi.fn().mockResolvedValue({brief: { id: 'proposal-1' },shouldResolve: true,});mockBriefModel.findById.mockResolvedValue({id: 'proposal-1',- metadata: { proposal: proposalMetadata },+ metadata: proposalBriefMetadata(),trigger: NIGHTLY_REVIEW_BRIEF_TRIGGER,});mockBriefModel.resolve.mockResolvedValue({ id: 'proposal-1', resolvedAction: 'approve' });- const result = await resolveWithMaintenanceProposal(+ const result = await resolveWithSelfReviewProposal('proposal-1',{ action: 'approve' },- maintenanceProposalResolver,+ selfReviewProposalResolver,);- expect(maintenanceProposalResolver).toHaveBeenCalledWith({+ expect(selfReviewProposalResolver).toHaveBeenCalledWith({action: 'approve',brief: expect.objectContaining({ id: 'proposal-1' }),proposal: proposalMetadata,@@ -167,26 +174,26 @@ describe('AgentSignalSelfReviewBriefService', () => {* @example* expect(mockBriefModel.resolve).not.toHaveBeenCalled();*/- it('keeps stale maintenance proposal briefs unresolved after approve preflight fails', async () => {+ it('keeps stale self-review proposal briefs unresolved after approve preflight fails', async () => {const unresolvedBrief = {id: 'proposal-2',- metadata: { proposal: { ...proposalMetadata, status: 'stale' } },+ metadata: proposalBriefMetadata({ ...proposalMetadata, status: 'stale' }),trigger: NIGHTLY_REVIEW_BRIEF_TRIGGER,};- const maintenanceProposalResolver = vi.fn().mockResolvedValue({+ const selfReviewProposalResolver = vi.fn().mockResolvedValue({brief: unresolvedBrief,shouldResolve: false,});mockBriefModel.findById.mockResolvedValue({id: 'proposal-2',- metadata: { proposal: proposalMetadata },+ metadata: proposalBriefMetadata(),trigger: NIGHTLY_REVIEW_BRIEF_TRIGGER,});- const result = await resolveWithMaintenanceProposal(+ const result = await resolveWithSelfReviewProposal('proposal-2',{ action: 'approve' },- maintenanceProposalResolver,+ selfReviewProposalResolver,);expect(result).toBe(unresolvedBrief);@@ -195,27 +202,27 @@ describe('AgentSignalSelfReviewBriefService', () => {/*** @example- * expect(maintenanceProposalResolver).toHaveBeenCalledWith(expect.objectContaining({ action: 'dismiss' }));+ * expect(selfReviewProposalResolver).toHaveBeenCalledWith(expect.objectContaining({ action: 'dismiss' }));*/- it('dismisses pending maintenance proposals through the proposal resolver', async () => {- const maintenanceProposalResolver = vi.fn().mockResolvedValue({+ it('dismisses pending self-review proposals through the proposal resolver', async () => {+ const selfReviewProposalResolver = vi.fn().mockResolvedValue({brief: { id: 'proposal-3' },shouldResolve: true,});mockBriefModel.findById.mockResolvedValue({id: 'proposal-3',- metadata: { proposal: proposalMetadata },+ metadata: proposalBriefMetadata(),trigger: NIGHTLY_REVIEW_BRIEF_TRIGGER,});mockBriefModel.resolve.mockResolvedValue({ id: 'proposal-3', resolvedAction: 'dismiss' });- await resolveWithMaintenanceProposal(+ await resolveWithSelfReviewProposal('proposal-3',{ action: 'dismiss' },- maintenanceProposalResolver,+ selfReviewProposalResolver,);- expect(maintenanceProposalResolver).toHaveBeenCalledWith(+ expect(selfReviewProposalResolver).toHaveBeenCalledWith(expect.objectContaining({ action: 'dismiss' }),);expect(mockBriefModel.resolve).toHaveBeenCalledWith('proposal-3', { action: 'dismiss' });@@ -225,7 +232,7 @@ describe('AgentSignalSelfReviewBriefService', () => {* @example* expect(mockSkillDocumentService.createSkill).toHaveBeenCalledWith(expect.objectContaining({ name: 'code-review' }));*/- it('applies fresh create_skill maintenance proposals through the default approve resolver', async () => {+ it('applies fresh create_skill self-review proposals through the default approve resolver', async () => {const createProposalMetadata = {...proposalMetadata,actionType: 'create_skill' as const,@@ -251,7 +258,7 @@ describe('AgentSignalSelfReviewBriefService', () => {operation: 'create' as const,},rationale: 'Create a managed skill.',- risk: MaintenanceRisk.Medium,+ risk: Risk.Medium,target: { skillName: 'code-review' },},],@@ -264,7 +271,7 @@ describe('AgentSignalSelfReviewBriefService', () => {agentSignal: {nightlySelfReview: {localDate: '2026-05-09',- maintenanceProposal: createProposalMetadata,+ selfReviewProposal: createProposalMetadata,sourceId: 'source-create',timezone: 'Asia/Shanghai',},@@ -278,7 +285,7 @@ describe('AgentSignalSelfReviewBriefService', () => {metadata: {agentSignal: {nightlySelfReview: {- maintenanceProposal: { status: 'applied' },+ selfReviewProposal: { status: 'applied' },},},},@@ -289,7 +296,7 @@ describe('AgentSignalSelfReviewBriefService', () => {resolvedAction: 'approve',});- const result = await resolveWithMaintenanceProposal('proposal-create', { action: 'approve' });+ const result = await resolveWithSelfReviewProposal('proposal-create', { action: 'approve' });expect(mockSkillDocumentService.getSkill).toHaveBeenCalledWith({agentId: 'agt_1',@@ -302,9 +309,11 @@ describe('AgentSignalSelfReviewBriefService', () => {name: 'code-review',title: 'Code Review',});- expect(mockReadWindow).toHaveBeenCalledWith('maintenance-operation:nightly:create:code-review');+ expect(mockReadWindow).toHaveBeenCalledWith(+ 'self-iteration-operation:nightly:create:code-review',+ );expect(mockTryDedupe).toHaveBeenCalledWith(- 'maintenance-operation-reserve:nightly:create:code-review',+ 'self-iteration-operation-reserve:nightly:create:code-review',expect.any(Number),);expect(mockPersistAgentSignalReceipts).toHaveBeenCalledWith([@@ -313,14 +322,14 @@ describe('AgentSignalSelfReviewBriefService', () => {id: 'nightly:create:code-review',kind: 'skill',sourceId: 'source-create',- sourceType: 'agent.maintenance_proposal.approved',+ sourceType: 'agent.self_review_proposal.approved',status: 'applied',topicId: 'source-create',userId,}),]);expect(mockWriteWindow).toHaveBeenCalledWith(- 'maintenance-operation:nightly:create:code-review',+ 'self-iteration-operation:nightly:create:code-review',{result: JSON.stringify({receiptId: 'nightly:create:code-review',@@ -341,7 +350,7 @@ describe('AgentSignalSelfReviewBriefService', () => {* @example* expect(mockSkillDocumentService.createSkill).not.toHaveBeenCalled();*/- it('dedupes repeated create_skill approvals through the maintenance operation reservation', async () => {+ it('dedupes repeated create_skill approvals through the self-iteration operation reservation', async () => {const createProposalMetadata = {...proposalMetadata,actionType: 'create_skill' as const,@@ -367,7 +376,7 @@ describe('AgentSignalSelfReviewBriefService', () => {operation: 'create' as const,},rationale: 'Create a managed skill.',- risk: MaintenanceRisk.Medium,+ risk: Risk.Medium,target: { skillName: 'code-review' },},],@@ -377,8 +386,12 @@ describe('AgentSignalSelfReviewBriefService', () => {agentId: 'agt_1',id: 'proposal-create',metadata: {- proposal: createProposalMetadata,- sourceId: 'source-create',+ agentSignal: {+ nightlySelfReview: {+ selfReviewProposal: createProposalMetadata,+ sourceId: 'source-create',+ },+ },},trigger: NIGHTLY_REVIEW_BRIEF_TRIGGER,};@@ -390,16 +403,17 @@ describe('AgentSignalSelfReviewBriefService', () => {summary: 'Already created.',}),});- mockBriefModel.findById- .mockResolvedValueOnce(pendingBrief)- .mockResolvedValueOnce({ ...pendingBrief, metadata: { proposal: { status: 'applied' } } });+ mockBriefModel.findById.mockResolvedValueOnce(pendingBrief).mockResolvedValueOnce({+ ...pendingBrief,+ metadata: proposalBriefMetadata({ status: 'applied' }),+ });mockBriefModel.updateMetadata.mockResolvedValue(pendingBrief);mockBriefModel.resolve.mockResolvedValue({id: 'proposal-create',resolvedAction: 'approve',});- const result = await resolveWithMaintenanceProposal('proposal-create', { action: 'approve' });+ const result = await resolveWithSelfReviewProposal('proposal-create', { action: 'approve' });expect(mockSkillDocumentService.createSkill).not.toHaveBeenCalled();expect(mockTryDedupe).not.toHaveBeenCalled();@@ -407,7 +421,7 @@ describe('AgentSignalSelfReviewBriefService', () => {expect.objectContaining({id: 'nightly:create:code-review',kind: 'skill',- sourceType: 'agent.maintenance_proposal.approved',+ sourceType: 'agent.self_review_proposal.approved',status: 'skipped',}),]);diff --git a/src/server/services/agentSignal/services/briefs/selfReview.ts b/src/server/services/agentSignal/services/briefs/selfReview.tsindex 5f35e1c970a..2d0cc389800 100644--- a/src/server/services/agentSignal/services/briefs/selfReview.ts+++ b/src/server/services/agentSignal/services/briefs/selfReview.ts@@ -4,38 +4,38 @@ import type { BriefItem } from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';import { AGENT_SIGNAL_DEFAULTS } from '@/server/services/agentSignal/constants';import { isAgentSignalEnabledForUser } from '@/server/services/agentSignal/featureGate';+import { persistAgentSignalReceipts } from '@/server/services/agentSignal/services/receiptService';import {- createBriefMaintenanceService,+ createBriefSelfReviewService,getNightlySelfReviewBriefMetadata,NIGHTLY_REVIEW_BRIEF_TRIGGER,-} from '@/server/services/agentSignal/services/maintenance/brief';-import type { MaintenanceProposalMetadata } from '@/server/services/agentSignal/services/maintenance/proposal';-import { getMaintenanceProposalFromBriefMetadata } from '@/server/services/agentSignal/services/maintenance/proposal';-import { createMaintenanceProposalApplyService } from '@/server/services/agentSignal/services/maintenance/proposalApply';-import { createMaintenanceProposalPreflightService } from '@/server/services/agentSignal/services/maintenance/proposalPreflight';+} from '@/server/services/agentSignal/services/selfIteration/review/brief';+import type { SelfReviewProposalMetadata } from '@/server/services/agentSignal/services/selfIteration/review/proposal';+import { getSelfReviewProposalFromBriefMetadata } from '@/server/services/agentSignal/services/selfIteration/review/proposal';+import { createSelfReviewProposalApplyService } from '@/server/services/agentSignal/services/selfIteration/review/proposalApply';+import { createSelfReviewProposalPreflightService } from '@/server/services/agentSignal/services/selfIteration/review/proposalPreflight';import {- createMaintenanceTools,- type MaintenanceToolOperationReservation,- type MaintenanceToolReceiptInput,- type MaintenanceToolWriteResult,-} from '@/server/services/agentSignal/services/maintenance/tools';-import { MaintenanceRisk } from '@/server/services/agentSignal/services/maintenance/types';-import { persistAgentSignalReceipts } from '@/server/services/agentSignal/services/receiptService';+ createToolSet,+ type OperationReservation,+ type ToolReceiptInput,+ type ToolWriteResult,+} from '@/server/services/agentSignal/services/selfIteration/tools/shared';+import { Risk } from '@/server/services/agentSignal/services/selfIteration/types';import { redisSourceEventStore } from '@/server/services/agentSignal/store/adapters/redis/sourceEventStore';import type { BriefResolveOptions } from '@/server/services/brief';import { BriefService } from '@/server/services/brief';import { SkillManagementDocumentService } from '@/server/services/skillManagement/SkillManagementDocumentService';-export interface MaintenanceProposalBriefResolutionInput {+export interface SelfReviewProposalBriefResolutionInput {/** User action requested by the Daily Brief card. */action: 'approve' | 'dismiss';/** Brief row that stores the pending proposal metadata. */brief: BriefItem;/** Frozen proposal metadata extracted from the brief. */- proposal: MaintenanceProposalMetadata;+ proposal: SelfReviewProposalMetadata;}-export interface MaintenanceProposalBriefResolutionResult {+export interface SelfReviewProposalBriefResolutionResult {/** Latest brief row after proposal metadata updates. */brief: BriefItem | null;/** Resolution action to store when it differs from the requested action. */@@ -46,9 +46,9 @@ export interface MaintenanceProposalBriefResolutionResult {export interface AgentSignalSelfReviewBriefServiceOptions {/** Optional override used by tests or alternate runtimes for Agent Signal proposal approval. */- maintenanceProposalResolver?: (- input: MaintenanceProposalBriefResolutionInput,- ) => Promise<MaintenanceProposalBriefResolutionResult>;+ selfReviewProposalResolver?: (+ input: SelfReviewProposalBriefResolutionInput,+ ) => Promise<SelfReviewProposalBriefResolutionResult>;}const asMetadataRecord = (metadata: unknown): Record<string, unknown> =>@@ -56,22 +56,22 @@ const asMetadataRecord = (metadata: unknown): Record<string, unknown> =>? (metadata as Record<string, unknown>): {};-const MAINTENANCE_OPERATION_STATE_TTL_SECONDS = AGENT_SIGNAL_DEFAULTS.receiptTtlSeconds;-const MAINTENANCE_PROPOSAL_APPROVED_SOURCE_TYPE = 'agent.maintenance_proposal.approved';+const SELF_ITERATION_OPERATION_STATE_TTL_SECONDS = AGENT_SIGNAL_DEFAULTS.receiptTtlSeconds;+const SELF_REVIEW_PROPOSAL_APPROVED_SOURCE_TYPE = 'agent.self_review_proposal.approved';-const maintenanceOperationScopeKey = (idempotencyKey: string) =>- `maintenance-operation:${idempotencyKey}`;+const selfIterationOperationScopeKey = (idempotencyKey: string) =>+ `self-iteration-operation:${idempotencyKey}`;-const maintenanceOperationReserveKey = (idempotencyKey: string) =>- `maintenance-operation-reserve:${idempotencyKey}`;+const selfIterationOperationReserveKey = (idempotencyKey: string) =>+ `self-iteration-operation-reserve:${idempotencyKey}`;const parseStoredOperationResult = (payload: Record<string, string> | undefined,-): MaintenanceToolWriteResult | undefined => {+): ToolWriteResult | undefined => {if (!payload?.result) return;try {- const result = JSON.parse(payload.result) as MaintenanceToolWriteResult;+ const result = JSON.parse(payload.result) as ToolWriteResult;if (result.status === 'applied' ||@@ -88,14 +88,14 @@ const parseStoredOperationResult = (}};-const createSkippedOperationResult = (): MaintenanceToolWriteResult => ({+const createSkippedOperationResult = (): ToolWriteResult => ({status: 'skipped_unsupported',summary:- 'Maintenance operation is already reserved or Redis is unavailable; skipped to avoid duplicate mutation.',+ 'Self-iteration operation is already reserved or Redis is unavailable; skipped to avoid duplicate mutation.',});const getToolReceiptStatus = (- status: MaintenanceToolReceiptInput['status'],+ status: ToolReceiptInput['status'],): 'applied' | 'failed' | 'proposed' | 'skipped' => {if (status === 'applied') return 'applied';if (status === 'failed') return 'failed';@@ -108,7 +108,7 @@ const getToolReceiptStatus = (* Resolves Agent Signal self-review Daily Brief actions.** Use when:- * - API boundaries resolve Daily Briefs that may contain Agent Signal maintenance proposals+ * - API boundaries resolve Daily Briefs that may contain Agent Signal self-review proposals* - Approve/dismiss must run self-review proposal preflight before normal brief resolution** Expects:@@ -122,14 +122,14 @@ const getToolReceiptStatus = (** briefRouter.resolve* -> {@link AgentSignalSelfReviewBriefService.resolve}- * -> {@link AgentSignalSelfReviewBriefService.resolveMaintenanceProposalIfPending}+ * -> {@link AgentSignalSelfReviewBriefService.resolveSelfReviewProposalIfPending}* -> {@link BriefService.resolve}*/export class AgentSignalSelfReviewBriefService {private briefService: BriefService;private briefModel: BriefModel;private db: LobeChatDatabase;- private maintenanceProposalResolver?: AgentSignalSelfReviewBriefServiceOptions['maintenanceProposalResolver'];+ private selfReviewProposalResolver?: AgentSignalSelfReviewBriefServiceOptions['selfReviewProposalResolver'];private userId: string;constructor(@@ -141,7 +141,7 @@ export class AgentSignalSelfReviewBriefService {this.userId = userId;this.briefService = new BriefService(db, userId);this.briefModel = new BriefModel(db, userId);- this.maintenanceProposalResolver = options.maintenanceProposalResolver;+ this.selfReviewProposalResolver = options.selfReviewProposalResolver;}/**@@ -159,7 +159,7 @@ export class AgentSignalSelfReviewBriefService {* - The resolved or still-pending brief row*/async resolve(brief: BriefItem, options?: BriefResolveOptions): Promise<BriefItem | null> {- const proposalResult = await this.resolveMaintenanceProposalIfPending(brief, options?.action);+ const proposalResult = await this.resolveSelfReviewProposalIfPending(brief, options?.action);if (proposalResult) {if (!proposalResult.shouldResolve) return proposalResult.brief;@@ -173,27 +173,27 @@ export class AgentSignalSelfReviewBriefService {return this.briefService.resolve(brief.id, options);}- private async resolveMaintenanceProposalIfPending(+ private async resolveSelfReviewProposalIfPending(brief: BriefItem,action?: string,- ): Promise<MaintenanceProposalBriefResolutionResult | undefined> {+ ): Promise<SelfReviewProposalBriefResolutionResult | undefined> {if (brief.trigger !== NIGHTLY_REVIEW_BRIEF_TRIGGER) return;- const proposal = getMaintenanceProposalFromBriefMetadata(brief.metadata);+ const proposal = getSelfReviewProposalFromBriefMetadata(brief.metadata);if (!proposal || proposal.status !== 'pending') return;if (action !== 'approve' && action !== 'dismiss') return;- const proposalAction: MaintenanceProposalBriefResolutionInput['action'] = action;+ const proposalAction: SelfReviewProposalBriefResolutionInput['action'] = action;const input = { action: proposalAction, brief, proposal };- if (this.maintenanceProposalResolver) return this.maintenanceProposalResolver(input);+ if (this.selfReviewProposalResolver) return this.selfReviewProposalResolver(input);- return this.resolveMaintenanceProposal(input);+ return this.resolveSelfReviewProposal(input);}- private async resolveMaintenanceProposal({+ private async resolveSelfReviewProposal({action,brief,proposal,- }: MaintenanceProposalBriefResolutionInput): Promise<MaintenanceProposalBriefResolutionResult> {+ }: SelfReviewProposalBriefResolutionInput): Promise<SelfReviewProposalBriefResolutionResult> {if (action === 'dismiss') {const updatedBrief = await this.updateProposal(brief, {...proposal,@@ -210,9 +210,9 @@ export class AgentSignalSelfReviewBriefService {const sourceId =typeof metadata?.sourceId === 'string'? metadata.sourceId- : `maintenance-proposal-approve:${brief.id}`;+ : `self-review-proposal-approve:${brief.id}`;const skillDocumentService = new SkillManagementDocumentService(this.db, this.userId);- const preflight = createMaintenanceProposalPreflightService({+ const preflight = createSelfReviewProposalPreflightService({isSkillNameAvailable: async ({ name }) => {const skill = await skillDocumentService.getSkill({agentId: brief.agentId ?? '',@@ -227,7 +227,7 @@ export class AgentSignalSelfReviewBriefService {agentId: brief.agentId ?? '',}),});- const tools = createMaintenanceTools({+ const tools = createToolSet({createSkill: async (toolInput) => {const result = await skillDocumentService.createSkill({agentId: brief.agentId ?? '',@@ -244,7 +244,7 @@ export class AgentSignalSelfReviewBriefService {},preflight: async (toolInput) => {if (!('baseSnapshot' in toolInput) || !('skillDocumentId' in toolInput)) {- return { allowed: false, reason: 'Unsupported maintenance preflight target.' };+ return { allowed: false, reason: 'Unsupported shared preflight target.' };}const result = await preflight.checkAction({@@ -261,8 +261,8 @@ export class AgentSignalSelfReviewBriefService {},operation: 'refine',},- rationale: toolInput.summary ?? 'Apply approved maintenance proposal.',- risk: MaintenanceRisk.Medium,+ rationale: toolInput.summary ?? 'Apply approved self-review proposal.',+ risk: Risk.Medium,target: { skillDocumentId: toolInput.skillDocumentId },});@@ -283,10 +283,8 @@ export class AgentSignalSelfReviewBriefService {summary: `Refined managed skill ${result.name}.`,};},- reserveOperation: async (- idempotencyKey: string,- ): Promise<MaintenanceToolOperationReservation> => {- const scopeKey = maintenanceOperationScopeKey(idempotencyKey);+ reserveOperation: async (idempotencyKey: string): Promise<OperationReservation> => {+ const scopeKey = selfIterationOperationScopeKey(idempotencyKey);const existing = parseStoredOperationResult(await redisSourceEventStore.readWindow(scopeKey),);@@ -299,12 +297,12 @@ export class AgentSignalSelfReviewBriefService {// of applying without a durable operation record.// Root cause summary: approve is a user-triggered HTTP path and can be clicked twice or// race across workers.- // Source/context: mirrors `reserveMaintenanceOperation` in- // `src/server/services/agentSignal/services/maintenance/serverRuntime.ts`.- // Removal condition: replace with a database-backed maintenance operation ledger.+ // Source/context: mirrors `reserveSelfIterationOperation` in+ // `src/server/services/agentSignal/services/selfIteration/review/server.ts`.+ // Removal condition: replace with a database-backed self-iteration operation ledger.const reserved = await redisSourceEventStore.tryDedupe(- maintenanceOperationReserveKey(idempotencyKey),- MAINTENANCE_OPERATION_STATE_TTL_SECONDS,+ selfIterationOperationReserveKey(idempotencyKey),+ SELF_ITERATION_OPERATION_STATE_TTL_SECONDS,);if (reserved) return { reserved: true };@@ -323,18 +321,18 @@ export class AgentSignalSelfReviewBriefService {createdAt: Date.now(),detail:toolInput.summary ??- `Maintenance tool ${toolInput.toolName} finished with ${toolInput.status}.`,+ `Self-review tool ${toolInput.toolName} finished with ${toolInput.status}.`,id: toolInput.idempotencyKey,kind:toolInput.toolName === 'createSkillIfAbsent' ||toolInput.toolName === 'replaceSkillContentCAS'? 'skill'- : 'maintenance',+ : 'review',metadata: {- sourceType: MAINTENANCE_PROPOSAL_APPROVED_SOURCE_TYPE,+ sourceType: SELF_REVIEW_PROPOSAL_APPROVED_SOURCE_TYPE,},sourceId,- sourceType: MAINTENANCE_PROPOSAL_APPROVED_SOURCE_TYPE,+ sourceType: SELF_REVIEW_PROPOSAL_APPROVED_SOURCE_TYPE,status: getToolReceiptStatus(toolInput.status),...(toolInput.resourceId &&(toolInput.toolName === 'createSkillIfAbsent' ||@@ -348,7 +346,7 @@ export class AgentSignalSelfReviewBriefService {},}: {}),- title: toolInput.summary ?? 'Maintenance tool outcome',+ title: toolInput.summary ?? 'Self-review tool outcome',topicId: sourceId,userId: this.userId,},@@ -358,24 +356,24 @@ export class AgentSignalSelfReviewBriefService {},completeOperation: async (toolInput) => {await redisSourceEventStore.writeWindow(- maintenanceOperationScopeKey(toolInput.idempotencyKey),+ selfIterationOperationScopeKey(toolInput.idempotencyKey),{result: JSON.stringify({...(toolInput.receiptId ? { receiptId: toolInput.receiptId } : {}),...(toolInput.resourceId ? { resourceId: toolInput.resourceId } : {}),status: toolInput.status,...(toolInput.summary ? { summary: toolInput.summary } : {}),- } satisfies MaintenanceToolWriteResult),+ } satisfies ToolWriteResult),},- MAINTENANCE_OPERATION_STATE_TTL_SECONDS,+ SELF_ITERATION_OPERATION_STATE_TTL_SECONDS,);},});- const briefMaintenance = createBriefMaintenanceService();- const applyService = createMaintenanceProposalApplyService({+ const briefSelfReview = createBriefSelfReviewService();+ const applyService = createSelfReviewProposalApplyService({checkAction: preflight.checkAction,checkGates: () =>- briefMaintenance.canApplyMaintenanceProposal({+ briefSelfReview.canApplySelfReviewProposal({checkAgentGate: () =>new AgentSignalReviewContextModel(this.db, this.userId).canAgentRunSelfIteration(brief.agentId ?? '',@@ -392,7 +390,7 @@ export class AgentSignalSelfReviewBriefService {agentId: brief.agentId,proposal,sourceId,- sourceType: MAINTENANCE_PROPOSAL_APPROVED_SOURCE_TYPE,+ sourceType: SELF_REVIEW_PROPOSAL_APPROVED_SOURCE_TYPE,userId: this.userId,...(typeof metadata?.localDate === 'string' ? { localDate: metadata.localDate } : {}),...(typeof metadata?.timezone === 'string' ? { timezone: metadata.timezone } : {}),@@ -410,7 +408,7 @@ export class AgentSignalSelfReviewBriefService {return { brief: updatedBrief, shouldResolve: false };}- private updateProposal(brief: BriefItem, nextProposal: MaintenanceProposalMetadata) {+ private updateProposal(brief: BriefItem, nextProposal: SelfReviewProposalMetadata) {const metadata = asMetadataRecord(brief.metadata);const agentSignal = asMetadataRecord(metadata.agentSignal);const nightlySelfReview = asMetadataRecord(agentSignal.nightlySelfReview);@@ -421,7 +419,7 @@ export class AgentSignalSelfReviewBriefService {...agentSignal,nightlySelfReview: {...nightlySelfReview,- maintenanceProposal: nextProposal,+ selfReviewProposal: nextProposal,},},});diff --git a/src/server/services/agentSignal/services/index.ts b/src/server/services/agentSignal/services/index.tsindex 106e43ddcba..e219ada3ec1 100644--- a/src/server/services/agentSignal/services/index.ts+++ b/src/server/services/agentSignal/services/index.ts@@ -1,15 +1,9 @@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 './selfFeedbackIntent';+export * from './selfIteration';+export * from './selfIteration/review/schedule';export * from './selfReflection';export * from './types';diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/agentRunner.test.ts b/src/server/services/agentSignal/services/maintenance/__tests__/agentRunner.test.tsdeleted file mode 100644index fc8a03272b4..00000000000--- a/src/server/services/agentSignal/services/maintenance/__tests__/agentRunner.test.ts+++ /dev/null@@ -1,154 +0,0 @@-// @vitest-environment node-import { describe, expect, it, vi } from 'vitest';--import type { MaintenanceAgentRunResult } from '../agentRunner';-import { createMaintenanceAgentRunner } from '../agentRunner';-import type { NightlyReviewContext } from '../nightlyCollector';-import { createMaintenanceTools } from '../tools';-import {- MaintenanceActionStatus,- MaintenanceApplyMode,- MaintenanceReviewScope,- MaintenanceRisk,- ReviewRunStatus,-} from '../types';--const reviewContext = {- agentId: 'agent-1',- documentActivity: {- ambiguousBucket: [],- excludedSummary: { count: 0, reasons: [] },- generalDocumentBucket: [],- skillBucket: [],- },- feedbackActivity: {- neutralCount: 0,- notSatisfied: [],- satisfied: [],- },- maintenanceSignals: [],- managedSkills: [],- proposalActivity: {- active: [],- dismissedCount: 0,- expiredCount: 0,- staleCount: 0,- supersededCount: 0,- },- receiptActivity: {- appliedCount: 0,- duplicateGroups: [],- failedCount: 0,- pendingProposalCount: 0,- recentReceipts: [],- reviewCount: 0,- },- relevantMemories: [],- reviewWindowEnd: '2026-05-04T14:00:00.000Z',- reviewWindowStart: '2026-05-03T14:00:00.000Z',- toolActivity: [],- topics: [],- userId: 'user-1',-} satisfies NightlyReviewContext;--const createNoopTools = () =>- createMaintenanceTools({- reserveOperation: vi.fn(async () => ({ reserved: true as const })),- writeReceipt: vi.fn(async () => ({ receiptId: 'receipt-1' })),- });--describe('createMaintenanceAgentRunner', () => {- /**- * @example- * expect(result.projectionPlan.actions).toHaveLength(1);- */- it('passes source metadata, max steps, and tools into the backend runner', async () => {- const tools = createNoopTools();- const run = vi.fn<() => Promise<MaintenanceAgentRunResult>>(async () => ({- execution: {- actions: [- {- idempotencyKey: 'source-1:noop',- status: MaintenanceActionStatus.Skipped,- },- ],- status: ReviewRunStatus.Completed,- },- projectionPlan: {- actions: [- {- actionType: 'noop',- applyMode: MaintenanceApplyMode.Skip,- confidence: 1,- dedupeKey: 'noop',- evidenceRefs: [{ id: 'topic-1', type: 'topic' }],- idempotencyKey: 'source-1:noop',- rationale: 'No change needed.',- risk: MaintenanceRisk.Low,- },- ],- localDate: '2026-05-04',- plannerVersion: 'test',- reviewScope: MaintenanceReviewScope.Nightly,- summary: 'No change needed.',- },- stepCount: 2,- }));- const runner = createMaintenanceAgentRunner({ maxSteps: 10, run, tools });-- const result = await runner.run({- context: reviewContext,- localDate: '2026-05-04',- sourceId: 'source-1',- userId: 'user-1',- });-- expect(run).toHaveBeenCalledWith(- expect.objectContaining({- context: reviewContext,- localDate: '2026-05-04',- maxSteps: 10,- reviewScope: MaintenanceReviewScope.Nightly,- sourceId: 'source-1',- tools,- userId: 'user-1',- }),- );- expect(result.execution.sourceId).toBe('source-1');- expect(result.projectionPlan.actions).toHaveLength(1);- });-- /**- * @example- * expect(result.execution.status).toBe('failed');- */- it('returns a conservative failed envelope when the backend runner throws', async () => {- const runner = createMaintenanceAgentRunner({- run: vi.fn(async () => {- throw new Error('model failed');- }),- tools: createNoopTools(),- });-- const result = await runner.run({- context: reviewContext,- localDate: '2026-05-04',- sourceId: 'source-1',- userId: 'user-1',- });-- expect(result.execution).toEqual({- actions: [],- sourceId: 'source-1',- status: ReviewRunStatus.Failed,- });- expect(result.projectionPlan).toEqual(- expect.objectContaining({- actions: [],- localDate: '2026-05-04',- reviewScope: MaintenanceReviewScope.Nightly,- }),- );- expect(result.stepCount).toBe(10);- });-});diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/executor.test.ts b/src/server/services/agentSignal/services/maintenance/__tests__/executor.test.tsdeleted file mode 100644index 77ffa4fc322..00000000000--- a/src/server/services/agentSignal/services/maintenance/__tests__/executor.test.ts+++ /dev/null@@ -1,88 +0,0 @@-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.tsdeleted file mode 100644index b3180258064..00000000000--- a/src/server/services/agentSignal/services/maintenance/__tests__/memory.test.ts+++ /dev/null@@ -1,50 +0,0 @@-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__/nightlyDocumentActivity.test.ts b/src/server/services/agentSignal/services/maintenance/__tests__/nightlyDocumentActivity.test.tsdeleted file mode 100644index 796a269dbdb..00000000000--- a/src/server/services/agentSignal/services/maintenance/__tests__/nightlyDocumentActivity.test.ts+++ /dev/null@@ -1,90 +0,0 @@-import { describe, expect, it } from 'vitest';--import { mapNightlyDocumentActivityRows } from '../nightlyDocumentActivity';--describe('mapNightlyDocumentActivityRows', () => {- /**- * @example- * hintIsSkill true rows enter the skill bucket and false rows enter the general bucket.- */- it('buckets hinted skill and general document activity separately', () => {- expect(- mapNightlyDocumentActivityRows([- {- agentDocumentId: 'agent-doc-skill',- documentId: 'doc-skill',- hintIsSkill: true,- policyLoadFormat: 'raw',- templateId: null,- title: 'YouTube comments skill',- updatedAt: new Date('2026-05-09T18:10:00.000Z'),- },- {- agentDocumentId: 'agent-doc-general',- documentId: 'doc-general',- hintIsSkill: false,- policyLoadFormat: 'raw',- templateId: null,- title: 'Meeting notes',- updatedAt: new Date('2026-05-09T18:11:00.000Z'),- },- ]),- ).toEqual({- ambiguousBucket: [],- excludedSummary: { count: 0, reasons: [] },- generalDocumentBucket: [- expect.objectContaining({- agentDocumentId: 'agent-doc-general',- reason: 'metadata.agentSignal.hintIsSkill=false',- }),- ],- skillBucket: [- expect.objectContaining({- agentDocumentId: 'agent-doc-skill',- hintIsSkill: true,- reason: 'metadata.agentSignal.hintIsSkill=true',- }),- ],- });- });-- /**- * @example- * Existing managed skill templates are still skill bucket evidence even without a hint.- */- it('buckets known skill template rows as skill activity', () => {- expect(- mapNightlyDocumentActivityRows([- {- agentDocumentId: 'agent-doc-index',- documentId: 'doc-index',- hintIsSkill: null,- policyLoadFormat: 'raw',- templateId: 'skills/index',- title: 'Skill index',- updatedAt: new Date('2026-05-09T18:10:00.000Z'),- },- {- agentDocumentId: 'agent-doc-managed-skill',- documentId: 'doc-managed-skill',- hintIsSkill: null,- policyLoadFormat: 'raw',- templateId: 'agent-skill',- title: 'Managed skill',- updatedAt: new Date('2026-05-09T18:11:00.000Z'),- },- ]).skillBucket,- ).toEqual([- expect.objectContaining({- agentDocumentId: 'agent-doc-index',- hintIsSkill: false,- reason: 'templateId=skills/index',- }),- expect.objectContaining({- agentDocumentId: 'agent-doc-managed-skill',- hintIsSkill: false,- reason: 'templateId=agent-skill',- }),- ]);- });-});diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/planner.test.ts b/src/server/services/agentSignal/services/maintenance/__tests__/planner.test.tsdeleted file mode 100644index ccd7646504f..00000000000--- a/src/server/services/agentSignal/services/maintenance/__tests__/planner.test.ts+++ /dev/null@@ -1,642 +0,0 @@-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: {- bodyMarkdown:- '# Release notes\n\nUse this skill to draft release notes.\n\n- 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: {- bodyMarkdown:- '# Release notes\n\nUse this skill to draft release notes.\n\n- Validate changelog sections before publishing.',- skillDocumentId: 'skill-release-notes',- },- },- risk: MaintenanceRisk.Low,- });- });-- /**- * @example- * Patch-only skill refinements are not treated as full replacement documents.- */- it('keeps patch-only skill refinement drafts out of automatic apply', () => {- const planner = createMaintenancePlannerService();-- const plan = planner.plan({- draft: {- actions: [- {- actionType: 'refine_skill',- confidence: 0.94,- evidenceRefs: [- { id: 'tool-fail-1', type: 'tool_call' },- { id: 'tool-fail-2', type: 'tool_call' },- ],- policyHints: {- evidenceStrength: 'strong',- mutationScope: 'small',- userExplicitness: 'implicit',- },- rationale: 'The skill needs a small checklist addition.',- target: { skillDocumentId: 'skill-release-notes' },- value: {- patch: 'Add a checklist step to validate changelog sections before publishing.',- skillDocumentId: 'skill-release-notes',- },- },- ],- findings: [],- summary: 'Patch-only skill refinement.',- },- reviewScope: MaintenanceReviewScope.Nightly,- sourceId: 'nightly-review:user-1:agent-1:2026-05-04',- userId: 'user-1',- });-- expect(plan.actions[0]).toMatchObject({- actionType: 'refine_skill',- applyMode: MaintenanceApplyMode.ProposalOnly,- operation: undefined,- risk: MaintenanceRisk.Medium,- });- });-- /**- * @example- * Complete replacement bodies can still be auto-applied for safe skill refinements.- */- it('allows skill refinement when the draft contains a complete replacement body', () => {- const planner = createMaintenancePlannerService();-- const plan = planner.plan({- draft: {- actions: [- {- actionType: 'refine_skill',- confidence: 0.94,- evidenceRefs: [- { id: 'tool-fail-1', type: 'tool_call' },- { id: 'tool-fail-2', type: 'tool_call' },- ],- policyHints: {- evidenceStrength: 'strong',- mutationScope: 'small',- userExplicitness: 'implicit',- },- rationale: 'The replacement body preserves identity and adds the missing step.',- target: { skillDocumentId: 'skill-release-notes' },- value: {- bodyMarkdown:- '# Release notes\n\nUse this skill to draft release notes.\n\n- Validate changelog sections before publishing.',- skillDocumentId: 'skill-release-notes',- },- },- ],- findings: [],- summary: 'Complete skill refinement.',- },- reviewScope: MaintenanceReviewScope.Nightly,- sourceId: 'nightly-review:user-1:agent-1:2026-05-04',- userId: 'user-1',- });-- expect(plan.actions[0]).toMatchObject({- actionType: 'refine_skill',- applyMode: MaintenanceApplyMode.AutoApply,- operation: {- input: {- bodyMarkdown:- '# Release notes\n\nUse this skill to draft release notes.\n\n- Validate changelog sections before publishing.',- skillDocumentId: 'skill-release-notes',- },- },- risk: MaintenanceRisk.Low,- });- });-- /**- * @example- * A broad rewrite that preserves the same managed skill identity remains auto-applicable.- */- it('allows broad in-document skill refinement when identity and evidence are stable', () => {- const planner = createMaintenancePlannerService();-- const plan = planner.plan({- draft: {- actions: [- {- actionType: 'refine_skill',- confidence: 0.93,- evidenceRefs: [- { id: 'msg-workflow-correction', type: 'message' },- { id: 'tool-workflow-fail', type: 'tool_call' },- ],- policyHints: {- evidenceStrength: 'strong',- mutationScope: 'broad',- userExplicitness: 'explicit',- },- rationale:- 'The existing skill should be rewritten in place while keeping its file and binding.',- target: { skillDocumentId: 'skill-release-notes' },- value: {- bodyMarkdown:- '# Release notes\n\nRewrite the checklist in place while preserving the same managed skill identity.',- skillDocumentId: 'skill-release-notes',- },- },- ],- findings: [],- summary: 'Broad in-place refinement.',- },- reviewScope: MaintenanceReviewScope.Nightly,- sourceId: 'nightly-review:user-1:agent-1:2026-05-04',- userId: 'user-1',- });-- expect(plan.actions[0]).toMatchObject({- actionType: 'refine_skill',- applyMode: MaintenanceApplyMode.AutoApply,- 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- * Noop drafts are skipped maintenance state, not proposal-only review work.- */- it('keeps noop drafts silent instead of proposal-only', () => {- const planner = createMaintenancePlannerService();-- const plan = planner.plan({- draft: {- actions: [- {- actionType: 'noop',- confidence: 0.99,- evidenceRefs: [],- rationale: 'No durable maintenance is needed.',- },- ],- findings: [],- summary: 'No maintenance needed.',- },- reviewScope: MaintenanceReviewScope.Nightly,- sourceId: 'nightly-review:user-1:agent-1:2026-05-04',- userId: 'user-1',- });-- expect(plan.actions[0]).toMatchObject({- actionType: 'noop',- applyMode: MaintenanceApplyMode.Skip,- risk: MaintenanceRisk.Low,- });- });-- /**- * @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- * One mixed review can produce positive auto-apply, proposal, and skip counts.- */- it('separates auto-apply proposal and skip modes for planner metrics', () => {- const planner = createMaintenancePlannerService();-- const plan = planner.plan({- draft: {- actions: [- {- actionType: 'write_memory',- confidence: 0.95,- evidenceRefs: [{ id: 'msg-memory', type: 'message' }],- policyHints: {- evidenceStrength: 'strong',- persistence: 'stable',- sensitivity: 'normal',- userExplicitness: 'explicit',- },- rationale: 'Durable preference.',- value: { content: 'User prefers concise release summaries.' },- },- {- actionType: 'consolidate_skill',- confidence: 0.96,- evidenceRefs: [- { id: 'skill-a', type: 'agent_document' },- { id: 'skill-b', type: 'agent_document' },- ],- rationale: 'Two managed skills overlap and require review.',- target: { skillDocumentId: 'skill-a' },- value: { sourceSkillIds: ['skill-a', 'skill-b'] },- },- {- actionType: 'noop',- confidence: 0.9,- evidenceRefs: [],- rationale: 'No extra maintenance is needed.',- },- ],- findings: [],- summary: 'Mixed maintenance plan.',- },- reviewScope: MaintenanceReviewScope.Nightly,- sourceId: 'nightly-review:user-1:agent-1:2026-05-04',- userId: 'user-1',- });-- const applyModeCounts = {- autoApply: plan.actions.filter(- (action) => action.applyMode === MaintenanceApplyMode.AutoApply,- ).length,- proposal: plan.actions.filter(- (action) => action.applyMode === MaintenanceApplyMode.ProposalOnly,- ).length,- skip: plan.actions.filter((action) => action.applyMode === MaintenanceApplyMode.Skip).length,- };-- expect(applyModeCounts).toEqual({ autoApply: 1, proposal: 1, skip: 1 });- });-- /**- * @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.tsdeleted file mode 100644index 2c5cffd5fbe..00000000000--- a/src/server/services/agentSignal/services/maintenance/__tests__/skill.test.ts+++ /dev/null@@ -1,78 +0,0 @@-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: {- bodyMarkdown:- '# Release notes\n\n- 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- * Patch descriptions are not accepted as complete executable skill replacement bodies.- */- it('rejects patch-only skill refinements before persistence', async () => {- const refineSkill = vi.fn();- const service = createSkillManagementService({ refineSkill });-- await expect(- service.refineSkill({- evidenceRefs: [{ id: 'msg-1', type: 'message' }],- idempotencyKey: 'source:refine_skill:skill:doc-1',- input: {- patch: 'Add a checklist step.',- skillDocumentId: 'doc-1',- userId: 'user-1',- },- }),- ).rejects.toThrow('Skill refinement requires a complete replacement bodyMarkdown');-- expect(refineSkill).not.toHaveBeenCalled();- });-- /**- * @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: {- bodyMarkdown: '# Builtin skill\n\nChange 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/agent.ts b/src/server/services/agentSignal/services/maintenance/agent.tsdeleted file mode 100644index 3ffd70808b4..00000000000--- a/src/server/services/agentSignal/services/maintenance/agent.ts+++ /dev/null@@ -1,1060 +0,0 @@-import type { AgentRuntimeContext, AgentState } from '@lobechat/agent-runtime';-import { AgentRuntime, GeneralChatAgent } from '@lobechat/agent-runtime';-import { DEFAULT_MINI_SYSTEM_AGENT_ITEM } from '@lobechat/const';-import type { LobeToolManifest } from '@lobechat/context-engine';-import { generateToolsFromManifest, ToolNameResolver } from '@lobechat/context-engine';-import type { ChatStreamPayload, ModelRuntime } from '@lobechat/model-runtime';-import { consumeStreamUntilDone } from '@lobechat/model-runtime';-import { SpanStatusCode } from '@lobechat/observability-otel/api';-import { tracer } from '@lobechat/observability-otel/modules/agent-signal';-import type { ChatToolPayload, MessageToolCall, ModelUsage } from '@lobechat/types';-import { RequestTrigger } from '@lobechat/types';--import type { NightlyReviewContext } from './nightlyCollector';-import type { MaintenanceProposalBaseSnapshot } from './proposal';-import type {- CloseMaintenanceProposalInput,- CreateMaintenanceProposalInput,- CreateSkillIfAbsentInput,- MaintenanceTools,- MaintenanceToolWriteInput,- MaintenanceToolWriteResult,- RefreshMaintenanceProposalInput,- ReplaceSkillContentCASInput,- SupersedeMaintenanceProposalInput,- WriteMemoryInput,-} from './tools';-import type { EvidenceRef } from './types';--/** Built-in tool identifier used for maintenance AgentRuntime tool calls. */-export const maintenanceToolFirstRuntimeToolIdentifier = 'agent-signal-maintenance';--/** Read-only maintenance tools exposed to the tool-first runtime. */-export type MaintenanceReadToolName =- | 'getEvidenceDigest'- | 'getManagedSkill'- | 'listMaintenanceProposals'- | 'listManagedSkills'- | 'readMaintenanceProposal';--/** Write maintenance tools whose terminal outcomes must be retained by the runtime. */-export type MaintenanceWriteToolName =- | 'closeMaintenanceProposal'- | 'createMaintenanceProposal'- | 'createSkillIfAbsent'- | 'refreshMaintenanceProposal'- | 'replaceSkillContentCAS'- | 'supersedeMaintenanceProposal'- | 'writeMemory';--/** Maintenance tool names exposed to the model. */-export type MaintenanceRuntimeToolName = MaintenanceReadToolName | MaintenanceWriteToolName;--/**- * Input passed to the tool-first maintenance AgentRuntime loop.- */-export interface MaintenanceToolFirstRuntimeInput {- /** Stable agent id being reviewed. */- agentId: string;- /** Bounded nightly review context collected before the run. */- context: NightlyReviewContext;- /** Maximum AgentRuntime steps allowed for the LLM/tool loop. */- maxSteps: number;- /** Model name passed to the injected model runtime. */- model: string;- /** Minimal model runtime dependency used to stream chat completions. */- modelRuntime: Pick<ModelRuntime, 'chat'>;- /** Stable source id used for tracing and fallback idempotency keys. */- sourceId: string;- /** Safe read/write maintenance tools available to this run. */- tools: MaintenanceTools;- /** Stable user id owning the reviewed agent. */- userId: string;-}--/**- * Write result captured from one supported maintenance write tool call.- */-export interface MaintenanceToolFirstRuntimeWriteOutcome {- /** Tool result returned by the safe maintenance write boundary. */- result: MaintenanceToolWriteResult;- /** Supported write tool that produced this outcome. */- toolName: MaintenanceWriteToolName;-}--/**- * Result returned after the maintenance AgentRuntime loop stops.- */-export interface MaintenanceToolFirstRuntimeResult {- /** Concatenated assistant text streamed across LLM calls. */- content: string;- /** AgentRuntime steps consumed before stopping. */- stepCount: number;- /** Model tool calls resolved against the maintenance manifest. */- toolCalls: ChatToolPayload[];- /** Per-call model usage emitted by streaming callbacks. */- usage: ModelUsage[];- /** Terminal write outcomes produced by supported maintenance write tools. */- writeOutcomes: MaintenanceToolFirstRuntimeWriteOutcome[];-}--interface MaintenanceToolExecutionResult {- data: unknown;- isWrite: boolean;- success: boolean;- toolName?: MaintenanceWriteToolName;-}--const createObjectSchema = (- properties: Record<string, unknown>,- required: string[] = [],-): Record<string, unknown> => ({- additionalProperties: false,- properties,- required,- type: 'object',-});--const stringSchema = { type: 'string' };-const stringArraySchema = { items: stringSchema, type: 'array' };-const freeformArraySchema = { items: {}, type: 'array' };-const freeformObjectSchema = { additionalProperties: true, type: 'object' };-const proposalActionSchema = createObjectSchema(- {- actionType: {- enum: ['create_skill', 'refine_skill', 'consolidate_skill', 'proposal_only'],- type: 'string',- },- applyMode: { enum: ['auto_apply', 'proposal_only', 'skip'], type: 'string' },- baseSnapshot: freeformObjectSchema,- confidence: { type: 'number' },- dedupeKey: stringSchema,- evidenceRefs: freeformArraySchema,- idempotencyKey: stringSchema,- operation: freeformObjectSchema,- rationale: stringSchema,- risk: { enum: ['low', 'medium', 'high'], type: 'string' },- target: freeformObjectSchema,- },- ['actionType', 'rationale', 'target'],-);-const proposalActionsSchema = { items: proposalActionSchema, type: 'array' };--/**- * Tool manifest used to expose current safe maintenance read/write tools to the model.- */-export const maintenanceToolFirstRuntimeManifest = {- api: [- {- description: 'List managed skills visible in the reviewed agent scope.',- name: 'listManagedSkills',- parameters: createObjectSchema({}),- },- {- description: 'Read one managed skill by skill document id in the reviewed agent scope.',- name: 'getManagedSkill',- parameters: createObjectSchema({ skillDocumentId: stringSchema }, ['skillDocumentId']),- },- {- description:- 'Read bounded evidence details for cited topic, message, tool_call, or agent_document ids in the nightly review window. Use this for evidenceRefs; do not pass evidence ids to proposal tools.',- name: 'getEvidenceDigest',- parameters: createObjectSchema({- evidenceIds: stringArraySchema,- reviewWindowEnd: stringSchema,- reviewWindowStart: stringSchema,- }),- },- {- description: 'List active and historical maintenance proposals in the reviewed agent scope.',- name: 'listMaintenanceProposals',- parameters: createObjectSchema({}),- },- {- description:- 'Read one maintenance proposal by proposal id or proposalKey from proposalActivity.active or listMaintenanceProposals. Never use topic, message, tool_call, or document evidence ids here.',- name: 'readMaintenanceProposal',- parameters: createObjectSchema({- proposalId: stringSchema,- proposalKey: stringSchema,- }),- },- {- description: 'Create one user-visible maintenance proposal for later approval.',- name: 'createMaintenanceProposal',- parameters: createObjectSchema(- {- actions: proposalActionsSchema,- idempotencyKey: stringSchema,- metadata: freeformObjectSchema,- proposalKey: stringSchema,- summary: stringSchema,- },- ['idempotencyKey', 'proposalKey', 'summary', 'actions'],- ),- },- {- description: 'Refresh an existing maintenance proposal after rechecking evidence.',- name: 'refreshMaintenanceProposal',- parameters: createObjectSchema(- {- idempotencyKey: stringSchema,- proposalId: stringSchema,- proposalKey: stringSchema,- summary: stringSchema,- },- ['idempotencyKey', 'proposalId'],- ),- },- {- description: 'Supersede an existing maintenance proposal with a replacement proposal key.',- name: 'supersedeMaintenanceProposal',- parameters: createObjectSchema(- {- idempotencyKey: stringSchema,- proposalId: stringSchema,- proposalKey: stringSchema,- summary: stringSchema,- supersededBy: stringSchema,- },- ['idempotencyKey', 'proposalId', 'supersededBy'],- ),- },- {- description: 'Close an existing maintenance proposal with an optional lifecycle reason.',- name: 'closeMaintenanceProposal',- parameters: createObjectSchema(- {- idempotencyKey: stringSchema,- proposalId: stringSchema,- proposalKey: stringSchema,- reason: stringSchema,- summary: stringSchema,- },- ['idempotencyKey', 'proposalId'],- ),- },- {- description:- 'Write one durable user memory when evidence explicitly states a stable normal-sensitivity user preference. Prefer this over skill tools for summary/style/preferences.',- name: 'writeMemory',- parameters: createObjectSchema(- {- content: stringSchema,- evidenceRefs: freeformArraySchema,- idempotencyKey: stringSchema,- proposalKey: stringSchema,- summary: stringSchema,- },- ['idempotencyKey', 'content', 'evidenceRefs'],- ),- },- {- description: 'Create one managed skill when no existing skill is selected.',- name: 'createSkillIfAbsent',- parameters: createObjectSchema(- {- bodyMarkdown: stringSchema,- description: stringSchema,- idempotencyKey: stringSchema,- name: stringSchema,- proposalKey: stringSchema,- summary: stringSchema,- title: stringSchema,- },- ['idempotencyKey', 'name', 'bodyMarkdown'],- ),- },- {- description:- 'Replace one existing managed skill after compare-and-swap preflight. Provide baseSnapshot when available; the server completes it from skillDocumentId when omitted.',- name: 'replaceSkillContentCAS',- parameters: createObjectSchema(- {- baseSnapshot: freeformObjectSchema,- bodyMarkdown: stringSchema,- description: stringSchema,- idempotencyKey: stringSchema,- proposalKey: stringSchema,- skillDocumentId: stringSchema,- summary: stringSchema,- },- ['idempotencyKey', 'skillDocumentId', 'bodyMarkdown'],- ),- },- ],- identifier: maintenanceToolFirstRuntimeToolIdentifier,- meta: {- description: 'Read nightly evidence and apply safe maintenance operations.',- title: 'Agent Signal Maintenance',- },- systemRole:- 'Use maintenance read tools before writes when evidence is incomplete. Use getEvidenceDigest for topic/message/tool_call/agent_document evidenceRefs. Use readMaintenanceProposal only with proposal keys from proposalActivity.active or listMaintenanceProposals, never with evidence ids. Treat write tool results as the source of truth.',- type: 'builtin',-} satisfies LobeToolManifest;--const MAINTENANCE_TOOL_FIRST_SYSTEM_ROLE = [- 'You are the Agent Signal maintenance agent.',- 'Inspect the bounded nightly review context and use the provided maintenance tools to read evidence or apply safe write operations.',- 'Evidence ids and proposal keys are different namespaces: read topic/message/tool_call/agent_document evidence with getEvidenceDigest; read proposals with readMaintenanceProposal only when using proposalActivity.active[].proposalKey or keys returned from listMaintenanceProposals.',- 'Never claim that a write happened unless a write tool result confirms it.',- 'Use writeMemory for explicit durable user preferences such as response style, summary structure, or verification-reporting preferences. Do not turn those preference memories into skills or proposals.',- 'Use createSkillIfAbsent only when evidence describes a reusable workflow and you can provide a non-empty skill name and full bodyMarkdown.',- 'When the evidence supports an approval-gated change, call createMaintenanceProposal in this run; do not offer to draft it later.',- 'For createMaintenanceProposal actions, use actionType exactly create_skill, refine_skill, consolidate_skill, or proposal_only. For refine_skill include target.skillDocumentId and operation { domain: "skill", operation: "refine", input: { skillDocumentId, bodyMarkdown } }. For consolidate_skill include operation { domain: "skill", operation: "consolidate", input: { canonicalSkillDocumentId, sourceSkillIds, bodyMarkdown } }.',- 'Stop after the useful maintenance work is complete and summarize the confirmed outcome.',-].join('\n');--const TOOL_NAME_SEPARATOR = '____';-const MAINTENANCE_TOOL_ERROR_MESSAGE = 'Maintenance tool call failed.';-const FORCE_FINISH_EXTRA_STEPS = 4;--const createMaintenanceRuntimePrompt = (input: MaintenanceToolFirstRuntimeInput) =>- [- `Agent id: ${input.agentId}`,- `User id: ${input.userId}`,- `Source id: ${input.sourceId}`,- `Review window: ${input.context.reviewWindowStart} to ${input.context.reviewWindowEnd}`,- 'Nightly review context JSON:',- JSON.stringify(input.context),- ].join('\n');--const toNullableString = (value: unknown) =>- typeof value === 'string' && value.trim().length > 0 ? value : undefined;--const toBoolean = (value: unknown) => (typeof value === 'boolean' ? value : undefined);--const toRecord = (value: unknown): Record<string, unknown> =>- value && typeof value === 'object' && !Array.isArray(value)- ? (value as Record<string, unknown>)- : {};--const toUnknownArray = (value: unknown): unknown[] => (Array.isArray(value) ? value : []);--const toStringArray = (value: unknown) =>- Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : [];--const toEvidenceRefs = (value: unknown): EvidenceRef[] =>- Array.isArray(value)- ? value.flatMap((item) => {- const record = toRecord(item);- const id = toNullableString(record.id);- const type = toNullableString(record.type);-- if (- !id ||- !(- type === 'topic' ||- type === 'message' ||- type === 'operation' ||- type === 'source' ||- type === 'receipt' ||- type === 'tool_call' ||- type === 'task' ||- type === 'agent_document' ||- type === 'memory'- )- ) {- return [];- }-- return [- {- id,- ...(toNullableString(record.summary)- ? { summary: toNullableString(record.summary) }- : {}),- type,- },- ];- })- : [];--/**- * Normalizes model-produced tool arguments.- *- * Before:- * - `"{\"name\":\"skill\"}"`- * - `"not json"`- *- * After:- * - `{ name: "skill" }`- * - `{}`- */-const parseToolArguments = (value: string | undefined): Record<string, unknown> => {- if (!value) return {};-- try {- const parsed = JSON.parse(value) as unknown;-- return toRecord(parsed);- } catch {- return {};- }-};--const getErrorMessage = (error: unknown) =>- error instanceof Error ? error.message : String(error);--const getApiNameFromRawToolName = (name: string) => {- const [identifier, apiName] = name.split(TOOL_NAME_SEPARATOR);-- return identifier === maintenanceToolFirstRuntimeToolIdentifier && apiName ? apiName : name;-};--const resolveMaintenanceToolCalls = ({- manifestMap,- offeredToolNames,- rawToolCalls,- toolNameResolver,-}: {- manifestMap: Record<string, LobeToolManifest>;- offeredToolNames: string[];- rawToolCalls: MessageToolCall[];- toolNameResolver: ToolNameResolver;-}): ChatToolPayload[] => {- const resolvedToolCalls = toolNameResolver.resolve(rawToolCalls, manifestMap, offeredToolNames);- const resolvedIds = new Set(resolvedToolCalls.map((toolCall) => toolCall.id));- const unresolvedToolCalls = rawToolCalls- .filter((toolCall) => !resolvedIds.has(toolCall.id))- .map(- (toolCall): ChatToolPayload => ({- apiName: getApiNameFromRawToolName(toolCall.function.name),- arguments: toolCall.function.arguments,- id: toolCall.id,- identifier: maintenanceToolFirstRuntimeToolIdentifier,- thoughtSignature: toolCall.thoughtSignature,- type: 'builtin',- }),- );-- return [...resolvedToolCalls, ...unresolvedToolCalls];-};--const createToolError = (message: string): MaintenanceToolExecutionResult => ({- data: { error: message },- isWrite: false,- success: false,-});--const withUser = <TInput extends MaintenanceToolWriteInput>(- toolName: MaintenanceWriteToolName,- args: Record<string, unknown>,- input: MaintenanceToolFirstRuntimeInput,- toolCallId: string,- fields: Omit<TInput, keyof MaintenanceToolWriteInput>,-): TInput =>- ({- ...fields,- idempotencyKey:- toNullableString(args.idempotencyKey) ?? `${input.sourceId}:${toolName}:${toolCallId}`,- proposalKey: toNullableString(args.proposalKey),- summary: toNullableString(args.summary),- userId: input.userId,- }) as TInput;--const toBaseSnapshot = (value: unknown): MaintenanceProposalBaseSnapshot => {- const record = toRecord(value);-- return {- absent: toBoolean(record.absent),- agentDocumentId: toNullableString(record.agentDocumentId),- contentHash: toNullableString(record.contentHash),- documentId: toNullableString(record.documentId),- documentUpdatedAt: toNullableString(record.documentUpdatedAt),- managed: toBoolean(record.managed),- skillName: toNullableString(record.skillName),- targetTitle: toNullableString(record.targetTitle),- targetType: record.targetType === 'skill' ? 'skill' : undefined,- writable: toBoolean(record.writable),- };-};--const executeWriteTool = async (- toolName: MaintenanceWriteToolName,- operation: () => Promise<MaintenanceToolWriteResult>,-): Promise<MaintenanceToolExecutionResult> => ({- data: await operation(),- isWrite: true,- success: true,- toolName,-});--const executeMaintenanceRuntimeTool = async (- toolCall: ChatToolPayload,- input: MaintenanceToolFirstRuntimeInput,-): Promise<MaintenanceToolExecutionResult> => {- const args = parseToolArguments(toolCall.arguments);-- if (toolCall.apiName === 'listManagedSkills') {- return {- data: await input.tools.listManagedSkills({ agentId: input.agentId, userId: input.userId }),- isWrite: false,- success: true,- };- }-- if (toolCall.apiName === 'getManagedSkill') {- const skillDocumentId = toNullableString(args.skillDocumentId);- if (!skillDocumentId) return createToolError('skillDocumentId is required');-- return {- data: await input.tools.getManagedSkill({- agentId: input.agentId,- skillDocumentId,- userId: input.userId,- }),- isWrite: false,- success: true,- };- }-- if (toolCall.apiName === 'getEvidenceDigest') {- return {- data: await input.tools.getEvidenceDigest({- agentId: input.agentId,- evidenceIds: toStringArray(args.evidenceIds),- reviewWindowEnd: toNullableString(args.reviewWindowEnd) ?? input.context.reviewWindowEnd,- reviewWindowStart:- toNullableString(args.reviewWindowStart) ?? input.context.reviewWindowStart,- userId: input.userId,- }),- isWrite: false,- success: true,- };- }-- if (toolCall.apiName === 'listMaintenanceProposals') {- return {- data: await input.tools.listMaintenanceProposals({- agentId: input.agentId,- userId: input.userId,- }),- isWrite: false,- success: true,- };- }-- if (toolCall.apiName === 'readMaintenanceProposal') {- return {- data: await input.tools.readMaintenanceProposal({- proposalId: toNullableString(args.proposalId),- proposalKey: toNullableString(args.proposalKey),- userId: input.userId,- }),- isWrite: false,- success: true,- };- }-- if (toolCall.apiName === 'createMaintenanceProposal') {- return executeWriteTool('createMaintenanceProposal', () =>- input.tools.createMaintenanceProposal(- withUser<CreateMaintenanceProposalInput>(- 'createMaintenanceProposal',- args,- input,- toolCall.id,- {- actions: toUnknownArray(args.actions),- metadata: toRecord(args.metadata),- },- ),- ),- );- }-- if (toolCall.apiName === 'refreshMaintenanceProposal') {- const proposalId = toNullableString(args.proposalId);- if (!proposalId) return createToolError('proposalId is required');-- return executeWriteTool('refreshMaintenanceProposal', () =>- input.tools.refreshMaintenanceProposal(- withUser<RefreshMaintenanceProposalInput>(- 'refreshMaintenanceProposal',- args,- input,- toolCall.id,- {- proposalId,- },- ),- ),- );- }-- if (toolCall.apiName === 'supersedeMaintenanceProposal') {- const proposalId = toNullableString(args.proposalId);- const supersededBy = toNullableString(args.supersededBy);- if (!proposalId) return createToolError('proposalId is required');- if (!supersededBy) return createToolError('supersededBy is required');-- return executeWriteTool('supersedeMaintenanceProposal', () =>- input.tools.supersedeMaintenanceProposal(- withUser<SupersedeMaintenanceProposalInput>(- 'supersedeMaintenanceProposal',- args,- input,- toolCall.id,- {- proposalId,- supersededBy,- },- ),- ),- );- }-- if (toolCall.apiName === 'closeMaintenanceProposal') {- const proposalId = toNullableString(args.proposalId);- if (!proposalId) return createToolError('proposalId is required');-- return executeWriteTool('closeMaintenanceProposal', () =>- input.tools.closeMaintenanceProposal(- withUser<CloseMaintenanceProposalInput>(- 'closeMaintenanceProposal',- args,- input,- toolCall.id,- {- proposalId,- reason: toNullableString(args.reason),- },- ),- ),- );- }-- if (toolCall.apiName === 'writeMemory') {- const content = toNullableString(args.content);- if (!content) return createToolError('content is required');-- const evidenceRefs = toEvidenceRefs(args.evidenceRefs);- if (evidenceRefs.length === 0) return createToolError('evidenceRefs are required');-- return executeWriteTool('writeMemory', () =>- input.tools.writeMemory(- withUser<WriteMemoryInput>('writeMemory', args, input, toolCall.id, {- content,- evidenceRefs,- }),- ),- );- }-- if (toolCall.apiName === 'createSkillIfAbsent') {- return executeWriteTool('createSkillIfAbsent', () =>- input.tools.createSkillIfAbsent(- withUser<CreateSkillIfAbsentInput>('createSkillIfAbsent', args, input, toolCall.id, {- bodyMarkdown: toNullableString(args.bodyMarkdown) ?? '',- description: toNullableString(args.description),- name: toNullableString(args.name) ?? '',- title: toNullableString(args.title),- }),- ),- );- }-- if (toolCall.apiName === 'replaceSkillContentCAS') {- const skillDocumentId = toNullableString(args.skillDocumentId);- if (!skillDocumentId) return createToolError('skillDocumentId is required');-- return executeWriteTool('replaceSkillContentCAS', () =>- input.tools.replaceSkillContentCAS(- withUser<ReplaceSkillContentCASInput>('replaceSkillContentCAS', args, input, toolCall.id, {- baseSnapshot: toBaseSnapshot(args.baseSnapshot),- bodyMarkdown: toNullableString(args.bodyMarkdown) ?? '',- description: toNullableString(args.description),- skillDocumentId,- }),- ),- );- }-- return createToolError(`Unsupported maintenance tool: ${toolCall.apiName}`);-};--const createInitialState = ({- input,- manifestMap,- runtimeTools,-}: {- input: MaintenanceToolFirstRuntimeInput;- manifestMap: Record<string, LobeToolManifest>;- runtimeTools: ReturnType<typeof generateToolsFromManifest>;-}): AgentState => {- const createdAt = new Date().toISOString();- const operationId = `agent-signal-maintenance:${input.sourceId}`;- const messages: ChatStreamPayload['messages'] = [- { content: MAINTENANCE_TOOL_FIRST_SYSTEM_ROLE, role: 'system' },- { content: createMaintenanceRuntimePrompt(input), role: 'user' },- ];-- return {- cost: {- calculatedAt: createdAt,- currency: 'USD',- llm: { byModel: [], currency: 'USD', total: 0 },- tools: { byTool: [], currency: 'USD', total: 0 },- total: 0,- },- createdAt,- lastModified: createdAt,- maxSteps: Math.max(1, input.maxSteps),- messages,- metadata: {- agentId: input.agentId,- sourceId: input.sourceId,- trigger: RequestTrigger.AgentSignal,- userId: input.userId,- },- modelRuntimeConfig: {- model: input.model,- provider: DEFAULT_MINI_SYSTEM_AGENT_ITEM.provider,- },- operationId,- operationToolSet: {- enabledToolIds: [maintenanceToolFirstRuntimeToolIdentifier],- manifestMap,- sourceMap: { [maintenanceToolFirstRuntimeToolIdentifier]: 'builtin' },- tools: runtimeTools,- },- status: 'idle',- stepCount: 0,- toolManifestMap: manifestMap,- toolSourceMap: { [maintenanceToolFirstRuntimeToolIdentifier]: 'builtin' },- tools: runtimeTools,- usage: {- humanInteraction: {- approvalRequests: 0,- promptRequests: 0,- selectRequests: 0,- totalWaitingTimeMs: 0,- },- llm: {- apiCalls: 0,- processingTimeMs: 0,- tokens: { input: 0, output: 0, total: 0 },- },- tools: {- byTool: [],- totalCalls: 0,- totalTimeMs: 0,- },- },- userInterventionConfig: { approvalMode: 'headless' },- };-};--/**- * Runs the tool-first maintenance agent with a bounded AgentRuntime LLM/tool loop.- *- * Triggering workflow:- *- * createMaintenanceAgentRunner- * -> future server runtime backend- * -> `agent_signal.maintenance_agent.run`- * -> {@link runMaintenanceToolFirstRuntime}- *- * Upstream:- * - {@link createInitialState}- *- * Downstream:- * - {@link executeMaintenanceRuntimeTool}- *- * Use when:- * - Nightly maintenance needs real LLM -> tool -> LLM behavior- * - The caller already has scoped safe maintenance tools and a model runtime- *- * Expects:- * - Tools enforce their own idempotency, preflight, and receipt contracts- * - `maxSteps` is a positive finite loop budget- *- * Returns:- * - Final streamed assistant content, step count, model usage, tool calls, and write outcomes- */-export const runMaintenanceToolFirstRuntime = async (- input: MaintenanceToolFirstRuntimeInput,-): Promise<MaintenanceToolFirstRuntimeResult> =>- tracer.startActiveSpan(- 'agent_signal.maintenance_agent.run',- {- attributes: {- 'agent.signal.agent_id': input.agentId,- 'agent.signal.maintenance_agent.max_steps': input.maxSteps,- 'agent.signal.source_id': input.sourceId,- 'agent.signal.user_id': input.userId,- },- },- async (runSpan) => {- const maxSteps = Math.max(1, input.maxSteps);- const toolNameResolver = new ToolNameResolver();- const manifestMap = {- [maintenanceToolFirstRuntimeToolIdentifier]: maintenanceToolFirstRuntimeManifest,- };- const runtimeTools = generateToolsFromManifest(maintenanceToolFirstRuntimeManifest);- const offeredToolNames = runtimeTools.map((tool) => tool.function.name);- const contentParts: string[] = [];- const toolCalls: ChatToolPayload[] = [];- const usage: ModelUsage[] = [];- const writeOutcomes: MaintenanceToolFirstRuntimeWriteOutcome[] = [];- const runtime = new AgentRuntime(- new GeneralChatAgent({- compressionConfig: { enabled: false },- modelRuntimeConfig: {- model: input.model,- provider: DEFAULT_MINI_SYSTEM_AGENT_ITEM.provider,- },- operationId: `agent-signal-maintenance:${input.sourceId}`,- userId: input.userId,- }),- {- executors: {- call_llm: async (instruction, state) => {- const payload = (- instruction as { payload: { messages: ChatStreamPayload['messages'] } }- ).payload;- let content = '';- let modelUsage: ModelUsage | undefined;- let rawToolCalls: MessageToolCall[] = [];-- const response = await input.modelRuntime.chat(- {- messages: payload.messages,- model: input.model,- stream: true,- tools: state.forceFinish ? [] : runtimeTools,- },- {- callback: {- onCompletion: (data) => {- modelUsage = data.usage;- },- onText: (text) => {- content += text;- },- onToolsCalling: ({ toolsCalling }) => {- rawToolCalls = toolsCalling;- },- },- metadata: { trigger: RequestTrigger.AgentSignal },- },- );- await consumeStreamUntilDone(response);-- if (content) contentParts.push(content);- if (modelUsage) usage.push(modelUsage);-- const assistantMessageId = `maintenance-assistant-${state.stepCount}`;- const resolvedToolCalls = resolveMaintenanceToolCalls({- manifestMap,- offeredToolNames,- rawToolCalls,- toolNameResolver,- });- toolCalls.push(...resolvedToolCalls);-- const newState = structuredClone(state);- newState.messages.push({- content,- id: assistantMessageId,- role: 'assistant',- ...(rawToolCalls.length > 0 ? { tool_calls: rawToolCalls } : {}),- });-- return {- events: [- {- result: { content, tool_calls: rawToolCalls, usage: modelUsage },- type: 'llm_result',- },- ],- newState,- nextContext: {- payload: {- hasToolsCalling: resolvedToolCalls.length > 0,- parentMessageId: assistantMessageId,- result: { content, tool_calls: rawToolCalls },- toolsCalling: resolvedToolCalls,- },- phase: 'llm_result',- session: {- messageCount: newState.messages.length,- sessionId: newState.operationId,- status: newState.status,- stepCount: newState.stepCount,- },- stepUsage: modelUsage,- } satisfies AgentRuntimeContext,- };- },- call_tool: async (instruction, state) => {- const payload = (- instruction as {- payload: {- parentMessageId: string;- toolCalling: ChatToolPayload;- };- }- ).payload;- const startedAt = Date.now();- let execution: MaintenanceToolExecutionResult;-- try {- execution = await executeMaintenanceRuntimeTool(payload.toolCalling, input);- } catch (error) {- execution = {- data: { error: MAINTENANCE_TOOL_ERROR_MESSAGE },- isWrite: false,- success: false,- };- }-- if (execution.isWrite && execution.toolName && execution.success) {- writeOutcomes.push({- result: execution.data as MaintenanceToolWriteResult,- toolName: execution.toolName,- });- }-- const content = JSON.stringify(execution.data);- const newState = structuredClone(state);- newState.messages.push({- content,- role: 'tool',- tool_call_id: payload.toolCalling.id,- });-- return {- events: [- {- id: payload.toolCalling.id,- result: { content, success: execution.success },- type: 'tool_result',- },- ],- newState,- nextContext: {- payload: {- data: execution.data,- executionTime: Date.now() - startedAt,- isSuccess: execution.success,- parentMessageId: payload.parentMessageId,- toolCall: payload.toolCalling,- toolCallId: payload.toolCalling.id,- },- phase: 'tool_result',- session: {- messageCount: newState.messages.length,- sessionId: newState.operationId,- status: newState.status,- stepCount: newState.stepCount,- },- } satisfies AgentRuntimeContext,- };- },- },- },- );- let state = createInitialState({ input, manifestMap, runtimeTools });- let context: AgentRuntimeContext = {- payload: {- model: input.model,- provider: DEFAULT_MINI_SYSTEM_AGENT_ITEM.provider,- tools: runtimeTools,- },- phase: 'user_input',- session: {- messageCount: state.messages.length,- sessionId: state.operationId,- status: state.status,- stepCount: state.stepCount,- },- };-- try {- // NOTICE:- // The public maxSteps policy lives in AgentRuntime via state.maxSteps.- // The outer loop is only a hard safety cap so force-finish and the final- // tool-result continuation can run after AgentRuntime crosses maxSteps.- // Source/context: packages/agent-runtime/src/core/runtime.ts forceFinish handling.- // Removal condition: AgentRuntime exposes a bounded run-until-done API.- const hardSafetyStepCap = maxSteps + FORCE_FINISH_EXTRA_STEPS;-- for (let stepIndex = 0; stepIndex < hardSafetyStepCap; stepIndex += 1) {- if (- state.status === 'done' ||- state.status === 'error' ||- state.status === 'interrupted'- ) {- break;- }-- const result = await tracer.startActiveSpan(- 'agent_signal.maintenance_agent.step',- {- attributes: {- 'agent.signal.agent_id': input.agentId,- 'agent.signal.maintenance_agent.max_steps': maxSteps,- 'agent.signal.maintenance_agent.step_count': state.stepCount + 1,- 'agent.signal.source_id': input.sourceId,- 'agent.signal.user_id': input.userId,- },- },- async (stepSpan) => {- try {- const stepResult = await runtime.step(state, context);- stepSpan.setAttribute(- 'agent.signal.maintenance_agent.step_count',- stepResult.newState.stepCount,- );-- if (stepResult.newState.status === 'error') {- stepSpan.setStatus({ code: SpanStatusCode.ERROR });- } else {- stepSpan.setStatus({ code: SpanStatusCode.OK });- }-- return stepResult;- } catch (error) {- stepSpan.recordException(error as Error);- stepSpan.setStatus({- code: SpanStatusCode.ERROR,- message: getErrorMessage(error),- });-- throw error;- } finally {- stepSpan.end();- }- },- );-- state = result.newState;-- if (!result.nextContext) break;- context = result.nextContext;- }-- runSpan.setAttribute('agent.signal.maintenance_agent.step_count', state.stepCount);- runSpan.setStatus({- code: state.status === 'error' ? SpanStatusCode.ERROR : SpanStatusCode.OK,- });-- return {- content: contentParts.join(''),- stepCount: state.stepCount,- toolCalls,- usage,- writeOutcomes,- };- } catch (error) {- runSpan.recordException(error as Error);- runSpan.setStatus({ code: SpanStatusCode.ERROR, message: getErrorMessage(error) });-- throw error;- } finally {- runSpan.end();- }- },- );diff --git a/src/server/services/agentSignal/services/maintenance/agentRunner.ts b/src/server/services/agentSignal/services/maintenance/agentRunner.tsdeleted file mode 100644index 11768b49820..00000000000--- a/src/server/services/agentSignal/services/maintenance/agentRunner.ts+++ /dev/null@@ -1,178 +0,0 @@-import { SpanStatusCode } from '@lobechat/observability-otel/api';-import { tracer } from '@lobechat/observability-otel/modules/agent-signal';--import type { NightlyReviewContext } from './nightlyCollector';-import type { MaintenanceReviewIdea } from './proposal';-import type { MaintenanceTools } from './tools';-import type { MaintenancePlan, MaintenanceReviewRunResult } from './types';-import { MaintenanceReviewScope, ReviewRunStatus } from './types';--/** Default step budget for one nightly maintenance agent run. */-const DEFAULT_MAX_MAINTENANCE_AGENT_STEPS = 10;--/**- * Result envelope returned by the bounded maintenance agent runner.- */-export interface MaintenanceAgentRunResult {- /** Executed tool or legacy executor result to persist as receipts. */- execution: MaintenanceReviewRunResult;- /** Non-actionable ideas collected during the run. */- ideas?: MaintenanceReviewIdea[];- /** Frozen deterministic plan used for Daily Brief proposal projection. */- projectionPlan: MaintenancePlan;- /** Optional number of agent/tool steps consumed by the backend runner. */- stepCount?: number;-}--/**- * Input passed to a maintenance runner backend.- */-export interface MaintenanceAgentRunnerRunInput {- /** Bounded digest context collected for one nightly review window. */- context: NightlyReviewContext;- /** User-local nightly date used in projected maintenance plans. */- localDate?: string;- /** Maximum backend agent/tool steps allowed for this run. */- maxSteps: number;- /** Review scope attached to projected plans and tracing. */- reviewScope: MaintenanceReviewScope;- /** Stable source id used to generate action idempotency keys. */- sourceId: string;- /** Safe read/write tools available to the backend runner. */- tools: MaintenanceTools;- /** Stable user id owning this run. */- userId: string;-}--/**- * Options for creating a bounded maintenance agent runner.- */-export interface MaintenanceAgentRunnerOptions {- /**- * Maximum backend agent/tool steps.- *- * @default 10- */- maxSteps?: number;- /** Backend implementation that may call tools and must return a projected plan. */- run: (input: MaintenanceAgentRunnerRunInput) => Promise<MaintenanceAgentRunResult>;- /** Safe tools exposed to the backend implementation. */- tools: MaintenanceTools;-}--/**- * Input for one bounded nightly maintenance run.- */-export interface MaintenanceAgentRunnerInput {- /** Bounded digest context collected for one nightly review window. */- context: NightlyReviewContext;- /** User-local nightly date used in projected maintenance plans. */- localDate?: string;- /** Stable source id used to generate action idempotency keys. */- sourceId: string;- /** Stable user id owning this run. */- userId: string;-}--const createFailedProjectionPlan = (input: MaintenanceAgentRunnerInput): MaintenancePlan => ({- actions: [],- localDate: input.localDate,- plannerVersion: 'maintenance-agent-runner-fallback-v1',- reviewScope: MaintenanceReviewScope.Nightly,- summary: 'Maintenance review runner failed before producing a valid plan.',-});--/**- * Creates a bounded runner for nightly maintenance agent execution.- *- * Call stack:- *- * createNightlyReviewSourceHandler- * -> {@link createMaintenanceAgentRunner}- * -> injected `run`- * -> safe maintenance tools- *- * Use when:- * - Nightly self-review should execute through one bounded runner boundary- * - Tests need to verify fallback and source-id normalization without DB or LLMs- *- * Expects:- * - `sourceId` is stable for idempotency- * - The backend `run` returns both execution output and the frozen projection plan- *- * Returns:- * - A runner that traces the run, injects tools, enforces the configured step budget, and- * returns a conservative failed result if the backend cannot produce a result- */-export const createMaintenanceAgentRunner = (options: MaintenanceAgentRunnerOptions) => {- const maxSteps = Math.max(1, options.maxSteps ?? DEFAULT_MAX_MAINTENANCE_AGENT_STEPS);-- return {- run: async (input: MaintenanceAgentRunnerInput): Promise<MaintenanceAgentRunResult> =>- tracer.startActiveSpan(- 'agent_signal.maintenance_agent.runner.run',- {- attributes: {- 'agent.signal.agent_id': input.context.agentId,- 'agent.signal.maintenance_agent.max_steps': maxSteps,- 'agent.signal.review_scope': MaintenanceReviewScope.Nightly,- 'agent.signal.source_id': input.sourceId,- 'agent.signal.user_id': input.userId,- },- },- async (span) => {- try {- const result = await options.run({- ...input,- maxSteps,- reviewScope: MaintenanceReviewScope.Nightly,- tools: options.tools,- });- const execution = {- ...result.execution,- sourceId: result.execution.sourceId ?? input.sourceId,- };-- span.setAttribute(- 'agent.signal.maintenance_agent.plan_action_count',- result.projectionPlan.actions.length,- );- span.setAttribute(- 'agent.signal.maintenance_agent.execution_action_count',- execution.actions.length,- );- if (typeof result.stepCount === 'number') {- span.setAttribute('agent.signal.maintenance_agent.step_count', result.stepCount);- }- span.setStatus({ code: SpanStatusCode.OK });-- return {- ...result,- execution,- };- } catch (error) {- span.setStatus({- code: SpanStatusCode.ERROR,- message:- error instanceof Error- ? error.message- : 'AgentSignal maintenance agent runner failed',- });- span.recordException(error as Error);-- return {- execution: {- actions: [],- sourceId: input.sourceId,- status: ReviewRunStatus.Failed,- },- projectionPlan: createFailedProjectionPlan(input),- stepCount: maxSteps,- };- } finally {- span.end();- }- },- ),- };-};diff --git a/src/server/services/agentSignal/services/maintenance/executor.ts b/src/server/services/agentSignal/services/maintenance/executor.tsdeleted file mode 100644index fb69cc42dbe..00000000000--- a/src/server/services/agentSignal/services/maintenance/executor.ts+++ /dev/null@@ -1,201 +0,0 @@-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.tsdeleted file mode 100644index b0926d58983..00000000000--- a/src/server/services/agentSignal/services/maintenance/memory.ts+++ /dev/null@@ -1,113 +0,0 @@-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/nightlyDocumentActivity.ts b/src/server/services/agentSignal/services/maintenance/nightlyDocumentActivity.tsdeleted file mode 100644index ef831a3f5cc..00000000000--- a/src/server/services/agentSignal/services/maintenance/nightlyDocumentActivity.ts+++ /dev/null@@ -1,75 +0,0 @@-import type { AgentSignalDocumentActivityRow } from '@/database/models/agentSignal/reviewContext';--import type { DocumentActivityDigest } from './nightlyCollector';--/**- * Maps database document activity rows into nightly maintenance buckets.- *- * Use when:- * - Server runtime adapters need to keep DB row shape separate from reviewer context shape- * - Tests need deterministic document bucket behavior without opening database connections- *- * Expects:- * - Rows are already scoped to one user, one agent, and one review window- *- * Returns:- * - Document activity buckets where only skill bucket rows can support skill maintenance- */-export const mapNightlyDocumentActivityRows = (- rows: AgentSignalDocumentActivityRow[],-): DocumentActivityDigest => {- const digest: DocumentActivityDigest = {- ambiguousBucket: [],- excludedSummary: { count: 0, reasons: [] },- generalDocumentBucket: [],- skillBucket: [],- };-- for (const row of rows) {- const base = {- agentDocumentId: row.agentDocumentId,- documentId: row.documentId,- title: row.title,- updatedAt: row.updatedAt.toISOString(),- };-- if (row.hintIsSkill === true) {- digest.skillBucket.push({- ...base,- hintIsSkill: true,- reason: 'metadata.agentSignal.hintIsSkill=true',- skillFileType: row.policyLoadFormat,- });- continue;- }-- if (- row.templateId === 'agent-skill' ||- row.templateId === 'skills/index' ||- row.templateId === 'skills/bundle'- ) {- digest.skillBucket.push({- ...base,- hintIsSkill: false,- reason: `templateId=${row.templateId}`,- skillFileType: row.templateId,- });- continue;- }-- if (row.hintIsSkill === false) {- digest.generalDocumentBucket.push({- ...base,- reason: 'metadata.agentSignal.hintIsSkill=false',- });- continue;- }-- digest.ambiguousBucket.push({- ...base,- reason: 'missing agentSignal hint metadata',- });- }-- return digest;-};diff --git a/src/server/services/agentSignal/services/maintenance/planner.ts b/src/server/services/agentSignal/services/maintenance/planner.tsdeleted file mode 100644index 0855b89da90..00000000000--- a/src/server/services/agentSignal/services/maintenance/planner.ts+++ /dev/null@@ -1,366 +0,0 @@-import { SpanStatusCode } from '@lobechat/observability-otel/api';-import { tracer } from '@lobechat/observability-otel/modules/agent-signal';--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;- const bodyMarkdown = getStringField(draft.value, 'bodyMarkdown');-- if (!skillDocumentId || !bodyMarkdown) return undefined;-- return {- domain: 'skill',- input: {- bodyMarkdown,- 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 isBroadInPlaceRefineDraft = (draft: MaintenanceActionDraft) =>- draft.actionType === 'refine_skill' &&- draft.policyHints?.mutationScope === 'broad' &&- Boolean(draft.target?.skillDocumentId);--const isStrongAutoApplySkillDraft = (draft: MaintenanceActionDraft) =>- draft.confidence >= SKILL_AUTO_APPLY_CONFIDENCE_THRESHOLD &&- draft.policyHints?.evidenceStrength === 'strong' &&- (draft.policyHints?.mutationScope === 'small' || isBroadInPlaceRefineDraft(draft));--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 (!isStrongAutoApplySkillDraft(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.actionType === 'noop') {- return { applyMode: MaintenanceApplyMode.Skip, risk: MaintenanceRisk.Low };- }-- if (draft.actionType === 'proposal_only') {- return { applyMode: MaintenanceApplyMode.ProposalOnly, risk: MaintenanceRisk.Medium };- }-- if (draft.evidenceRefs.length === 0 || draft.confidence < LOW_RISK_CONFIDENCE_THRESHOLD) {- return { applyMode: MaintenanceApplyMode.Skip, risk: MaintenanceRisk.High };- }-- 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 => {- return tracer.startActiveSpan(- 'agent_signal.nightly_review.planner.plan',- {- attributes: {- 'agent.signal.nightly.draft_action_count': request.draft.actions.length,- 'agent.signal.nightly.finding_count': request.draft.findings.length,- 'agent.signal.nightly.max_auto_apply_actions': maxAutoApplyActions,- 'agent.signal.nightly.review_scope': request.reviewScope,- 'agent.signal.source_id': request.sourceId,- 'agent.signal.user_id': request.userId,- },- },- (span) => {- try {- 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,- };- });- const plan = {- actions,- localDate: request.localDate,- plannerVersion,- reviewScope: request.reviewScope,- summary: request.draft.summary,- };-- span.setAttribute('agent.signal.nightly.plan_action_count', actions.length);- span.setAttribute('agent.signal.nightly.auto_apply_count', autoApplyCount);- span.setAttribute(- 'agent.signal.nightly.proposal_count',- actions.filter((action) => action.applyMode === MaintenanceApplyMode.ProposalOnly)- .length,- );- span.setAttribute(- 'agent.signal.nightly.skip_count',- actions.filter((action) => action.applyMode === MaintenanceApplyMode.Skip).length,- );- span.setStatus({ code: SpanStatusCode.OK });-- return plan;- } catch (error) {- span.setStatus({- code: SpanStatusCode.ERROR,- message:- error instanceof Error- ? error.message- : 'AgentSignal nightly review planning failed',- });- span.recordException(error as Error);-- throw error;- } finally {- span.end();- }- },- );- },- };-};diff --git a/src/server/services/agentSignal/services/maintenance/serverRuntime.ts b/src/server/services/agentSignal/services/maintenance/serverRuntime.tsdeleted file mode 100644index 59a7bb2796f..00000000000--- a/src/server/services/agentSignal/services/maintenance/serverRuntime.ts+++ /dev/null@@ -1,1990 +0,0 @@-import { DEFAULT_MINI_SYSTEM_AGENT_ITEM } from '@lobechat/const';-import type { GenerateObjectSchema } from '@lobechat/model-runtime';-import { SpanStatusCode } from '@lobechat/observability-otel/api';-import { tracer } from '@lobechat/observability-otel/modules/agent-signal';-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 { BriefModel } from '@/database/models/brief';-import type { BriefItem } from '@/database/schemas';-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 { runMaintenanceToolFirstRuntime } from './agent';-import { createMaintenanceAgentRunner } from './agentRunner';-import { createBriefMaintenanceService, createServerMaintenanceBriefWriter } from './brief';-import { projectMaintenanceToolRuntimeRun } from './briefProjection';-import { createMaintenanceExecutorService } from './executor';-import { createMemoryMaintenanceService } from './memory';-import type {- FeedbackActivityDigest,- NightlyReviewContext,- NightlyReviewManagedSkillSummary,- NightlyReviewRelevantMemorySummary,- NightlyReviewTopicActivityRow,- ProposalActivityDigest,- ReceiptActivityDigest,- ToolActivityDigest,-} from './nightlyCollector';-import { createNightlyReviewService } from './nightlyCollector';-import { mapNightlyDocumentActivityRows } from './nightlyDocumentActivity';-import { createMaintenancePlannerService } from './planner';-import type { MaintenanceProposalAction, MaintenanceProposalMetadata } from './proposal';-import {- getMaintenanceProposalFromBriefMetadata,- refreshMaintenanceProposal,- supersedeMaintenanceProposal,-} from './proposal';-import { createMaintenanceProposalPreflightService } from './proposalPreflight';-import { createMaintenanceProposalSnapshotService } from './proposalSnapshot';-import { createSkillManagementService } from './skill';-import type {- CloseMaintenanceProposalInput,- CreateMaintenanceProposalInput,- CreateSkillIfAbsentInput,- MaintenanceToolOperationReservation,- MaintenanceToolReceiptInput,- MaintenanceToolWriteResult,- RefreshMaintenanceProposalInput,- ReplaceSkillContentCASInput,- SupersedeMaintenanceProposalInput,- WriteMemoryInput,-} from './tools';-import { createMaintenanceTools } from './tools';-import type {- EvidenceRef,- MaintenanceActionDraft,- MaintenanceActionPolicyHints,- MaintenanceActionTarget,- MaintenancePlanDraft,-} from './types';-import { MaintenanceReviewScope, MaintenanceRisk } 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', 'null'] },- type: {- enum: [- 'topic',- 'message',- 'operation',- 'source',- 'receipt',- 'tool_call',- 'task',- 'agent_document',- 'memory',- ],- type: 'string',- },- },- required: ['id', 'summary', 'type'],- type: 'object',- },- type: 'array',- },- policyHints: {- additionalProperties: false,- properties: {- evidenceStrength: {- enum: ['weak', 'medium', 'strong', null],- type: ['string', 'null'],- },- mutationScope: { enum: ['small', 'broad', null], type: ['string', 'null'] },- persistence: { enum: ['stable', 'temporal', null], type: ['string', 'null'] },- sensitivity: { enum: ['normal', 'sensitive', null], type: ['string', 'null'] },- userExplicitness: {- enum: ['explicit', 'implicit', 'inferred', null],- type: ['string', 'null'],- },- },- required: [- 'evidenceStrength',- 'mutationScope',- 'persistence',- 'sensitivity',- 'userExplicitness',- ],- type: 'object',- },- rationale: { type: 'string' },- target: {- additionalProperties: false,- properties: {- memoryId: { type: ['string', 'null'] },- skillDocumentId: { type: ['string', 'null'] },- skillName: { type: ['string', 'null'] },- targetReadonly: { type: ['boolean', 'null'] },- taskIds: {- items: { type: 'string' },- type: ['array', 'null'],- },- topicIds: {- items: { type: 'string' },- type: ['array', 'null'],- },- },- required: [- 'memoryId',- 'skillDocumentId',- 'skillName',- 'targetReadonly',- 'taskIds',- 'topicIds',- ],- type: 'object',- },- value: {- additionalProperties: false,- properties: {- bodyMarkdown: { type: ['string', 'null'] },- canonicalSkillDocumentId: { type: ['string', 'null'] },- content: { type: ['string', 'null'] },- description: { type: ['string', 'null'] },- name: { type: ['string', 'null'] },- patch: { type: ['string', 'null'] },- readonly: { type: ['boolean', 'null'] },- skillDocumentId: { type: ['string', 'null'] },- sourceSkillIds: {- items: { type: 'string' },- type: ['array', 'null'],- },- targetReadonly: { type: ['boolean', 'null'] },- title: { type: ['string', 'null'] },- },- required: [- 'bodyMarkdown',- 'canonicalSkillDocumentId',- 'content',- 'description',- 'name',- 'patch',- 'readonly',- 'skillDocumentId',- 'sourceSkillIds',- 'targetReadonly',- 'title',- ],- type: ['object', 'null'],- },- },- required: [- 'actionType',- 'confidence',- 'evidenceRefs',- 'policyHints',- 'rationale',- 'target',- 'value',- ],- type: 'object',- },- type: 'array',- },- findings: {- items: {- additionalProperties: false,- properties: {- evidenceRefs: {- items: {- additionalProperties: false,- properties: {- id: { type: 'string' },- summary: { type: ['string', 'null'] },- type: { type: 'string' },- },- required: ['id', 'summary', '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;--/** Bounded unresolved Daily Brief read budget for proposal activity digesting. */-const NIGHTLY_PROPOSAL_ACTIVITY_LIMIT = 20;--/** Daily Brief trigger used by Agent Signal nightly maintenance proposals. */-const NIGHTLY_REVIEW_BRIEF_TRIGGER = 'agent-signal:nightly-review';--const ACTIVE_PROPOSAL_STATUSES = new Set(['accepted', 'applying', 'pending']);--interface ProposalBriefReader {- listUnresolvedByAgentAndTrigger: (options: {- agentId: string;- limit?: number;- trigger: string;- }) => Promise<Awaited<ReturnType<BriefModel['listUnresolvedByAgentAndTrigger']>>>;-}--// 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().nullish(),- type: z.enum([- 'topic',- 'message',- 'operation',- 'source',- 'receipt',- 'tool_call',- 'task',- 'agent_document',- 'memory',- ]),- })- .transform(- (value): EvidenceRef => ({- id: value.id,- ...(value.summary ? { summary: value.summary } : {}),- type: value.type,- }),- );--const MaintenanceActionDraftSchema: z.ZodType<MaintenanceActionDraft, z.ZodTypeDef, unknown> =- 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']).nullish(),- mutationScope: z.enum(['small', 'broad']).nullish(),- persistence: z.enum(['stable', 'temporal']).nullish(),- sensitivity: z.enum(['normal', 'sensitive']).nullish(),- userExplicitness: z.enum(['explicit', 'implicit', 'inferred']).nullish(),- })- .nullable()- .transform((value): MaintenanceActionPolicyHints | undefined =>- value- ? {- ...(value.evidenceStrength ? { evidenceStrength: value.evidenceStrength } : {}),- ...(value.mutationScope ? { mutationScope: value.mutationScope } : {}),- ...(value.persistence ? { persistence: value.persistence } : {}),- ...(value.sensitivity ? { sensitivity: value.sensitivity } : {}),- ...(value.userExplicitness ? { userExplicitness: value.userExplicitness } : {}),- }- : undefined,- )- .optional(),- rationale: z.string(),- target: z- .object({- memoryId: z.string().nullish(),- skillDocumentId: z.string().nullish(),- skillName: z.string().nullish(),- targetReadonly: z.boolean().nullish(),- taskIds: z.array(z.string()).nullish(),- topicIds: z.array(z.string()).nullish(),- })- .nullable()- .transform((value): MaintenanceActionTarget | undefined =>- value- ? {- ...(value.memoryId ? { memoryId: value.memoryId } : {}),- ...(value.skillDocumentId ? { skillDocumentId: value.skillDocumentId } : {}),- ...(value.skillName ? { skillName: value.skillName } : {}),- ...(typeof value.targetReadonly === 'boolean'- ? { targetReadonly: value.targetReadonly }- : {}),- ...(value.taskIds ? { taskIds: value.taskIds } : {}),- ...(value.topicIds ? { topicIds: value.topicIds } : {}),- }- : undefined,- )- .optional(),- value: z.unknown().optional(),- });--const MaintenancePlanDraftSchema: z.ZodType<MaintenancePlanDraft, z.ZodTypeDef, unknown> = 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(),- },-);--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') ?? '';- 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,-) => {- return tracer.startActiveSpan(- 'agent_signal.maintenance_review_agent.run',- {- attributes: {- 'agent.signal.agent_id': context.agentId,- 'agent.signal.model': DEFAULT_MINI_SYSTEM_AGENT_ITEM.model,- 'agent.signal.provider': DEFAULT_MINI_SYSTEM_AGENT_ITEM.provider,- 'agent.signal.user_id': userId,- },- },- async (span) => {- try {- 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 } },- );- const draft = MaintenancePlanDraftSchema.parse(result);-- span.setAttribute('agent.signal.nightly.draft_action_count', draft.actions.length);- span.setAttribute('agent.signal.nightly.finding_count', draft.findings.length);- span.setStatus({ code: SpanStatusCode.OK });-- return draft;- } catch (error) {- span.setStatus({- code: SpanStatusCode.ERROR,- message:- error instanceof Error ? error.message : 'AgentSignal maintenance reviewer failed',- });- span.recordException(error as Error);-- throw error;- } finally {- span.end();- }- },- );-};--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,- })),- };-};--const getProposalTargetDigest = (- proposal: NonNullable<ReturnType<typeof getMaintenanceProposalFromBriefMetadata>>,-): Pick<ProposalActivityDigest['active'][number], 'targetId' | 'targetTitle'> => {- const action = proposal.actions[0];- const target = action?.target;-- return {- ...(target?.skillDocumentId- ? { targetId: target.skillDocumentId }- : target?.memoryId- ? { targetId: target.memoryId }- : target?.skillName- ? { targetId: target.skillName }- : {}),- ...(action?.baseSnapshot?.targetTitle ? { targetTitle: action.baseSnapshot.targetTitle } : {}),- };-};--const getProposalEvidenceCount = (- proposal: NonNullable<ReturnType<typeof getMaintenanceProposalFromBriefMetadata>>,-) => {- const evidenceRefs = new Map<string, EvidenceRef>();-- for (const evidenceRef of proposal.evidenceRefs ?? []) {- evidenceRefs.set(`${evidenceRef.type}:${evidenceRef.id}`, evidenceRef);- }-- for (const action of proposal.actions) {- for (const evidenceRef of action.evidenceRefs) {- evidenceRefs.set(`${evidenceRef.type}:${evidenceRef.id}`, evidenceRef);- }- }-- return evidenceRefs.size;-};--const hasPendingProposalExpired = ({ expiresAt, now }: { expiresAt: string; now: string }) => {- const expiresAtMs = new Date(expiresAt).getTime();- const nowMs = new Date(now).getTime();-- return Number.isFinite(expiresAtMs) && Number.isFinite(nowMs) && expiresAtMs <= nowMs;-};--const isNoopProposal = (- proposal: NonNullable<ReturnType<typeof getMaintenanceProposalFromBriefMetadata>>,-) =>- proposal.actionType === 'noop' ||- proposal.actions.every((action) => action.actionType === 'noop');--/**- * Lists existing server-side maintenance proposal activity for one agent.- *- * Use when:- * - Nightly review context needs unresolved proposal state- * - Tests need the server adapter behavior without booting the full runtime- *- * Expects:- * - `briefModel` applies user, agent, trigger, and unresolved filters before the limit- * - `now` is an ISO timestamp used to treat expired pending proposals as inactive- * - Stored metadata may be malformed and must be treated as absent- *- * Returns:- * - Active unresolved proposal digests plus unresolved status counts- */-export const listServerProposalActivity = async ({- agentId,- briefModel,- now = new Date().toISOString(),- userId,-}: {- agentId: string;- briefModel: ProposalBriefReader;- now?: string;- userId: string;-}): Promise<ProposalActivityDigest> =>- tracer.startActiveSpan(- 'agent_signal.nightly_review.collector.list_proposal_activity',- {- attributes: {- 'agent.signal.agent_id': agentId,- 'agent.signal.nightly.proposal_read_limit': NIGHTLY_PROPOSAL_ACTIVITY_LIMIT,- 'agent.signal.user_id': userId,- },- },- async (span) => {- try {- const rows = await briefModel.listUnresolvedByAgentAndTrigger({- agentId,- limit: NIGHTLY_PROPOSAL_ACTIVITY_LIMIT,- trigger: NIGHTLY_REVIEW_BRIEF_TRIGGER,- });- const digest: ProposalActivityDigest = {- active: [],- dismissedCount: 0,- expiredCount: 0,- staleCount: 0,- supersededCount: 0,- };- let validProposalCount = 0;-- for (const brief of rows) {- if (brief.agentId !== agentId) continue;- if (brief.trigger !== NIGHTLY_REVIEW_BRIEF_TRIGGER) continue;-- const proposal = getMaintenanceProposalFromBriefMetadata(brief.metadata);- if (!proposal) continue;- if (isNoopProposal(proposal)) continue;-- validProposalCount += 1;-- if (proposal.status === 'dismissed') digest.dismissedCount += 1;- if (proposal.status === 'expired') digest.expiredCount += 1;- if (proposal.status === 'stale') digest.staleCount += 1;- if (proposal.status === 'superseded') digest.supersededCount += 1;-- if (- proposal.status === 'pending' &&- hasPendingProposalExpired({ expiresAt: proposal.expiresAt, now })- ) {- digest.expiredCount += 1;- continue;- }-- if (!ACTIVE_PROPOSAL_STATUSES.has(proposal.status)) continue;-- digest.active.push({- actionType: proposal.actionType,- createdAt: proposal.createdAt,- evidenceCount: getProposalEvidenceCount(proposal),- expiresAt: proposal.expiresAt,- proposalId: brief.id,- proposalKey: proposal.proposalKey,- status: proposal.status,- summary: brief.summary,- ...getProposalTargetDigest(proposal),- updatedAt: proposal.updatedAt,- });- }-- span.setAttribute('agent.signal.nightly.proposal_unresolved_row_count', rows.length);- span.setAttribute('agent.signal.nightly.proposal_valid_count', validProposalCount);- span.setAttribute('agent.signal.nightly.proposal_active_count', digest.active.length);- span.setAttribute('agent.signal.nightly.proposal_dismissed_count', digest.dismissedCount);- span.setAttribute('agent.signal.nightly.proposal_expired_count', digest.expiredCount);- span.setAttribute('agent.signal.nightly.proposal_stale_count', digest.staleCount);- span.setAttribute('agent.signal.nightly.proposal_superseded_count', digest.supersededCount);- span.setStatus({ code: SpanStatusCode.OK });-- return digest;- } catch (error) {- span.setStatus({- code: SpanStatusCode.ERROR,- message:- error instanceof Error- ? error.message- : 'AgentSignal nightly proposal activity read failed',- });- span.recordException(error as Error);-- throw error;- } finally {- span.end();- }- },- );--const NIGHTLY_REVIEW_SOURCE_TYPE = 'agent.nightly_review.requested';-const MAINTENANCE_OPERATION_STATE_TTL_SECONDS = AGENT_SIGNAL_DEFAULTS.receiptTtlSeconds;--const maintenanceOperationScopeKey = (idempotencyKey: string) =>- `maintenance-operation:${idempotencyKey}`;--const maintenanceOperationReserveKey = (idempotencyKey: string) =>- `maintenance-operation-reserve:${idempotencyKey}`;--const parseStoredOperationResult = (- payload: Record<string, string> | undefined,-): MaintenanceToolWriteResult | undefined => {- if (!payload?.result) return;-- try {- const result = JSON.parse(payload.result) as MaintenanceToolWriteResult;-- if (- result.status === 'applied' ||- result.status === 'deduped' ||- result.status === 'failed' ||- result.status === 'proposed' ||- result.status === 'skipped_stale' ||- result.status === 'skipped_unsupported'- ) {- return result;- }- } catch {- return;- }-};--const createSkippedOperationResult = (): MaintenanceToolWriteResult => ({- status: 'skipped_unsupported',- summary:- 'Maintenance operation is already reserved or Redis is unavailable; skipped to avoid duplicate mutation.',-});--const reserveMaintenanceOperation = async (- idempotencyKey: string,-): Promise<MaintenanceToolOperationReservation> => {- const scopeKey = maintenanceOperationScopeKey(idempotencyKey);- const existing = parseStoredOperationResult(await redisSourceEventStore.readWindow(scopeKey));-- if (existing) return { existing, reserved: false };-- // NOTICE:- // Redis is the only available cross-worker idempotency boundary for nightly tool writes.- // `tryDedupe` also returns false when the Redis client is unavailable, so the safe fallback is- // to skip mutation instead of writing without a durable reservation.- // Source/context: `src/server/services/agentSignal/store/adapters/redis/sourceEventStore.ts`.- // Removal condition: replace with a database-backed maintenance operation ledger.- const reserved = await redisSourceEventStore.tryDedupe(- maintenanceOperationReserveKey(idempotencyKey),- MAINTENANCE_OPERATION_STATE_TTL_SECONDS,- );-- if (reserved) return { reserved: true };-- return {- existing:- parseStoredOperationResult(await redisSourceEventStore.readWindow(scopeKey)) ??- createSkippedOperationResult(),- reserved: false,- };-};--const completeMaintenanceOperation = async (input: MaintenanceToolReceiptInput) => {- await redisSourceEventStore.writeWindow(- maintenanceOperationScopeKey(input.idempotencyKey),- {- result: JSON.stringify({- ...(input.receiptId ? { receiptId: input.receiptId } : {}),- ...(input.resourceId ? { resourceId: input.resourceId } : {}),- status: input.status,- ...(input.summary ? { summary: input.summary } : {}),- } satisfies MaintenanceToolWriteResult),- },- MAINTENANCE_OPERATION_STATE_TTL_SECONDS,- );-};--const getToolReceiptStatus = (- status: MaintenanceToolReceiptInput['status'],-): 'applied' | 'failed' | 'proposed' | 'skipped' => {- if (status === 'applied') return 'applied';- if (status === 'failed') return 'failed';- if (status === 'proposed') return 'proposed';-- return 'skipped';-};--const writeMaintenanceToolReceipt = async ({- agentId,- input,- sourceId,- userId,-}: {- agentId: string;- input: MaintenanceToolReceiptInput;- sourceId: string;- userId: string;-}) => {- await persistAgentSignalReceipts([- {- agentId,- createdAt: Date.now(),- detail: input.summary ?? `Maintenance tool ${input.toolName} finished with ${input.status}.`,- id: input.idempotencyKey,- kind:- input.toolName === 'createSkillIfAbsent' || input.toolName === 'replaceSkillContentCAS'- ? 'skill'- : 'maintenance',- metadata: {- sourceType: NIGHTLY_REVIEW_SOURCE_TYPE,- },- sourceId,- sourceType: NIGHTLY_REVIEW_SOURCE_TYPE,- status: getToolReceiptStatus(input.status),- ...(input.resourceId &&- (input.toolName === 'createSkillIfAbsent' || input.toolName === 'replaceSkillContentCAS')- ? {- target: {- id: input.resourceId,- ...(input.summary ? { summary: input.summary } : {}),- title: input.summary ?? input.resourceId,- type: 'skill',- },- }- : {}),- title: input.summary ?? 'Maintenance tool outcome',- topicId: sourceId,- userId,- },- ]);-- return { receiptId: input.idempotencyKey };-};--const createSkillProposalAction = (input: CreateSkillIfAbsentInput): MaintenanceProposalAction => ({- actionType: 'create_skill',- baseSnapshot: {- absent: true,- skillName: input.name,- targetType: 'skill',- },- evidenceRefs: [],- idempotencyKey: input.idempotencyKey,- operation: {- domain: 'skill',- input: {- bodyMarkdown: input.bodyMarkdown,- description: input.description,- name: input.name,- title: input.title,- userId: input.userId,- },- operation: 'create',- },- rationale: input.summary ?? `Create managed skill ${input.name}.`,- risk: MaintenanceRisk.Low,- target: { skillName: input.name },-});--const createRefineProposalAction = (- input: ReplaceSkillContentCASInput,-): MaintenanceProposalAction => ({- actionType: 'refine_skill',- baseSnapshot: input.baseSnapshot,- evidenceRefs: [],- idempotencyKey: input.idempotencyKey,- operation: {- domain: 'skill',- input: {- bodyMarkdown: input.bodyMarkdown,- patch: input.summary,- skillDocumentId: input.skillDocumentId,- userId: input.userId,- },- operation: 'refine',- },- rationale: input.summary ?? `Refine managed skill ${input.skillDocumentId}.`,- risk: MaintenanceRisk.Low,- target: { skillDocumentId: input.skillDocumentId },-});--const getBriefMetadataWithProposal = (- brief: BriefItem,- proposal: MaintenanceProposalMetadata,-): BriefItem['metadata'] => {- const metadata = getRecord(brief.metadata);- const agentSignal = getRecord(metadata.agentSignal);- const nightlySelfReview = getRecord(agentSignal.nightlySelfReview);-- return {- ...metadata,- agentSignal: {- ...agentSignal,- nightlySelfReview: {- ...nightlySelfReview,- maintenanceProposal: proposal,- },- },- };-};--const getProposalToolCallPayload = (- toolName: string,- input:- | CreateMaintenanceProposalInput- | RefreshMaintenanceProposalInput- | SupersedeMaintenanceProposalInput,-) => ({- apiName: toolName,- arguments: JSON.stringify(input),- id: `${input.idempotencyKey}:tool-call`,- identifier: 'agent-signal-maintenance',- type: 'builtin' as const,-});--const collectPlanEvidenceRefs = (- plan: ReturnType<typeof projectMaintenanceToolRuntimeRun>['projectionPlan'],-) => {- 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 getRecord = (value: unknown): Record<string, unknown> =>- value && typeof value === 'object' && !Array.isArray(value)- ? (value as Record<string, unknown>)- : {};--const getString = (value: unknown) =>- typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined;--const getStringArray = (value: unknown) =>- Array.isArray(value) ? value.flatMap((item) => (getString(item) ? [getString(item)!] : [])) : [];--const getProposalActionSnapshotInput = (action: Record<string, unknown>) => {- const operation = getRecord(action.operation);- const operationInput = getRecord(operation.input);- const target = getRecord(action.target);-- return {- ...operationInput,- name: getString(operationInput.name) ?? getString(target.skillName),- skillDocumentId: getString(operationInput.skillDocumentId) ?? getString(target.skillDocumentId),- title: getString(operationInput.title) ?? getString(target.skillName),- };-};--const withCompleteProposalSnapshots = async ({- agentId,- input,- snapshotService,- userId,-}: {- agentId: string;- input: CreateMaintenanceProposalInput;- snapshotService: ReturnType<typeof createMaintenanceProposalSnapshotService>;- userId: string;-}): Promise<CreateMaintenanceProposalInput> => {- if (!input.actions || input.actions.length === 0) {- throw new Error('Maintenance proposal requires at least one action.');- }-- const actions = await Promise.all(- input.actions.map(async (rawAction) => {- const action = getRecord(rawAction);- const actionType = action.actionType;-- if (actionType === 'consolidate_skill') {- const operation = getRecord(action.operation);- const operationInput = getRecord(operation.input);- const canonicalSkillDocumentId = getString(operationInput.canonicalSkillDocumentId);- const sourceSkillIds = getStringArray(operationInput.sourceSkillIds);- const sourceSnapshots = await Promise.all(- sourceSkillIds.map((skillDocumentId) =>- snapshotService.captureActionSnapshot({- actionType: 'refine_skill',- agentId,- input: { skillDocumentId },- userId,- }),- ),- );-- return {- ...action,- ...(canonicalSkillDocumentId- ? {- baseSnapshot: await snapshotService.captureActionSnapshot({- actionType: 'refine_skill',- agentId,- input: { skillDocumentId: canonicalSkillDocumentId },- userId,- }),- }- : {}),- operation: {- ...operation,- input: {- ...operationInput,- sourceSnapshots,- },- },- };- }-- if (actionType !== 'create_skill' && actionType !== 'refine_skill') return rawAction;-- return {- ...action,- baseSnapshot: await snapshotService.captureActionSnapshot({- actionType,- agentId,- input: getProposalActionSnapshotInput(action),- userId,- }),- };- }),- );-- return { ...input, actions };-};--const isCompleteRefineToolSnapshot = (- snapshot: ReplaceSkillContentCASInput['baseSnapshot'],-): snapshot is NonNullable<ReplaceSkillContentCASInput['baseSnapshot']> & {- agentDocumentId: string;- contentHash: string;- documentId: string;-} =>- snapshot?.targetType === 'skill' &&- typeof snapshot.agentDocumentId === 'string' &&- snapshot.agentDocumentId.trim().length > 0 &&- typeof snapshot.contentHash === 'string' &&- snapshot.contentHash.trim().length > 0 &&- typeof snapshot.documentId === 'string' &&- snapshot.documentId.trim().length > 0 &&- snapshot.managed === true &&- snapshot.writable === true;--const withCompleteReplaceSkillSnapshot = async ({- agentId,- input,- snapshotService,- userId,-}: {- agentId: string;- input: ReplaceSkillContentCASInput;- snapshotService: ReturnType<typeof createMaintenanceProposalSnapshotService>;- userId: string;-}): Promise<ReplaceSkillContentCASInput> => {- if (isCompleteRefineToolSnapshot(input.baseSnapshot)) return input;-- const baseSnapshot = await snapshotService.captureActionSnapshot({- actionType: 'refine_skill',- agentId,- input: {- skillDocumentId: input.skillDocumentId,- },- userId,- });-- return {- ...input,- baseSnapshot,- // NOTICE:- // `replaceSkillContentCAS` can be called with either the managed skill bundle id or its- // SKILL.md index agent document id. Snapshot capture resolves both to the bundle id, and- // approve-time preflight compares the action target against that resolved bundle id.- // Without normalizing here, a valid index-targeted write is reported as target drift- // (`target_type_changed`) even though it points to the same managed skill.- // Removal condition: remove only if preflight natively accepts equivalent bundle/index ids.- skillDocumentId: baseSnapshot.agentDocumentId ?? input.skillDocumentId,- };-};--const createProposalProjectionFromToolInput = ({- input,- localDate,- sourceId,- toolName,- userId,-}: {- input: CreateMaintenanceProposalInput;- localDate: string;- sourceId: string;- toolName: 'createMaintenanceProposal';- userId: string;-}) =>- projectMaintenanceToolRuntimeRun({- content: input.summary,- includeProposalLifecycleActions: true,- localDate,- outcomes: [- {- receiptId: input.idempotencyKey,- status: 'proposed',- summary: input.summary,- toolName,- },- ],- reviewScope: MaintenanceReviewScope.Nightly,- sourceId,- toolCalls: [getProposalToolCallPayload(toolName, input)],- userId,- });--const findMaintenanceProposalBrief = async ({- agentId,- briefModel,- proposalId,- proposalKey,-}: {- agentId: string;- briefModel: ProposalBriefReader;- proposalId?: string;- proposalKey?: string;-}) => {- const rows = await briefModel.listUnresolvedByAgentAndTrigger({- agentId,- limit: NIGHTLY_PROPOSAL_ACTIVITY_LIMIT,- trigger: NIGHTLY_REVIEW_BRIEF_TRIGGER,- });-- return rows.find((row) => {- if (proposalId && row.id === proposalId) return true;-- const proposal = getMaintenanceProposalFromBriefMetadata(row.metadata);-- return proposalKey ? proposal?.proposalKey === proposalKey : false;- });-};--const updateMaintenanceProposalBrief = async ({- agentId,- briefModel,- proposalId,- proposalKey,- updateProposal,-}: {- agentId: string;- briefModel: BriefModel;- proposalId?: string;- proposalKey?: string;- updateProposal: (proposal: MaintenanceProposalMetadata) => MaintenanceProposalMetadata;-}) => {- const brief = await findMaintenanceProposalBrief({- agentId,- briefModel,- proposalId,- proposalKey,- });-- if (!brief) throw new Error('Maintenance proposal not found');-- const existingProposal = getMaintenanceProposalFromBriefMetadata(brief.metadata);- if (!existingProposal) throw new Error('Maintenance proposal metadata not found');-- const updatedProposal = updateProposal(existingProposal);- const updatedBrief = await briefModel.updateMetadata(- brief.id,- getBriefMetadataWithProposal(brief, updatedProposal),- );-- return {- resourceId: updatedBrief?.id ?? brief.id,- summary: `Updated maintenance proposal ${updatedProposal.proposalKey}.`,- };-};--const createServerMaintenanceToolset = ({- agentId,- briefModel,- context,- db,- localDate,- proposalBriefWriter,- skillDocumentService,- sourceId,- userId,-}: {- agentId: string;- briefModel: BriefModel;- context: NightlyReviewContext;- db: LobeChatDatabase;- localDate: string;- proposalBriefWriter: ReturnType<typeof createServerMaintenanceBriefWriter>;- skillDocumentService: SkillManagementDocumentService;- sourceId: string;- userId: string;-}) => {- const proposalPreflight = createMaintenanceProposalPreflightService({- isSkillNameAvailable: async ({ agentId: targetAgentId, name }) => {- const skills = await skillDocumentService.listSkills({ agentId: targetAgentId ?? agentId });-- return !skills.some((skill) => skill.name === name);- },- readSkillTargetSnapshot: (skillDocumentId) =>- skillDocumentService.readSkillTargetSnapshot({- agentDocumentId: skillDocumentId,- agentId,- }),- });- const proposalSnapshot = createMaintenanceProposalSnapshotService({- isSkillNameAvailable: async ({ agentId: targetAgentId, name }) => {- const skills = await skillDocumentService.listSkills({ agentId: targetAgentId ?? agentId });-- return !skills.some((skill) => skill.name === name);- },- readSkillTargetSnapshot: (skillDocumentId) =>- skillDocumentService.readSkillTargetSnapshot({- agentDocumentId: skillDocumentId,- agentId,- }),- });-- return createMaintenanceTools({- closeProposal: async (input: CloseMaintenanceProposalInput) =>- updateMaintenanceProposalBrief({- agentId,- briefModel,- proposalId: input.proposalId,- proposalKey: input.proposalKey,- updateProposal: (proposal) => ({- ...proposal,- status: 'dismissed',- updatedAt: new Date().toISOString(),- }),- }),- completeOperation: completeMaintenanceOperation,- completeReplaceSkillInput: (input) =>- withCompleteReplaceSkillSnapshot({- agentId,- input,- snapshotService: proposalSnapshot,- userId,- }),- createProposal: async (input) => {- const projectionInput = await withCompleteProposalSnapshots({- agentId,- input,- snapshotService: proposalSnapshot,- userId,- });- const projection = createProposalProjectionFromToolInput({- input: projectionInput,- localDate,- sourceId,- toolName: 'createMaintenanceProposal',- userId,- });- const brief = createBriefMaintenanceService().projectNightlyReviewBrief({- agentId,- evidenceRefs: collectPlanEvidenceRefs(projection.projectionPlan),- ideas: projection.ideas,- localDate,- plan: projection.projectionPlan,- result: projection.execution,- reviewWindowEnd: context.reviewWindowEnd,- reviewWindowStart: context.reviewWindowStart,- timezone: 'UTC',- userId,- });-- if (!brief) throw new Error('Maintenance proposal projection produced no brief');-- const result = await proposalBriefWriter.writeDailyBrief(brief);-- return {- proposalId: result?.id,- resourceId: result?.id,- summary: input.summary ?? 'Created maintenance proposal.',- };- },- createSkill: async (input) => {- const preflight = await proposalPreflight.checkAction(createSkillProposalAction(input));- if (!preflight.allowed) {- throw new Error(`Skill creation preflight failed: ${preflight.reason}`);- }-- const result = await skillDocumentService.createSkill({- agentId,- bodyMarkdown: input.bodyMarkdown,- description: input.description ?? 'Agent Signal managed skill.',- name: input.name,- title: input.title ?? input.name,- });-- return {- resourceId: result.bundle.agentDocumentId,- summary: `Created managed skill ${result.name}.`,- };- },- writeMemory: async (input: WriteMemoryInput) => {- // TODO: Harden the real writeMemory E2E path. Local QStash verification showed this- // tool reaches the memory action agent, but the agent does not always converge to an- // applied receipt/brief. Keep this marker until the memory auto-apply case has a- // deterministic eval plus a passing end-to-end run.- const memoryService = createMemoryMaintenanceService({- writeMemory: async ({ content, evidenceRefs, idempotencyKey }) => {- const result = await runMemoryActionAgent(- {- agentId,- message: content,- reason: `Agent Signal maintenance memory candidate from ${evidenceRefs.length} evidence refs.`,- },- {- db,- 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,- };- },- });- const result = await memoryService.writeMemory({- evidenceRefs: input.evidenceRefs,- idempotencyKey: input.idempotencyKey,- input: {- content: input.content,- userId: input.userId,- },- });-- return {- resourceId: result.memoryId,- summary: result.summary,- };- },- getEvidenceDigest: async ({ evidenceIds }) => {- const selectedEvidenceIds = new Set(evidenceIds ?? []);- const includeAll = selectedEvidenceIds.size === 0;-- return {- documentActivity: context.documentActivity,- proposalActivity: context.proposalActivity,- receiptActivity: context.receiptActivity,- toolActivity: context.toolActivity,- topics: includeAll- ? context.topics- : context.topics.filter((topic) =>- topic.evidenceRefs.some((ref) => selectedEvidenceIds.has(ref.id)),- ),- };- },- getManagedSkill: ({ agentId: targetAgentId, skillDocumentId }) =>- skillDocumentService.getSkill({- agentDocumentId: skillDocumentId,- agentId: targetAgentId,- includeContent: true,- }),- listMaintenanceProposals: ({ agentId: targetAgentId }) =>- listServerProposalActivity({- agentId: targetAgentId,- briefModel,- userId,- }).then((digest) => [digest]),- listManagedSkills: ({ agentId: targetAgentId }) =>- skillDocumentService.listSkills({ agentId: targetAgentId }),- preflight: async (input) => {- if ('skillDocumentId' in input) {- const result = await proposalPreflight.checkAction(createRefineProposalAction(input));-- return result.allowed ? { allowed: true } : { allowed: false, reason: result.reason };- }-- return { allowed: true };- },- readProposal: async ({ proposalId, proposalKey }) => {- const digest = await listServerProposalActivity({- agentId,- briefModel,- userId,- });-- return digest.active.find(- (proposal) =>- (proposalId && proposal.proposalId === proposalId) ||- (proposalKey && proposal.proposalKey === proposalKey),- );- },- refreshProposal: async (input: RefreshMaintenanceProposalInput) =>- updateMaintenanceProposalBrief({- agentId,- briefModel,- proposalId: input.proposalId,- proposalKey: input.proposalKey,- updateProposal: (proposal) =>- refreshMaintenanceProposal({- existing: proposal,- incoming: proposal,- now: new Date().toISOString(),- }),- }),- replaceSkill: async (input) => {- const result = await skillDocumentService.replaceSkillIndex({- agentDocumentId: input.skillDocumentId,- agentId,- bodyMarkdown: input.bodyMarkdown,- description: input.description,- });-- if (!result) throw new Error('Skill target not found');-- return {- resourceId: result.bundle.agentDocumentId,- summary: `Refined managed skill ${result.name}.`,- };- },- reserveOperation: reserveMaintenanceOperation,- supersedeProposal: async (input: SupersedeMaintenanceProposalInput) =>- updateMaintenanceProposalBrief({- agentId,- briefModel,- proposalId: input.proposalId,- proposalKey: input.proposalKey,- updateProposal: (proposal) =>- supersedeMaintenanceProposal({- existing: proposal,- now: new Date().toISOString(),- supersededBy: input.supersededBy,- }),- }),- writeReceipt: (input) => writeMaintenanceToolReceipt({ agentId, input, sourceId, userId }),- });-};--/**- * 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 nightlyReviewModel = new AgentSignalNightlyReviewModel(db);- const reviewContextModel = new AgentSignalReviewContextModel(db, userId);- const briefModel = new BriefModel(db, userId);- const skillDocumentService = new SkillManagementDocumentService(db, userId);- const collector = createNightlyReviewService({- listDocumentActivity: async ({ agentId: targetAgentId, reviewWindowEnd, reviewWindowStart }) =>- tracer.startActiveSpan(- 'agent_signal.nightly_review.collector.list_document_activity',- {- attributes: {- 'agent.signal.agent_id': targetAgentId,- 'agent.signal.user_id': userId,- },- },- async (span) => {- try {- const rows = await reviewContextModel.listDocumentActivity({- agentId: targetAgentId,- windowEnd: new Date(reviewWindowEnd),- windowStart: new Date(reviewWindowStart),- });- const digest = mapNightlyDocumentActivityRows(rows);-- span.setAttribute('agent.signal.nightly.document_activity_row_count', rows.length);- span.setAttribute(- 'agent.signal.nightly.document_skill_event_count',- digest.skillBucket.length,- );- span.setStatus({ code: SpanStatusCode.OK });-- return digest;- } catch (error) {- span.setStatus({- code: SpanStatusCode.ERROR,- message:- error instanceof Error- ? error.message- : 'AgentSignal nightly document activity read failed',- });- span.recordException(error as Error);-- throw error;- } finally {- span.end();- }- },- ),- listFeedbackActivity: async ({ agentId: targetAgentId }) =>- tracer.startActiveSpan(- 'agent_signal.nightly_review.collector.list_feedback_activity',- {- attributes: {- 'agent.signal.agent_id': targetAgentId,- 'agent.signal.user_id': userId,- },- },- async (span): Promise<FeedbackActivityDigest> => {- try {- const digest: FeedbackActivityDigest = {- neutralCount: 0,- notSatisfied: [],- satisfied: [],- };-- span.setAttribute('agent.signal.nightly.feedback_satisfied_count', 0);- span.setAttribute('agent.signal.nightly.feedback_not_satisfied_count', 0);- span.setStatus({ code: SpanStatusCode.OK });-- return digest;- } finally {- span.end();- }- },- ),- 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,- }));- },- listProposalActivity: ({ agentId: targetAgentId }) =>- listServerProposalActivity({- agentId: targetAgentId,- briefModel,- userId,- }),- 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(),- }));- },- listReceiptActivity: async ({ agentId: targetAgentId }) =>- tracer.startActiveSpan(- 'agent_signal.nightly_review.collector.list_receipt_activity',- {- attributes: {- 'agent.signal.agent_id': targetAgentId,- 'agent.signal.user_id': userId,- },- },- async (span): Promise<ReceiptActivityDigest> => {- try {- const digest: ReceiptActivityDigest = {- appliedCount: 0,- duplicateGroups: [],- failedCount: 0,- pendingProposalCount: 0,- recentReceipts: [],- reviewCount: 0,- };-- span.setAttribute('agent.signal.nightly.receipt_pending_proposal_count', 0);- span.setAttribute('agent.signal.nightly.receipt_recent_count', 0);- span.setStatus({ code: SpanStatusCode.OK });-- return digest;- } finally {- span.end();- }- },- ),- listToolActivity: async ({ agentId: targetAgentId, reviewWindowEnd, reviewWindowStart }) =>- tracer.startActiveSpan(- 'agent_signal.nightly_review.collector.list_tool_activity',- {- attributes: {- 'agent.signal.agent_id': targetAgentId,- 'agent.signal.user_id': userId,- },- },- async (span) => {- try {- const rows = await reviewContextModel.listToolActivity({- agentId: targetAgentId,- windowEnd: new Date(reviewWindowEnd),- windowStart: new Date(reviewWindowStart),- });- const digest = rows.map<ToolActivityDigest>((row) => ({- apiName: row.apiName,- failedCount: row.failedCount,- firstUsedAt: row.firstUsedAt?.toISOString(),- identifier: row.identifier,- lastUsedAt: row.lastUsedAt?.toISOString(),- messageIds: row.messageIds.slice(0, 10),- sampleArgs: row.sampleArgs.slice(0, 3),- sampleErrors: row.sampleErrors.slice(0, 3),- topicIds: row.topicIds.slice(0, 10),- totalCount: row.totalCount,- }));-- span.setAttribute('agent.signal.nightly.tool_activity_count', digest.length);- span.setStatus({ code: SpanStatusCode.OK });-- return digest;- } catch (error) {- span.setStatus({- code: SpanStatusCode.ERROR,- message:- error instanceof Error- ? error.message- : 'AgentSignal nightly tool activity read failed',- });- span.recordException(error as Error);-- throw error;- } finally {- span.end();- }- },- ),- 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) => ({- correctionCount: row.correctionCount,- correctionIds: row.correctionIds,- evidenceRefs: row.topicId ? [{ id: row.topicId, type: 'topic' }] : [],- failedMessages: row.failedMessages,- failedToolCount: row.failedToolCount,- failedToolCalls: row.failedToolCalls,- failureCount: row.failureCount,- lastActivityAt: row.lastActivityAt.toISOString(),- messageCount: row.messageCount,- summary: row.summary,- title: row.title ?? undefined,- topicId: row.topicId ?? undefined,- }));- },- });- const briefWriter = createServerMaintenanceBriefWriter(db, 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),- runMaintenanceReviewAgent: async ({ context, localDate, sourceId, userId: runnerUserId }) => {- const modelRuntime = await initModelRuntimeFromDB(- db,- runnerUserId,- DEFAULT_MINI_SYSTEM_AGENT_ITEM.provider,- );- const maintenanceTools = createServerMaintenanceToolset({- agentId: context.agentId,- briefModel,- context,- db,- localDate: localDate ?? context.reviewWindowEnd.slice(0, 10),- proposalBriefWriter: briefWriter,- skillDocumentService,- sourceId,- userId: runnerUserId,- });- const maintenanceAgentRunner = createMaintenanceAgentRunner({- maxSteps: 10,- run: async ({ context, localDate, maxSteps, reviewScope, sourceId, tools, userId }) => {- const runtimeResult = await runMaintenanceToolFirstRuntime({- agentId: context.agentId,- context,- maxSteps,- model: DEFAULT_MINI_SYSTEM_AGENT_ITEM.model,- modelRuntime,- sourceId,- tools,- userId,- });- const projected = projectMaintenanceToolRuntimeRun({- content: runtimeResult.content,- localDate,- outcomes: runtimeResult.writeOutcomes.map((outcome) => ({- ...outcome.result,- toolName: outcome.toolName,- })),- reviewScope,- sourceId,- toolCalls: runtimeResult.toolCalls,- userId,- });-- return {- ...projected,- stepCount: runtimeResult.stepCount,- };- },- tools: maintenanceTools,- });-- return maintenanceAgentRunner.run({- context,- localDate,- sourceId,- userId: runnerUserId,- });- },- writeDailyBrief: (brief) => briefWriter.writeDailyBrief(brief),- writeReceipts: (receipts) => persistAgentSignalReceipts(receipts),- };-};diff --git a/src/server/services/agentSignal/services/maintenance/skill.ts b/src/server/services/agentSignal/services/maintenance/skill.tsdeleted file mode 100644index 7c377d931fa..00000000000--- a/src/server/services/agentSignal/services/maintenance/skill.ts+++ /dev/null@@ -1,182 +0,0 @@-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 {- /** Full replacement Markdown body without YAML frontmatter. */- bodyMarkdown?: string;- /** Human-readable proposal patch text, not executable replacement content. */- 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';- };- /** Full replacement Markdown body for the canonical skill. */- bodyMarkdown?: string;- /** Canonical writable managed skill agent document id. */- canonicalSkillDocumentId: string;- /** Optional description to persist with the canonical skill index. */- description?: string;- /** Source managed skill ids used to build the canonical skill. */- sourceSkillIds: string[];- /** Frozen source snapshots captured when the consolidation was proposed. */- sourceSnapshots?: SkillMaintenanceTargetSnapshot[];-}--/** Frozen managed-skill target state used by approve-time consolidation preflight. */-export interface SkillMaintenanceTargetSnapshot {- /** Managed skill bundle agent document id. */- agentDocumentId?: string;- /** Content hash observed when the proposal was created. */- contentHash?: string;- /** Canonical document id observed when the proposal was created. */- documentId?: string;- /** Whether the target was managed by Agent Signal. */- managed?: boolean;- /** Target domain captured by the proposal snapshot. */- targetType?: 'skill';- /** Whether the target was writable at proposal time. */- writable?: boolean;-}--/** 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');- }-};--const assertCompleteRefineBody = (input: RefineMaintenanceSkillInput) => {- if (!input.bodyMarkdown?.trim()) {- throw new Error('Skill refinement requires a complete replacement bodyMarkdown');- }-};--/**- * 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);- assertCompleteRefineBody(request.input);-- if (!adapters.refineSkill) {- throw new Error('Skill refine adapter is required');- }-- return adapters.refineSkill(request);- },-});diff --git a/src/server/services/agentSignal/services/maintenance/tools.ts b/src/server/services/agentSignal/services/maintenance/tools.tsdeleted file mode 100644index d1e37eacec4..00000000000--- a/src/server/services/agentSignal/services/maintenance/tools.ts+++ /dev/null@@ -1,712 +0,0 @@-import { SpanStatusCode } from '@lobechat/observability-otel/api';-import { tracer } from '@lobechat/observability-otel/modules/agent-signal';--import type { MaintenanceProposalBaseSnapshot } from './proposal';-import type { EvidenceRef } from './types';--/** Terminal status emitted by safe maintenance write tools. */-export type MaintenanceToolWriteStatus =- | 'applied'- | 'deduped'- | 'failed'- | 'proposed'- | 'skipped_stale'- | 'skipped_unsupported';--/** Public result returned by safe maintenance write tools. */-export interface MaintenanceToolWriteResult {- /** Receipt written for the terminal tool outcome. */- receiptId?: string;- /** Resource touched or considered by the maintenance tool. */- resourceId?: string;- /** Terminal write safety status. */- status: MaintenanceToolWriteStatus;- /** Bounded human-readable tool result. */- summary?: string;-}--/** Successful preflight result for a maintenance write targeting an existing resource. */-export interface MaintenanceToolPreflightAllowed {- /** Whether the target is still safe to mutate. */- allowed: true;-}--/** Failed preflight result for a maintenance write targeting an existing resource. */-export interface MaintenanceToolPreflightDenied {- /** Whether the target is still safe to mutate. */- allowed: false;- /** Short stale/conflict reason to store in the receipt. */- reason: string;-}--/** Preflight result emitted before existing-resource writes. */-export type MaintenanceToolPreflightResult =- | MaintenanceToolPreflightAllowed- | MaintenanceToolPreflightDenied;--/** Shared write envelope accepted by all maintenance tools. */-export interface MaintenanceToolWriteInput {- /** Stable operation key used to dedupe repeated tool calls. */- idempotencyKey: string;- /** Stable proposal key used for proposal-scoped tracing and receipts. */- proposalKey?: string;- /** Optional caller-provided summary, bounded before persistence. */- summary?: string;- /** User that owns the maintenance operation. */- userId: string;-}--/** Input for replacing one managed skill using compare-and-swap safety checks. */-export interface ReplaceSkillContentCASInput extends MaintenanceToolWriteInput {- /** Complete target snapshot captured when the proposal was created. */- baseSnapshot?: MaintenanceProposalBaseSnapshot;- /** Replacement skill body. */- bodyMarkdown: string;- /** Optional replacement description. */- description?: string;- /** Existing managed skill document id. */- skillDocumentId: string;-}--/** Input for creating one skill when no existing skill has been selected. */-export interface CreateSkillIfAbsentInput extends MaintenanceToolWriteInput {- /** Skill body or authoring payload. */- bodyMarkdown: string;- /** Optional skill description. */- description?: string;- /** Stable skill name. */- name: string;- /** Optional skill title. */- title?: string;-}--/** Input for writing one durable memory candidate from explicit nightly evidence. */-export interface WriteMemoryInput extends MaintenanceToolWriteInput {- /** Candidate durable memory content. */- content: string;- /** Evidence supporting this memory write. */- evidenceRefs: EvidenceRef[];-}--/** Input for listing managed skills in one agent scope. */-export interface ListManagedSkillsInput {- /** Agent whose managed skills are visible to the tool call. */- agentId: string;- /** User that owns the read operation. */- userId: string;-}--/** Input for reading one managed skill in one agent scope. */-export interface GetManagedSkillInput extends ListManagedSkillsInput {- /** Existing managed skill document id. */- skillDocumentId: string;-}--/** Input for listing maintenance proposals in one agent scope. */-export interface ListMaintenanceProposalsInput {- /** Agent whose proposals are visible to the tool call. */- agentId: string;- /** User that owns the read operation. */- userId: string;-}--/** Input for reading an evidence digest in one agent scope. */-export interface GetEvidenceDigestInput {- /** Agent whose evidence is visible to the tool call. */- agentId: string;- /** Optional bounded evidence ids selected by the caller. */- evidenceIds?: string[];- /** Optional inclusive review window end timestamp. */- reviewWindowEnd?: string;- /** Optional inclusive review window start timestamp. */- reviewWindowStart?: string;- /** User that owns the read operation. */- userId: string;-}--/** Input for creating one user-visible maintenance proposal. */-export interface CreateMaintenanceProposalInput extends MaintenanceToolWriteInput {- /** Proposal action payload retained by the injected proposal adapter. */- actions?: unknown[];- /** Proposal metadata retained by the injected proposal adapter. */- metadata?: Record<string, unknown>;-}--/** Input for refreshing an existing maintenance proposal. */-export interface RefreshMaintenanceProposalInput extends MaintenanceToolWriteInput {- /** Existing proposal id to refresh. */- proposalId: string;-}--/** Input for superseding an existing maintenance proposal. */-export interface SupersedeMaintenanceProposalInput extends MaintenanceToolWriteInput {- /** Existing proposal id to supersede. */- proposalId: string;- /** Replacement proposal key or id. */- supersededBy: string;-}--/** Input for closing an existing maintenance proposal. */-export interface CloseMaintenanceProposalInput extends MaintenanceToolWriteInput {- /** Existing proposal id to close. */- proposalId: string;- /** Lifecycle reason recorded by the injected adapter. */- reason?: string;-}--/** Result returned by mutation adapters before receipt persistence. */-export interface MaintenanceToolMutationResult {- /** Resource created or updated by the adapter. */- resourceId?: string;- /** Short adapter summary. */- summary?: string;-}--/** Receipt write request emitted after every terminal write outcome. */-export interface MaintenanceToolReceiptInput extends MaintenanceToolWriteResult {- /** Stable operation key used to dedupe repeated tool calls. */- idempotencyKey: string;- /** Stable proposal key used for proposal-scoped tracing and receipts. */- proposalKey?: string;- /** Tool that produced this receipt. */- toolName: string;- /** User that owns the maintenance operation. */- userId: string;-}--/** Receipt adapter result. */-export interface MaintenanceToolReceiptResult {- /** Persisted receipt id. */- receiptId?: string;-}--/** Lifecycle request emitted after a reserved maintenance operation reaches a terminal state. */-export interface MaintenanceToolOperationLifecycleInput extends MaintenanceToolReceiptInput {- /** Persisted terminal receipt id, when the receipt adapter returns one. */- receiptId?: string;-}--/** Lifecycle request emitted when a reserved operation cannot write its terminal receipt. */-export interface MaintenanceToolOperationFailureInput extends MaintenanceToolReceiptInput {- /** Error thrown while writing the terminal receipt. */- error: unknown;-}--/** Atomic reservation result for a newly claimed maintenance operation. */-export interface MaintenanceToolReservedOperation {- /** True when the adapter atomically claimed this idempotency key for mutation. */- reserved: true;-}--/** Atomic reservation result for a previously completed maintenance operation. */-export interface MaintenanceToolExistingOperation {- /** Prior terminal operation result returned without running mutation. */- existing: MaintenanceToolWriteResult;- /** False when the adapter found an existing terminal operation for this key. */- reserved: false;-}--/** Atomic idempotency reservation emitted before any write preflight or mutation. */-export type MaintenanceToolOperationReservation =- | MaintenanceToolExistingOperation- | MaintenanceToolReservedOperation;--/** Adapters used by safe maintenance read/write tools. */-export interface MaintenanceToolsAdapters {- /** Closes an existing maintenance proposal. */- closeProposal?: (input: CloseMaintenanceProposalInput) => Promise<MaintenanceToolMutationResult>;- /**- * Marks a reserved idempotency operation as terminal after its receipt is persisted.- *- * Adapters that store in-progress reservations should use this hook to make the terminal- * receipt/result the dedupe source of truth. Without it, repeated calls may either rerun- * mutation or leave reservations stuck in an in-progress state.- */- completeOperation?: (input: MaintenanceToolOperationLifecycleInput) => Promise<void>;- /** Completes server-owned CAS metadata before validating an existing skill replacement. */- completeReplaceSkillInput?: (- input: ReplaceSkillContentCASInput,- ) => Promise<ReplaceSkillContentCASInput>;- /** Creates one user-visible maintenance proposal. */- createProposal?: (- input: CreateMaintenanceProposalInput,- ) => Promise<MaintenanceToolMutationResult & { proposalId?: string }>;- /** Creates one managed skill. */- createSkill?: (input: CreateSkillIfAbsentInput) => Promise<MaintenanceToolMutationResult>;- /** Reads a bounded evidence digest for maintenance planning. */- getEvidenceDigest?: (input: GetEvidenceDigestInput) => Promise<unknown | undefined>;- /** Reads one managed skill in the requested agent scope. */- getManagedSkill?: (input: GetManagedSkillInput) => Promise<unknown | undefined>;- /** Lists maintenance proposals in the requested agent scope. */- listMaintenanceProposals?: (input: ListMaintenanceProposalsInput) => Promise<unknown[]>;- /** Lists managed skills in the requested agent scope. */- listManagedSkills?: (input: ListManagedSkillsInput) => Promise<unknown[]>;- /**- * Marks or releases a reserved operation when its terminal receipt cannot be persisted.- *- * Adapters should make this hook prevent duplicate mutation while avoiding permanently stuck- * reservations. A common implementation records the failure against the idempotency key and- * releases retryable reservation state only when the mutation contract is safe to retry.- */- markOperationFailed?: (input: MaintenanceToolOperationFailureInput) => Promise<void>;- /** Checks freshness and writability before mutating existing resources. */- preflight?: (- input:- | CloseMaintenanceProposalInput- | RefreshMaintenanceProposalInput- | ReplaceSkillContentCASInput- | SupersedeMaintenanceProposalInput,- ) => Promise<MaintenanceToolPreflightResult>;- /** Reads an existing maintenance proposal. */- readProposal?: (input: {- proposalId?: string;- proposalKey?: string;- userId: string;- }) => Promise<unknown>;- /** Refreshes an existing maintenance proposal. */- refreshProposal?: (- input: RefreshMaintenanceProposalInput,- ) => Promise<MaintenanceToolMutationResult>;- /** Replaces existing managed skill content after CAS preflight. */- replaceSkill?: (input: ReplaceSkillContentCASInput) => Promise<MaintenanceToolMutationResult>;- /** Atomically reserves an idempotency key before any preflight or mutation runs. */- reserveOperation: (idempotencyKey: string) => Promise<MaintenanceToolOperationReservation>;- /** Supersedes an existing maintenance proposal. */- supersedeProposal?: (- input: SupersedeMaintenanceProposalInput,- ) => Promise<MaintenanceToolMutationResult>;- /** Writes one durable memory candidate. */- writeMemory?: (input: WriteMemoryInput) => Promise<MaintenanceToolMutationResult>;- /** Writes the audit receipt for a terminal maintenance tool status. */- writeReceipt: (input: MaintenanceToolReceiptInput) => Promise<MaintenanceToolReceiptResult>;-}--const MAX_SUMMARY_LENGTH = 240;--/**- * Normalizes maintenance tool summaries.- *- * Before:- * - `" A very long summary ... "`- *- * After:- * - `"A very long summary ..."`- */-const boundSummary = (summary: string | undefined) => {- if (!summary) return undefined;-- const normalized = summary.trim().replaceAll(/\s+/g, ' ');-- return normalized.length > MAX_SUMMARY_LENGTH- ? `${normalized.slice(0, MAX_SUMMARY_LENGTH - 3)}...`- : normalized;-};--const errorSummary = (error: unknown) =>- boundSummary(error instanceof Error ? error.message : String(error));--const getErrorMessage = (error: unknown) =>- error instanceof Error ? error.message : String(error);--const hasNonBlankString = (value: unknown): value is string =>- typeof value === 'string' && value.trim().length > 0;--const isCompleteRefineBaseSnapshot = (- snapshot: unknown,-): snapshot is MaintenanceProposalBaseSnapshot & {- agentDocumentId: string;- contentHash: string;- documentId: string;-} => {- if (!snapshot || typeof snapshot !== 'object') return false;-- const record = snapshot as Record<string, unknown>;-- return (- record.targetType === 'skill' &&- hasNonBlankString(record.agentDocumentId) &&- hasNonBlankString(record.documentId) &&- hasNonBlankString(record.contentHash) &&- record.managed === true &&- record.writable === true- );-};--const getResultWithReceipt = async (- adapters: MaintenanceToolsAdapters,- input: MaintenanceToolWriteInput,- toolName: string,- result: MaintenanceToolWriteResult,-): Promise<MaintenanceToolWriteResult> => {- const boundedResult = { ...result, summary: boundSummary(result.summary) };- const receipt = await adapters.writeReceipt({- ...boundedResult,- idempotencyKey: input.idempotencyKey,- proposalKey: input.proposalKey,- toolName,- userId: input.userId,- });-- return { ...boundedResult, receiptId: receipt.receiptId ?? boundedResult.receiptId };-};--const withWriteSpan = async <TInput extends MaintenanceToolWriteInput>(- toolName: string,- input: TInput,- operation: (- recordConvertedException: (error: unknown) => void,- ) => Promise<MaintenanceToolWriteResult>,-) => {- return tracer.startActiveSpan(- 'agent_signal.maintenance_tool.write',- {- attributes: {- 'agent.signal.maintenance_tool.name': toolName,- ...(input.proposalKey ? { 'agent.signal.proposal.key': input.proposalKey } : {}),- },- },- async (span) => {- try {- const result = await operation((error) => span.recordException(error as Error));-- span.setAttribute('agent.signal.maintenance_tool.write_status', result.status);- span.setStatus({- code: result.status === 'failed' ? SpanStatusCode.ERROR : SpanStatusCode.OK,- });-- return result;- } catch (error) {- span.recordException(error as Error);- span.setStatus({ code: SpanStatusCode.ERROR, message: getErrorMessage(error) });-- throw error;- } finally {- span.end();- }- },- );-};--const withReadSpan = async <TResult>(- toolName: string,- proposalKey: string | undefined,- operation: () => Promise<TResult>,-) => {- return tracer.startActiveSpan(- 'agent_signal.maintenance_tool.read',- {- attributes: {- 'agent.signal.maintenance_tool.name': toolName,- ...(proposalKey ? { 'agent.signal.proposal.key': proposalKey } : {}),- },- },- async (span) => {- try {- const result = await operation();-- span.setStatus({ code: SpanStatusCode.OK });-- return result;- } catch (error) {- span.recordException(error as Error);- span.setStatus({ code: SpanStatusCode.ERROR, message: getErrorMessage(error) });-- throw error;- } finally {- span.end();- }- },- );-};--const runWriteTool = async <TInput extends MaintenanceToolWriteInput>({- adapters,- input,- mutate,- preflight,- preflightRequired,- resourceId,- successStatus,- toolName,- unsupportedSummary,- validate,-}: {- adapters: MaintenanceToolsAdapters;- input: TInput;- mutate?: () => Promise<MaintenanceToolMutationResult>;- preflight?: () => Promise<MaintenanceToolPreflightResult>;- preflightRequired?: boolean;- resourceId?: string;- successStatus: Exclude<- MaintenanceToolWriteStatus,- 'deduped' | 'failed' | 'skipped_stale' | 'skipped_unsupported'- >;- toolName: string;- unsupportedSummary: string;- validate?: () => MaintenanceToolWriteResult | undefined;-}) => {- return withWriteSpan(toolName, input, async (recordConvertedException) => {- let operationReserved = false;- const result = await (async (): Promise<MaintenanceToolWriteResult> => {- try {- const reservation = await adapters.reserveOperation(input.idempotencyKey);-- if (!reservation.reserved) {- return {- resourceId: reservation.existing.resourceId,- status: 'deduped',- summary: reservation.existing.summary,- };- }-- operationReserved = true;-- const validationResult = validate?.();- if (validationResult) return validationResult;-- if (!mutate) {- return {- resourceId,- status: 'skipped_unsupported',- summary: unsupportedSummary,- };- }-- if (preflightRequired && !preflight) {- return {- resourceId,- status: 'skipped_unsupported',- summary: 'Maintenance preflight is not supported.',- };- }-- if (preflight) {- const preflightResult = await preflight();-- if (!preflightResult.allowed) {- return {- resourceId,- status: 'skipped_stale',- summary: preflightResult.reason || input.summary,- };- }- }-- const mutationResult = await mutate();-- return {- resourceId: mutationResult.resourceId ?? resourceId,- status: successStatus,- summary: mutationResult.summary ?? input.summary,- };- } catch (error) {- recordConvertedException(error);-- return {- resourceId,- status: 'failed',- summary: errorSummary(error),- };- }- })();-- try {- const resultWithReceipt = await getResultWithReceipt(adapters, input, toolName, result);-- if (operationReserved) {- await adapters.completeOperation?.({- ...resultWithReceipt,- idempotencyKey: input.idempotencyKey,- proposalKey: input.proposalKey,- toolName,- userId: input.userId,- });- }-- return resultWithReceipt;- } catch (error) {- if (operationReserved) {- await adapters.markOperationFailed?.({- ...result,- error,- idempotencyKey: input.idempotencyKey,- proposalKey: input.proposalKey,- toolName,- userId: input.userId,- });- }-- throw error;- }- });-};--/**- * Creates safe read/write maintenance tools with injected domain adapters.- *- * Use when:- * - Agent Signal needs callable maintenance tools before runner wiring- * - Tests need to verify write safety contracts without database services- *- * Expects:- * - `idempotencyKey` is stable per intended write- * - Existing-resource writes inject `preflight` before mutation- *- * Returns:- * - Tool functions that dedupe, preflight, mutate, receipt, and trace consistently- */-export const createMaintenanceTools = (adapters: MaintenanceToolsAdapters) => ({- closeMaintenanceProposal: async (input: CloseMaintenanceProposalInput) =>- runWriteTool({- adapters,- input,- mutate: adapters.closeProposal ? () => adapters.closeProposal!(input) : undefined,- preflight: adapters.preflight ? () => adapters.preflight!(input) : undefined,- preflightRequired: true,- resourceId: input.proposalId,- successStatus: 'applied',- toolName: 'closeMaintenanceProposal',- unsupportedSummary: 'Maintenance proposal close is not supported.',- }),- createMaintenanceProposal: async (input: CreateMaintenanceProposalInput) =>- runWriteTool({- adapters,- input,- mutate: adapters.createProposal- ? async () => {- const result = await adapters.createProposal!(input);-- return {- resourceId: result.resourceId ?? result.proposalId,- summary: result.summary,- };- }- : undefined,- successStatus: 'proposed',- toolName: 'createMaintenanceProposal',- unsupportedSummary: 'Maintenance proposal creation is not supported.',- }),- createSkillIfAbsent: async (input: CreateSkillIfAbsentInput) =>- runWriteTool({- adapters,- input,- mutate: adapters.createSkill ? () => adapters.createSkill!(input) : undefined,- successStatus: 'applied',- toolName: 'createSkillIfAbsent',- unsupportedSummary: 'Skill creation is not supported.',- validate: () => {- if (hasNonBlankString(input.name) && hasNonBlankString(input.bodyMarkdown)) {- return undefined;- }-- return {- status: 'skipped_unsupported',- summary: 'Skill creation requires a non-empty name and body.',- };- },- }),- writeMemory: async (input: WriteMemoryInput) =>- runWriteTool({- adapters,- input,- mutate: adapters.writeMemory ? () => adapters.writeMemory!(input) : undefined,- successStatus: 'applied',- toolName: 'writeMemory',- unsupportedSummary: 'Memory writing is not supported.',- }),- getEvidenceDigest: async (input: GetEvidenceDigestInput) =>- withReadSpan('getEvidenceDigest', undefined, async () => {- if (!adapters.getEvidenceDigest) return undefined;-- return adapters.getEvidenceDigest(input);- }),- getManagedSkill: async (input: GetManagedSkillInput) =>- withReadSpan('getManagedSkill', undefined, async () => {- if (!adapters.getManagedSkill) return undefined;-- return adapters.getManagedSkill(input);- }),- listMaintenanceProposals: async (input: ListMaintenanceProposalsInput) =>- withReadSpan('listMaintenanceProposals', undefined, async () => {- if (!adapters.listMaintenanceProposals) return [];-- return adapters.listMaintenanceProposals(input);- }),- listManagedSkills: async (input: ListManagedSkillsInput) =>- withReadSpan('listManagedSkills', undefined, async () => {- if (!adapters.listManagedSkills) return [];-- return adapters.listManagedSkills(input);- }),- readMaintenanceProposal: async (input: {- proposalId?: string;- proposalKey?: string;- userId: string;- }) =>- withReadSpan('readMaintenanceProposal', input.proposalKey, async () => {- if (!adapters.readProposal) return undefined;-- return adapters.readProposal(input);- }),- refreshMaintenanceProposal: async (input: RefreshMaintenanceProposalInput) =>- runWriteTool({- adapters,- input,- mutate: adapters.refreshProposal ? () => adapters.refreshProposal!(input) : undefined,- preflight: adapters.preflight ? () => adapters.preflight!(input) : undefined,- preflightRequired: true,- resourceId: input.proposalId,- successStatus: 'proposed',- toolName: 'refreshMaintenanceProposal',- unsupportedSummary: 'Maintenance proposal refresh is not supported.',- }),- replaceSkillContentCAS: async (input: ReplaceSkillContentCASInput) => {- const enrichedInput = adapters.completeReplaceSkillInput- ? await adapters.completeReplaceSkillInput(input)- : input;-- return runWriteTool({- adapters,- input: enrichedInput,- mutate: adapters.replaceSkill ? () => adapters.replaceSkill!(enrichedInput) : undefined,- preflight: adapters.preflight ? () => adapters.preflight!(enrichedInput) : undefined,- preflightRequired: true,- resourceId: enrichedInput.skillDocumentId,- successStatus: 'applied',- toolName: 'replaceSkillContentCAS',- unsupportedSummary: 'Skill replacement is not supported.',- validate: () => {- if (!hasNonBlankString(enrichedInput.bodyMarkdown)) {- return {- resourceId: enrichedInput.skillDocumentId,- status: 'skipped_unsupported',- summary: 'Skill replacement requires a non-empty body.',- };- }-- if (isCompleteRefineBaseSnapshot(enrichedInput.baseSnapshot)) return undefined;-- return {- resourceId: enrichedInput.skillDocumentId,- status: 'skipped_unsupported',- summary: 'Skill replacement requires a complete base snapshot.',- };- },- });- },- supersedeMaintenanceProposal: async (input: SupersedeMaintenanceProposalInput) =>- runWriteTool({- adapters,- input,- mutate: adapters.supersedeProposal ? () => adapters.supersedeProposal!(input) : undefined,- preflight: adapters.preflight ? () => adapters.preflight!(input) : undefined,- preflightRequired: true,- resourceId: input.proposalId,- successStatus: 'applied',- toolName: 'supersedeMaintenanceProposal',- unsupportedSummary: 'Maintenance proposal supersede is not supported.',- }),-});--/** Callable safe maintenance tools exposed to bounded maintenance agent runners. */-export type MaintenanceTools = ReturnType<typeof createMaintenanceTools>;diff --git a/src/server/services/agentSignal/services/maintenance/types.ts b/src/server/services/agentSignal/services/maintenance/types.tsdeleted file mode 100644index 40968422a08..00000000000--- a/src/server/services/agentSignal/services/maintenance/types.ts+++ /dev/null@@ -1,276 +0,0 @@-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/receiptService.ts b/src/server/services/agentSignal/services/receiptService.tsindex 2369746df51..8297caa59d9 100644--- a/src/server/services/agentSignal/services/receiptService.ts+++ b/src/server/services/agentSignal/services/receiptService.ts@@ -4,37 +4,55 @@ import { AGENT_SIGNAL_DEFAULTS } from '../constants';import { AGENT_SIGNAL_POLICY_ACTION_TYPES } from '../policies/types';import { redisReceiptStore } from '../store/adapters/redis/receiptStore';import type {+ ActionPlan,+ ActionResult,+ ActionType,EvidenceRef,- MaintenanceActionPlan,- MaintenanceActionResult,- MaintenanceActionType,- MaintenancePlan,- MaintenanceReviewRunResult,-} from './maintenance/types';-import {- MaintenanceActionStatus,- MaintenanceReviewScope,- ReviewRunStatus,-} from './maintenance/types';--/** Metadata envelope used by maintenance receipts. */+ Idea,+ IterationMode,+ Plan,+ RunResult,+ SelfFeedbackIntent,+} from './selfIteration/types';+import { ActionStatus, ReviewRunStatus, Scope } from './selfIteration/types';++/** Metadata envelope used by self-iteration 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;+ /** Agent Signal action status for action receipts. */+ actionStatus?: ActionStatus;+ /** Agent Signal action type for action receipts. */+ actionType?: ActionType;/** 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;+ /** SelfIteration review scope that produced the receipt. */+ reviewScope?: Scope;/** Scoped self-reflection id for non-nightly review receipts. */scopeId?: string;/** Scoped self-reflection namespace for non-nightly review receipts. */scopeType?: string;+ /** Self-iteration output metadata persisted for reflection and declared-intent review receipts. */+ selfIteration?: {+ /** Non-actionable ideas captured by the shared self-iteration runtime. */+ ideas?: Idea[];+ /** Immediate intents captured by reflection or declared-intent runs. */+ intents?: SelfFeedbackIntent[];+ /** Runtime mode that produced the metadata. */+ mode: IterationMode;+ /** Reflection trigger reason when available. */+ reason?: string;+ /** Scope that bounded the runtime source. */+ scope?: { id: string; type: string };+ /** Source id that produced this metadata. */+ sourceId: string;+ /** Tool call that declared the intent when available. */+ toolCallId?: string;+ /** Evidence window used by the run when available. */+ window?: { end: string; start: string };+ };/** Source type that produced the receipt. */sourceType?: string;/** IANA timezone used for nightly receipt projection. */@@ -56,7 +74,7 @@ export interface AgentSignalReceipt {/** Stable receipt id used as Redis member and payload key suffix. */id: string;/** User-facing durable outcome domain. */- kind: 'maintenance' | 'memory' | 'review' | 'skill';+ kind: 'memory' | 'review' | 'skill';/** Structured metadata for audit, brief linking, and eval assertions. */metadata?: AgentSignalReceiptMetadata;/** Agent runtime operation that produced the receipt, when known. */@@ -131,7 +149,7 @@ interface PersistAgentSignalReceiptsOptions {store?: AgentSignalReceiptStore;}-/** Input used to create one maintenance review summary receipt. */+/** Input used to create one self-iteration review summary receipt. */export interface CreateReviewSummaryReceiptInput {/** Agent that owns the reviewed scope. */agentId: string;@@ -139,14 +157,16 @@ export interface CreateReviewSummaryReceiptInput {createdAt?: number;/** User-local date for nightly reviews. */localDate?: string;- /** Normalized maintenance plan that was executed. */- plan: MaintenancePlan;+ /** Normalized self-iteration plan that was executed. */+ plan: Plan;/** Aggregated executor result for the review. */- result: MaintenanceReviewRunResult;+ result: RunResult;/** Scoped review id for self-reflection and intent runs. */scopeId?: string;/** Scoped review namespace for self-reflection and intent runs. */scopeType?: string;+ /** Optional self-iteration metadata persisted only on the source-level summary receipt. */+ selfIteration?: AgentSignalReceiptMetadata['selfIteration'];/** Source id that triggered the review. */sourceId: string;/** Source type that triggered the review. */@@ -159,10 +179,10 @@ export interface CreateReviewSummaryReceiptInput {userId: string;}-/** Input used to create one maintenance action receipt. */-export interface CreateMaintenanceActionReceiptInput {+/** Input used to create one self-review action receipt. */+export interface CreateSelfReviewActionReceiptInput {/** Planner-normalized action. */- action: MaintenanceActionPlan;+ action: ActionPlan;/** Agent that owns the reviewed scope. */agentId: string;/** Millisecond timestamp for receipt ordering. */@@ -170,9 +190,9 @@ export interface CreateMaintenanceActionReceiptInput {/** User-local date for nightly reviews. */localDate?: string;/** Executor result for the action. */- result: MaintenanceActionResult;+ result: ActionResult;/** Review scope that produced this action. */- reviewScope: MaintenanceReviewScope;+ reviewScope: Scope;/** Scoped review id for self-reflection and intent runs. */scopeId?: string;/** Scoped review namespace for self-reflection and intent runs. */@@ -189,13 +209,22 @@ export interface CreateMaintenanceActionReceiptInput {userId: string;}-/** Input used to create all receipts for one maintenance review run. */-export interface CreateMaintenanceReviewReceiptsInput extends Omit<+/** Input used to create all receipts for one self-review run. */+export interface CreateSelfReviewReceiptsInput extends Omit<CreateReviewSummaryReceiptInput,'plan'> {- /** Normalized maintenance plan that was executed. */- plan: MaintenancePlan;+ /** Normalized self-iteration plan that was executed. */+ plan: Plan;+}++/** Input used to create all receipts for one self-feedback or self-reflection run. */+export interface CreateSelfFeedbackReceiptsInput extends Omit<+ CreateReviewSummaryReceiptInput,+ 'plan'+> {+ /** Normalized self-iteration plan that was executed. */+ plan: Plan;}const getPayloadString = (payload: Record<string, unknown>, key: string) => {@@ -277,36 +306,34 @@ const toReceiptKind = (return;};-const getMaintenanceTopicId = (input: { sourceId: string; topicId?: string }) =>+const getReceiptTopicId = (input: { sourceId: string; topicId?: string }) =>input.topicId ?? input.sourceId;-const getActionReceiptKind = (action: MaintenanceActionPlan): AgentSignalReceipt['kind'] =>- action.operation?.domain ?? 'maintenance';+const getActionReceiptKind = (action: ActionPlan): AgentSignalReceipt['kind'] =>+ action.operation?.domain ?? 'review';-const getActionReceiptStatus = (- status: MaintenanceActionStatus,-): AgentSignalReceipt['status'] | undefined => {- if (status === MaintenanceActionStatus.Applied) return 'applied';- if (status === MaintenanceActionStatus.Proposed) return 'proposed';+const getActionReceiptStatus = (status: ActionStatus): AgentSignalReceipt['status'] | undefined => {+ if (status === ActionStatus.Applied) return 'applied';+ if (status === ActionStatus.Proposed) return 'proposed';return;};-const getActionReceiptTitle = (action: MaintenanceActionPlan, result: MaintenanceActionResult) => {+const getActionReceiptTitle = (action: ActionPlan, result: ActionResult) => {if (result.summary) return getClampedString(result.summary);- if (action.actionType === 'write_memory') return 'Memory maintenance action';+ if (action.actionType === 'write_memory') return 'Memory self-review 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';+ return 'Agent Signal review action';};/**- * Creates one source-level receipt summarizing a maintenance review run.+ * Creates one source-level receipt summarizing a self-iteration review run.** Use when:- * - Nightly or scoped self-reflection handlers finish a maintenance review+ * - Nightly or scoped self-reflection handlers finish a self-iteration review* - Receipts need one audit anchor before action-level receipts are linked to briefs** Expects:@@ -329,6 +356,7 @@ export const createReviewSummaryReceipt = (evidenceRefs: input.plan.actions.flatMap((action) => action.evidenceRefs),...(input.localDate ? { localDate: input.localDate } : {}),reviewScope: input.plan.reviewScope,+ ...(input.selfIteration ? { selfIteration: input.selfIteration } : {}),...(input.scopeId ? { scopeId: input.scopeId } : {}),...(input.scopeType ? { scopeType: input.scopeType } : {}),sourceType: input.sourceType,@@ -338,18 +366,18 @@ export const createReviewSummaryReceipt = (sourceType: input.sourceType,status: input.result.status === ReviewRunStatus.Failed ? 'failed' : 'completed',title:- input.plan.reviewScope === MaintenanceReviewScope.Nightly+ input.plan.reviewScope === Scope.Nightly? 'Nightly self-review completed': 'Self-review completed',- topicId: getMaintenanceTopicId(input),+ topicId: getReceiptTopicId(input),userId: input.userId,});/**- * Creates one action-level maintenance receipt for applied or proposed actions.+ * Creates one action-level self-iteration receipt for applied or proposed actions.** Use when:- * - A maintenance action mutated a resource or produced a user-visible proposal+ * - A self-review action mutated a resource or produced a user-visible proposal* - Brief metadata needs durable receipt ids linked to individual outcomes** Expects:@@ -359,8 +387,8 @@ export const createReviewSummaryReceipt = (* Returns:* - A stable action receipt, or `undefined` when no user-visible action receipt is needed*/-export const createMaintenanceActionReceipt = (- input: CreateMaintenanceActionReceiptInput,+export const createSelfReviewActionReceipt = (+ input: CreateSelfReviewActionReceiptInput,): AgentSignalReceipt | undefined => {if (input.action.actionType === 'noop') return;@@ -397,7 +425,7 @@ export const createMaintenanceActionReceipt = (type: kind === 'skill' ? 'skill' : 'memory',},title,- topicId: getMaintenanceTopicId(input),+ topicId: getReceiptTopicId(input),userId: input.userId,};};@@ -415,15 +443,13 @@ export const createMaintenanceActionReceipt = (* Returns:* - Receipts ordered as summary first, then action results in executor order*/-export const createMaintenanceReviewReceipts = (- input: CreateMaintenanceReviewReceiptsInput,-): AgentSignalReceipt[] => {+const createReceipts = (input: CreateReviewSummaryReceiptInput): 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({+ const receipt = createSelfReviewActionReceipt({action,agentId: input.agentId,createdAt: input.createdAt,@@ -445,6 +471,40 @@ export const createMaintenanceReviewReceipts = (return [createReviewSummaryReceipt(input), ...actionReceipts];};+/**+ * Projects one nightly self-review summary receipt plus applied/proposed action receipts.+ *+ * Use when:+ * - Nightly self-review handlers need receipts before Daily Brief creation+ * - Review action receipts should stay named as self-review output+ *+ * Expects:+ * - `plan.actions` and `result.actions` share action idempotency keys+ *+ * Returns:+ * - Receipts ordered as summary first, then action results in executor order+ */+export const createSelfReviewReceipts = (+ input: CreateSelfReviewReceiptsInput,+): AgentSignalReceipt[] => createReceipts(input);++/**+ * Projects one self-feedback summary receipt plus applied/proposed action receipts.+ *+ * Use when:+ * - Immediate self-feedback or self-reflection handlers finish a scoped run+ * - Receipt metadata carries self-feedback ideas or intents+ *+ * Expects:+ * - `plan.actions` and `result.actions` share action idempotency keys+ *+ * Returns:+ * - Receipts ordered as summary first, then action results in executor order+ */+export const createSelfFeedbackReceipts = (+ input: CreateSelfFeedbackReceiptsInput,+): AgentSignalReceipt[] => createReceipts(input);+/*** 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/selfFeedbackIntent.tssimilarity index 69%rename from src/server/services/agentSignal/services/selfIterationIntent.tsrename to src/server/services/agentSignal/services/selfFeedbackIntent.tsindex ee537a4ead0..21167dae372 100644--- a/src/server/services/agentSignal/services/selfIterationIntent.ts+++ b/src/server/services/agentSignal/services/selfFeedbackIntent.ts@@ -2,34 +2,34 @@ 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';+import type { EvidenceRef } from './selfIteration/types';+import { buildSelfFeedbackIntentSourceId } from './selfIteration/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';+/** Actions that an agent may declare as self-feedback intent. */+export type SelfFeedbackIntentAction = 'write' | 'create' | 'refine' | 'consolidate' | 'proposal';-/** Maintenance target categories accepted from agent-declared intent. */-export type SelfIterationIntentKind = 'memory' | 'skill' | 'gap';+/** Self-feedback target categories accepted from agent-declared intent. */+export type SelfFeedbackIntentKind = 'memory' | 'skill' | 'gap';/** Evidence strength assigned to one accepted or rejected declaration. */-export type SelfIterationIntentStrength = 'strong' | 'weak';+export type SelfFeedbackIntentStrength = 'strong' | 'weak';-/** Source event input emitted by the self-iteration intent declaration service. */-export type SelfIterationIntentSourceEventInput =- AgentSignalSourceEventInput<'agent.self_iteration_intent.declared'>;+/** Source event input emitted by the self-feedback intent declaration service. */+export type SelfFeedbackIntentSourceEventInput =+ AgentSignalSourceEventInput<'agent.self_feedback_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;+/** Input payload declared by the running agent through the self-feedback intent tool. */+export interface DeclareSelfFeedbackIntentPayload {+ /** Self-feedback action the agent believes may be useful. */+ action: SelfFeedbackIntentAction;/** Agent confidence from 0 to 1. */confidence: number;/** Evidence references that justify the declaration. */evidenceRefs?: EvidenceRef[];/** Target category for the declaration. */- kind: SelfIterationIntentKind;+ kind: SelfFeedbackIntentKind;/** Existing memory id when the declaration targets a known memory. */memoryId?: string;/** Human-readable rationale from the agent. */@@ -40,12 +40,12 @@ export interface DeclareSelfIterationIntentPayload {summary: string;}-/** Input used to declare one agent-facing self-iteration intent source event. */-export interface DeclareSelfIterationIntentInput {+/** Input used to declare one agent-facing self-feedback intent source event. */+export interface DeclareSelfFeedbackIntentInput {/** Stable agent id associated with the running agent. */agentId: string;- /** Agent-declared maintenance intent payload. */- input: DeclareSelfIterationIntentPayload;+ /** Agent-declared self-feedback intent payload. */+ input: DeclareSelfFeedbackIntentPayload;/** 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. */@@ -57,7 +57,7 @@ export interface DeclareSelfIterationIntentInput {}/** Result returned after one declaration attempt. */-export interface DeclareSelfIterationIntentResult {+export interface DeclareSelfFeedbackIntentResult {/** Whether the declaration was accepted and emitted to the enqueue boundary. */accepted: boolean;/** Optional rejection reason when no source was enqueued. */@@ -71,37 +71,37 @@ export interface DeclareSelfIterationIntentResult {/** Stable source id built for accepted declarations when available. */sourceId?: string;/** Evidence strength assigned from confidence and evidence presence. */- strength: SelfIterationIntentStrength;+ strength: SelfFeedbackIntentStrength;}-/** Dependencies used by the pure self-iteration intent declaration service. */-export interface SelfIterationIntentServiceDependencies {+/** Dependencies used by the pure self-feedback intent declaration service. */+export interface SelfFeedbackIntentServiceDependencies {/*** Optional declaration-level gate checked before source event construction crosses enqueue* boundaries.** @default Allows declarations.*/- canDeclareIntent?: (input: DeclareSelfIterationIntentInput) => MaybePromise<boolean>;+ canDeclareIntent?: (input: DeclareSelfFeedbackIntentInput) => 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>;+ canEnqueue?: (input: SelfFeedbackIntentSourceEventInput) => MaybePromise<boolean>;+ /** Enqueues one self-feedback intent source event. */+ enqueueSource: (input: SelfFeedbackIntentSourceEventInput) => 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 {+export interface SelfFeedbackIntentService {/**- * Emits one agent-declared self-iteration intent source event when validation and gates pass.+ * Emits one agent-declared self-feedback intent source event when validation and gates pass.** Use when:- * - A running chat or task agent wants to declare maintenance intent+ * - A running chat or task agent wants to declare self-feedback intent* - Callers need a source-event boundary without direct memory or skill mutation** Expects:@@ -112,23 +112,23 @@ export interface SelfIterationIntentService {* - Source acceptance status, stable source id when emitted, and evidence strength*/declareIntent: (- input: DeclareSelfIterationIntentInput,- ) => Promise<DeclareSelfIterationIntentResult>;+ input: DeclareSelfFeedbackIntentInput,+ ) => Promise<DeclareSelfFeedbackIntentResult>;}const DECLARATION_LIMIT_PER_SCOPE = 3;const STRONG_CONFIDENCE_THRESHOLD = 0.75;-const validActions = new Set<SelfIterationIntentAction>([+const validActions = new Set<SelfFeedbackIntentAction>(['write','create','refine','consolidate','proposal',]);-const validKinds = new Set<SelfIterationIntentKind>(['memory', 'skill', 'gap']);+const validKinds = new Set<SelfFeedbackIntentKind>(['memory', 'skill', 'gap']);-const getStrength = (input: DeclareSelfIterationIntentPayload): SelfIterationIntentStrength => {+const getStrength = (input: DeclareSelfFeedbackIntentPayload): SelfFeedbackIntentStrength => {if (!input.evidenceRefs?.length || input.confidence < STRONG_CONFIDENCE_THRESHOLD) {return 'weak';}@@ -136,13 +136,13 @@ const getStrength = (input: DeclareSelfIterationIntentPayload): SelfIterationIntreturn 'strong';};-const getRateLimitScopeKey = (input: DeclareSelfIterationIntentInput) => {+const getRateLimitScopeKey = (input: DeclareSelfFeedbackIntentInput) => {const scopeKey = input.operationId ? `operation:${input.operationId}` : `topic:${input.topicId}`;return `${input.userId}:${input.agentId}:${scopeKey}`;};-const getIntentScope = (input: DeclareSelfIterationIntentInput) =>+const getIntentScope = (input: DeclareSelfFeedbackIntentInput) =>input.operationId? ({scopeId: input.operationId,@@ -155,7 +155,7 @@ const isValidConfidence = (confidence: number) =>Number.isFinite(confidence) && confidence >= 0 && confidence <= 1;/**- * Creates a pure self-iteration intent declaration service.+ * Creates a pure self-feedback intent declaration service.** Use when:* - Runtime tool handlers need a DI-friendly source emission boundary@@ -168,9 +168,9 @@ const isValidConfidence = (confidence: number) =>* Returns:* - A service that emits accepted declarations and never mutates memory or skill resources*/-export const createSelfIterationIntentService = (- deps: SelfIterationIntentServiceDependencies,-): SelfIterationIntentService => {+export const createSelfFeedbackIntentService = (+ deps: SelfFeedbackIntentServiceDependencies,+): SelfFeedbackIntentService => {const acceptedCounts = new Map<string, number>();return {@@ -202,14 +202,14 @@ export const createSelfIterationIntentService = (const toolCallId = input.toolCallId ?? deps.nextToolCallId();const intentScope = getIntentScope(input);- const sourceId = buildSelfIterationIntentSourceId({+ const sourceId = buildSelfFeedbackIntentSourceId({agentId: input.agentId,scopeId: intentScope.scopeId,scopeType: intentScope.scopeType,toolCallId,userId: input.userId,});- const sourceEvent: SelfIterationIntentSourceEventInput = {+ const sourceEvent: SelfFeedbackIntentSourceEventInput = {payload: {action: input.input.action,agentId: input.agentId,@@ -227,7 +227,7 @@ export const createSelfIterationIntentService = (},scopeKey: intentScope.scopeKey,sourceId,- sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentSelfIterationIntentDeclared,+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentSelfFeedbackIntentDeclared,};if (deps.canEnqueue && !(await deps.canEnqueue(sourceEvent))) {diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/agent.test.ts b/src/server/services/agentSignal/services/selfIteration/__test__/execute.test.tssimilarity index 51%rename from src/server/services/agentSignal/services/maintenance/__tests__/agent.test.tsrename to src/server/services/agentSignal/services/selfIteration/__test__/execute.test.tsindex 9e40fce585f..62437014b52 100644--- a/src/server/services/agentSignal/services/maintenance/__tests__/agent.test.ts+++ b/src/server/services/agentSignal/services/selfIteration/__test__/execute.test.ts@@ -5,9 +5,12 @@ import { consumeStreamUntilDone } from '@lobechat/model-runtime';import type { MessageToolCall, ModelUsage } from '@lobechat/types';import { beforeEach, describe, expect, it, vi } from 'vitest';-import { runMaintenanceToolFirstRuntime } from '../agent';-import type { NightlyReviewContext } from '../nightlyCollector';-import type { MaintenanceTools, MaintenanceToolWriteResult } from '../tools';+import type { AgentRunResult } from '../execute';+import { createAgentRunner, executeSelfIteration } from '../execute';+import type { NightlyReviewContext } from '../review/collect';+import type { ToolSet, ToolWriteResult } from '../tools/shared';+import { createToolSet } from '../tools/shared';+import { ActionStatus, ApplyMode, ReviewRunStatus, Risk, Scope } from '../types';vi.mock('@lobechat/model-runtime', async (importOriginal) => {const actual = await importOriginal<typeof ModelRuntimeModule>();@@ -31,7 +34,7 @@ const reviewContext = {notSatisfied: [],satisfied: [],},- maintenanceSignals: [],+ selfReviewSignals: [],managedSkills: [],proposalActivity: {active: [],@@ -51,6 +54,7 @@ const reviewContext = {relevantMemories: [],reviewWindowEnd: '2026-05-04T14:00:00.000Z',reviewWindowStart: '2026-05-03T14:00:00.000Z',+ selfFeedbackCandidates: [],toolActivity: [],topics: [],userId: 'user-1',@@ -82,31 +86,36 @@ const createMockModelRuntime = (steps: MockChatStep[]) => {};};-const createMockTools = (writeResult?: MaintenanceToolWriteResult): MaintenanceTools => ({- closeMaintenanceProposal: vi.fn(async () => ({+const createNoopTools = () =>+ createToolSet({+ reserveOperation: vi.fn(async () => ({ reserved: true as const })),+ writeReceipt: vi.fn(async () => ({ receiptId: 'receipt-1' })),+ });++const createMockTools = (writeResult?: ToolWriteResult): ToolSet => ({+ closeSelfReviewProposal: vi.fn(async () => ({receiptId: 'receipt-close',status: 'applied' as const,})),- createMaintenanceProposal: vi.fn(async () => ({+ createSelfReviewProposal: vi.fn(async () => ({receiptId: 'receipt-proposal',status: 'proposed' as const,})),- createSkillIfAbsent: vi.fn(async () =>- writeResult- ? writeResult- : {- receiptId: 'receipt-skill',- resourceId: 'skill-1',- status: 'applied' as const,- summary: 'Created skill.',- },+ createSkillIfAbsent: vi.fn(+ async () =>+ writeResult || {+ receiptId: 'receipt-skill',+ resourceId: 'skill-1',+ status: 'applied' as const,+ summary: 'Created skill.',+ },),getEvidenceDigest: vi.fn(async () => ({ evidence: [] })),getManagedSkill: vi.fn(async () => ({ id: 'skill-1' })),- listMaintenanceProposals: vi.fn(async () => []),+ listSelfReviewProposals: vi.fn(async () => []),listManagedSkills: vi.fn(async () => []),- readMaintenanceProposal: vi.fn(async () => undefined),- refreshMaintenanceProposal: vi.fn(async () => ({+ readSelfReviewProposal: vi.fn(async () => undefined),+ refreshSelfReviewProposal: vi.fn(async () => ({receiptId: 'receipt-refresh',status: 'proposed' as const,})),@@ -114,23 +123,22 @@ const createMockTools = (writeResult?: MaintenanceToolWriteResult): MaintenanceTreceiptId: 'receipt-replace',status: 'applied' as const,})),- supersedeMaintenanceProposal: vi.fn(async () => ({+ supersedeSelfReviewProposal: vi.fn(async () => ({receiptId: 'receipt-supersede',status: 'applied' as const,})),- writeMemory: vi.fn(async () =>- writeResult- ? writeResult- : {- receiptId: 'receipt-memory',- resourceId: 'memory-1',- status: 'applied' as const,- summary: 'Wrote memory.',- },+ writeMemory: vi.fn(+ async () =>+ writeResult || {+ receiptId: 'receipt-memory',+ resourceId: 'memory-1',+ status: 'applied' as const,+ summary: 'Wrote memory.',+ },),});-describe('runMaintenanceToolFirstRuntime', () => {+describe('executeSelfIteration', () => {beforeEach(() => {vi.clearAllMocks();});@@ -146,7 +154,7 @@ describe('runMaintenanceToolFirstRuntime', () => {resourceId: 'skill-1',status: 'applied',summary: 'Created skill.',- } satisfies MaintenanceToolWriteResult;+ } satisfies ToolWriteResult;const tools = createMockTools(writeResult);const { chat, modelRuntime } = createMockModelRuntime([{@@ -174,7 +182,7 @@ describe('runMaintenanceToolFirstRuntime', () => {},]);- const result = await runMaintenanceToolFirstRuntime({+ const result = await executeSelfIteration({agentId: 'agent-1',context: reviewContext,maxSteps: 5,@@ -213,7 +221,7 @@ describe('runMaintenanceToolFirstRuntime', () => {resourceId: 'memory-1',status: 'applied',summary: 'Wrote memory.',- } satisfies MaintenanceToolWriteResult;+ } satisfies ToolWriteResult;const tools = createMockTools(writeResult);const { modelRuntime } = createMockModelRuntime([{@@ -238,7 +246,7 @@ describe('runMaintenanceToolFirstRuntime', () => {},]);- const result = await runMaintenanceToolFirstRuntime({+ const result = await executeSelfIteration({agentId: 'agent-1',context: reviewContext,maxSteps: 5,@@ -260,16 +268,109 @@ describe('runMaintenanceToolFirstRuntime', () => {expect(result.writeOutcomes).toEqual([{ result: writeResult, toolName: 'writeMemory' }]);});+ /**+ * @example+ * expect(prompt).toContain('skill_document_with_tool_failure');+ * expect(prompt).toContain('createSelfReviewProposal');+ */+ it('shows deterministic proposal rules for skill document failures in the review prompt', async () => {+ const tools = createMockTools();+ const { chat, modelRuntime } = createMockModelRuntime([+ {+ content: 'No action.',+ },+ ]);++ await executeSelfIteration({+ agentId: 'agent-1',+ context: {+ ...reviewContext,+ documentActivity: {+ ...reviewContext.documentActivity,+ skillBucket: [+ {+ agentDocumentId: 'skill-doc-1',+ documentId: 'doc-1',+ hintIsSkill: false,+ reason: 'templateId=agent-skill',+ updatedAt: '2026-05-04T13:00:00.000Z',+ },+ ],+ },+ selfReviewSignals: [+ {+ evidenceRefs: [+ { id: 'topic-1', type: 'topic' },+ { id: 'message-1', type: 'message' },+ { id: 'skill-doc-1', type: 'agent_document' },+ ],+ features: [+ {+ apiName: 'replaceSkillContentCAS',+ failedCount: 2,+ identifier: 'agent-signal-self-iteration',+ topicCount: 1,+ totalCount: 2,+ type: 'tool_usage',+ },+ ],+ kind: 'skill_document_with_tool_failure',+ strength: 'medium',+ },+ ],+ managedSkills: [+ {+ documentId: 'skill-doc-1',+ name: 'release-note-checklist',+ readonly: false,+ },+ ],+ toolActivity: [+ {+ apiName: 'replaceSkillContentCAS',+ failedCount: 2,+ identifier: 'agent-signal-self-iteration',+ messageIds: ['message-1'],+ sampleArgs: [+ JSON.stringify({+ bodyMarkdown: '# Release note checklist',+ proposalKey: 'agent-1:refine_skill:agent_document:skill-doc-1',+ skillDocumentId: 'skill-doc-1',+ }),+ ],+ sampleErrors: ['CAS snapshot failed'],+ topicIds: ['topic-1'],+ totalCount: 2,+ },+ ],+ },+ maxSteps: 1,+ model: 'gpt-test',+ modelRuntime,+ sourceId: 'source-1',+ tools,+ userId: 'user-1',+ });++ const prompt = JSON.stringify(chat.mock.calls[0]?.[0].messages);++ expect(prompt).toContain('skill_document_with_tool_failure');+ expect(prompt).toContain('createSelfReviewProposal');+ expect(prompt).toContain('# Release note checklist');+ expect(prompt).toContain('refine_skill');+ expect(prompt).toContain('replaceSkillContentCAS');+ });+/*** @example* expect(systemPrompt).toContain('getEvidenceDigest');- * expect(systemPrompt).toContain('readMaintenanceProposal');+ * expect(systemPrompt).toContain('readSelfReviewProposal');*/- it('tells the model to keep evidence ids separate from maintenance proposal keys', async () => {+ it('tells the model to keep evidence ids separate from self-review proposal keys', async () => {const tools = createMockTools();const { chat, modelRuntime } = createMockModelRuntime([{ content: 'No action needed.' }]);- await runMaintenanceToolFirstRuntime({+ await executeSelfIteration({agentId: 'agent-1',context: reviewContext,maxSteps: 1,@@ -283,10 +384,98 @@ describe('runMaintenanceToolFirstRuntime', () => {const systemPrompt = chat.mock.calls[0]?.[0].messages[0]?.content;expect(systemPrompt).toContain('getEvidenceDigest');- expect(systemPrompt).toContain('readMaintenanceProposal');+ expect(systemPrompt).toContain('readSelfReviewProposal');expect(systemPrompt).toContain('Evidence ids and proposal keys are different namespaces');});+ /**+ * @example+ * expect(userPrompt).toContain('<self_iteration_review');+ * expect(userPrompt).toContain('<nightly_review_context_json>');+ */+ it('wraps the nightly review prompt in XML while keeping review labels visible', async () => {+ const tools = createMockTools();+ const { chat, modelRuntime } = createMockModelRuntime([{ content: 'No action needed.' }]);++ await executeSelfIteration({+ agentId: 'agent-1',+ context: reviewContext,+ maxSteps: 1,+ model: 'gpt-test',+ modelRuntime,+ sourceId: 'source-1',+ tools,+ userId: 'user-1',+ });++ const userPrompt = chat.mock.calls[0]?.[0].messages[1]?.content;++ expect(userPrompt).toContain('<self_iteration_review');+ expect(userPrompt).toContain('review_window_start="2026-05-03T14:00:00.000Z"');+ expect(userPrompt).toContain('review_window_end="2026-05-04T14:00:00.000Z"');+ expect(userPrompt).toContain('<nightly_review_context_json>');+ expect(userPrompt).not.toContain('Self-iteration context JSON:');+ });++ /**+ * @example+ * expect(userPrompt).toContain('Mode: reflection');+ * expect(tools.getEvidenceDigest).toHaveBeenCalledWith(expect.objectContaining({ reviewWindowStart: '2026-05-04T14:00:00.000Z' }));+ */+ it('exposes explicit mode and evidence window to the prompt and evidence tool fallback', async () => {+ const tools = createMockTools();+ const { chat, modelRuntime } = createMockModelRuntime([+ {+ content: 'I will inspect evidence.',+ toolCalls: [+ {+ function: {+ arguments: JSON.stringify({+ evidenceIds: ['task-1'],+ }),+ name: 'getEvidenceDigest',+ },+ id: 'tool-call-evidence',+ type: 'function',+ },+ ],+ },+ {+ content: 'Evidence inspected.',+ },+ ]);++ await executeSelfIteration({+ agentId: 'agent-1',+ context: reviewContext,+ maxSteps: 2,+ mode: 'reflection',+ model: 'gpt-test',+ modelRuntime,+ sourceId: 'source-1',+ tools,+ userId: 'user-1',+ window: {+ end: '2026-05-04T14:30:00.000Z',+ start: '2026-05-04T14:00:00.000Z',+ },+ });++ const userPrompt = chat.mock.calls[0]?.[0].messages[1]?.content;++ expect(userPrompt).toContain('Mode: reflection');+ expect(userPrompt).toContain(+ 'Evidence window: 2026-05-04T14:00:00.000Z to 2026-05-04T14:30:00.000Z',+ );+ expect(tools.getEvidenceDigest).toHaveBeenCalledWith(+ expect.objectContaining({+ evidenceIds: ['task-1'],+ reviewWindowEnd: '2026-05-04T14:30:00.000Z',+ reviewWindowStart: '2026-05-04T14:00:00.000Z',+ }),+ );+ });+/*** @example* expect(result.writeOutcomes).toEqual([]);@@ -301,7 +490,7 @@ describe('runMaintenanceToolFirstRuntime', () => {{function: {arguments: '{"unexpected":true}',- name: 'missingMaintenanceTool',+ name: 'missingSelfIterationTool',},id: 'tool-call-unsupported',type: 'function',@@ -313,7 +502,7 @@ describe('runMaintenanceToolFirstRuntime', () => {},]);- const result = await runMaintenanceToolFirstRuntime({+ const result = await executeSelfIteration({agentId: 'agent-1',context: reviewContext,maxSteps: 4,@@ -360,7 +549,7 @@ describe('runMaintenanceToolFirstRuntime', () => {},]);- const result = await runMaintenanceToolFirstRuntime({+ const result = await executeSelfIteration({agentId: 'agent-1',context: reviewContext,maxSteps: 1,@@ -380,7 +569,7 @@ describe('runMaintenanceToolFirstRuntime', () => {/*** @example- * expect(modelVisibleMessages).toContain('Maintenance tool call failed.');+ * expect(modelVisibleMessages).toContain('Self-review tool call failed.');* expect(modelVisibleMessages).not.toContain('secret-token-123');*/it('sanitizes thrown tool errors before adding model-visible tool messages', async () => {@@ -389,7 +578,7 @@ describe('runMaintenanceToolFirstRuntime', () => {createSkillIfAbsent: vi.fn(async () => {throw new Error('upstream secret-token-123 failed');}),- } satisfies MaintenanceTools;+ } satisfies ToolSet;const { chat, modelRuntime } = createMockModelRuntime([{content: 'I will create a skill.',@@ -413,7 +602,7 @@ describe('runMaintenanceToolFirstRuntime', () => {},]);- await runMaintenanceToolFirstRuntime({+ await executeSelfIteration({agentId: 'agent-1',context: reviewContext,maxSteps: 5,@@ -426,7 +615,103 @@ describe('runMaintenanceToolFirstRuntime', () => {const modelVisibleMessages = JSON.stringify(chat.mock.calls[1]?.[0].messages);- expect(modelVisibleMessages).toContain('Maintenance tool call failed.');+ expect(modelVisibleMessages).toContain('Self-iteration tool call failed.');expect(modelVisibleMessages).not.toContain('secret-token-123');});});++describe('createAgentRunner', () => {+ /**+ * @example+ * expect(result.projectionPlan.actions).toHaveLength(1);+ */+ it('passes source metadata, max steps, and tools into the backend runner', async () => {+ const tools = createNoopTools();+ const run = vi.fn<() => Promise<AgentRunResult>>(async () => ({+ execution: {+ actions: [+ {+ idempotencyKey: 'source-1:noop',+ status: ActionStatus.Skipped,+ },+ ],+ status: ReviewRunStatus.Completed,+ },+ projectionPlan: {+ actions: [+ {+ actionType: 'noop',+ applyMode: ApplyMode.Skip,+ confidence: 1,+ dedupeKey: 'noop',+ evidenceRefs: [{ id: 'topic-1', type: 'topic' }],+ idempotencyKey: 'source-1:noop',+ rationale: 'No change needed.',+ risk: Risk.Low,+ },+ ],+ localDate: '2026-05-04',+ plannerVersion: 'test',+ reviewScope: Scope.Nightly,+ summary: 'No change needed.',+ },+ stepCount: 2,+ }));+ const runner = createAgentRunner({ maxSteps: 10, run, tools });++ const result = await runner.run({+ context: reviewContext,+ localDate: '2026-05-04',+ sourceId: 'source-1',+ userId: 'user-1',+ });++ expect(run).toHaveBeenCalledWith(+ expect.objectContaining({+ context: reviewContext,+ localDate: '2026-05-04',+ maxSteps: 10,+ reviewScope: Scope.Nightly,+ sourceId: 'source-1',+ tools,+ userId: 'user-1',+ }),+ );+ expect(result.execution.sourceId).toBe('source-1');+ expect(result.projectionPlan.actions).toHaveLength(1);+ });++ /**+ * @example+ * expect(result.execution.status).toBe('failed');+ */+ it('returns a conservative failed envelope when the backend runner throws', async () => {+ const runner = createAgentRunner({+ run: vi.fn(async () => {+ throw new Error('model failed');+ }),+ tools: createNoopTools(),+ });++ const result = await runner.run({+ context: reviewContext,+ localDate: '2026-05-04',+ sourceId: 'source-1',+ userId: 'user-1',+ });++ expect(result.execution).toEqual({+ actions: [],+ sourceId: 'source-1',+ status: ReviewRunStatus.Failed,+ });+ expect(result.projectionPlan).toEqual(+ expect.objectContaining({+ actions: [],+ localDate: '2026-05-04',+ reviewScope: Scope.Nightly,+ }),+ );+ expect(result.stepCount).toBe(10);+ });+});diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/briefProjection.test.ts b/src/server/services/agentSignal/services/selfIteration/__test__/projection.test.tssimilarity index 82%rename from src/server/services/agentSignal/services/maintenance/__tests__/briefProjection.test.tsrename to src/server/services/agentSignal/services/selfIteration/__test__/projection.test.tsindex 7b8a852c79e..ebd8823b04a 100644--- a/src/server/services/agentSignal/services/maintenance/__tests__/briefProjection.test.ts+++ b/src/server/services/agentSignal/services/selfIteration/__test__/projection.test.ts@@ -1,24 +1,15 @@import { describe, expect, it } from 'vitest';-import {- projectMaintenanceToolOutcomes,- projectMaintenanceToolRuntimeRun,-} from '../briefProjection';-import {- MaintenanceActionStatus,- MaintenanceApplyMode,- MaintenanceReviewScope,- MaintenanceRisk,- ReviewRunStatus,-} from '../types';+import { projectOutcomes, projectRun } from '../projection';+import { ActionStatus, ApplyMode, ReviewRunStatus, Risk, Scope } from '../types';-describe('projectMaintenanceToolOutcomes', () => {+describe('projectOutcomes', () => {/*** @example* Empty tool outcome lists stay silent and carry empty metadata.*/it('does not request a brief when no write tools ran', () => {- const projection = projectMaintenanceToolOutcomes({ outcomes: [] });+ const projection = projectOutcomes({ outcomes: [] });expect(projection).toEqual({actionCounts: { applied: 0, failed: 0, proposed: 0, skipped: 0 },@@ -34,7 +25,7 @@ describe('projectMaintenanceToolOutcomes', () => {* Applied write-tool outcomes become insight metadata with durable receipt links.*/it('projects applied writes to insight metadata with action and receipt ids', () => {- const projection = projectMaintenanceToolOutcomes({+ const projection = projectOutcomes({outcomes: [{receiptId: 'receipt-1',@@ -68,28 +59,28 @@ describe('projectMaintenanceToolOutcomes', () => {* Proposal lifecycle tool outcomes stay silent because they mutate proposal state, not resources.*/it('keeps proposal lifecycle outcomes out of resource decision metadata', () => {- const projection = projectMaintenanceToolOutcomes({+ const projection = projectOutcomes({outcomes: [{receiptId: 'receipt-created',resourceId: 'proposal-1',status: 'proposed',summary: 'Review new skill proposal.',- toolName: 'createMaintenanceProposal',+ toolName: 'createSelfReviewProposal',},{receiptId: 'receipt-refreshed',resourceId: 'proposal-2',status: 'proposed',summary: 'Review refreshed skill proposal.',- toolName: 'refreshMaintenanceProposal',+ toolName: 'refreshSelfReviewProposal',},{receiptId: 'receipt-superseded',resourceId: 'proposal-3',status: 'proposed',summary: 'Review superseding skill proposal.',- toolName: 'supersedeMaintenanceProposal',+ toolName: 'supersedeSelfReviewProposal',},],});@@ -114,7 +105,7 @@ describe('projectMaintenanceToolOutcomes', () => {* Visible risky write outcomes create insight metadata when no decision exists.*/it('projects stale and failed outcomes to insight metadata', () => {- const projection = projectMaintenanceToolOutcomes({+ const projection = projectOutcomes({outcomes: [{receiptId: 'receipt-stale',@@ -125,7 +116,7 @@ describe('projectMaintenanceToolOutcomes', () => {{status: 'failed',summary: 'Proposal close failed.',- toolName: 'closeMaintenanceProposal',+ toolName: 'closeSelfReviewProposal',},],});@@ -145,7 +136,7 @@ describe('projectMaintenanceToolOutcomes', () => {* Unsupported and deduped writes are retained as metadata but stay brief-silent.*/it('keeps skipped unsupported and deduped outcomes silent when they are the only outcomes', () => {- const projection = projectMaintenanceToolOutcomes({+ const projection = projectOutcomes({outcomes: [{receiptId: 'receipt-unsupported',@@ -156,7 +147,7 @@ describe('projectMaintenanceToolOutcomes', () => {{status: 'deduped',summary: 'Duplicate operation.',- toolName: 'refreshMaintenanceProposal',+ toolName: 'refreshSelfReviewProposal',},],});@@ -172,13 +163,13 @@ describe('projectMaintenanceToolOutcomes', () => {});});-describe('projectMaintenanceToolRuntimeRun', () => {+describe('projectRun', () => {/*** @example- * projectMaintenanceToolRuntimeRun keeps createMaintenanceProposal action payloads approve-ready.+ * projectRun keeps createSelfReviewProposal action payloads approve-ready.*/it('preserves proposed create skill actions from proposal lifecycle tool arguments', () => {- const projection = projectMaintenanceToolRuntimeRun({+ const projection = projectRun({content: 'Created a proposal.',includeProposalLifecycleActions: true,localDate: '2026-05-09',@@ -188,19 +179,19 @@ describe('projectMaintenanceToolRuntimeRun', () => {resourceId: 'brief-proposal-1',status: 'proposed',summary: 'Review concise answers skill.',- toolName: 'createMaintenanceProposal',+ toolName: 'createSelfReviewProposal',},],- reviewScope: MaintenanceReviewScope.Nightly,+ reviewScope: Scope.Nightly,sourceId: 'source-1',toolCalls: [{- apiName: 'createMaintenanceProposal',+ apiName: 'createSelfReviewProposal',arguments: JSON.stringify({actions: [{actionType: 'create_skill',- applyMode: MaintenanceApplyMode.ProposalOnly,+ applyMode: ApplyMode.ProposalOnly,baseSnapshot: {absent: true,skillName: 'concise-answers',@@ -221,7 +212,7 @@ describe('projectMaintenanceToolRuntimeRun', () => {operation: 'create',},rationale: 'User repeatedly asks for concise answers.',- risk: MaintenanceRisk.Low,+ risk: Risk.Low,target: { skillName: 'concise-answers' },},],@@ -230,7 +221,7 @@ describe('projectMaintenanceToolRuntimeRun', () => {summary: 'Review concise answers skill.',}),id: 'call-proposal-1',- identifier: 'agent-signal-maintenance',+ identifier: 'agent-signal-self-iteration',type: 'builtin',},],@@ -242,7 +233,7 @@ describe('projectMaintenanceToolRuntimeRun', () => {idempotencyKey: 'source-1:create_skill:concise-answers',receiptId: 'receipt-proposal-1',resourceId: 'brief-proposal-1',- status: MaintenanceActionStatus.Proposed,+ status: ActionStatus.Proposed,summary: 'Review concise answers skill.',},]);@@ -265,10 +256,10 @@ describe('projectMaintenanceToolRuntimeRun', () => {/*** @example- * projectMaintenanceToolRuntimeRun binds repeated same-name write outcomes by call order.+ * projectRun binds repeated same-name write outcomes by call order.*/it('matches repeated same-name tool outcomes to their own ordered tool call arguments', () => {- const projection = projectMaintenanceToolRuntimeRun({+ const projection = projectRun({outcomes: [{receiptId: 'receipt-first',@@ -283,7 +274,7 @@ describe('projectMaintenanceToolRuntimeRun', () => {toolName: 'createSkillIfAbsent',},],- reviewScope: MaintenanceReviewScope.Nightly,+ reviewScope: Scope.Nightly,sourceId: 'source-1',toolCalls: [{@@ -294,7 +285,7 @@ describe('projectMaintenanceToolRuntimeRun', () => {name: 'first-skill',}),id: 'call-first',- identifier: 'agent-signal-maintenance',+ identifier: 'agent-signal-self-iteration',type: 'builtin',},{@@ -305,7 +296,7 @@ describe('projectMaintenanceToolRuntimeRun', () => {name: 'second-skill',}),id: 'call-second',- identifier: 'agent-signal-maintenance',+ identifier: 'agent-signal-self-iteration',type: 'builtin',},],@@ -335,31 +326,31 @@ describe('projectMaintenanceToolRuntimeRun', () => {/*** @example- * projectMaintenanceToolRuntimeRun must not emit unapprovable proposal_only actions for refreshes.+ * projectRun must not emit unapprovable proposal_only actions for refreshes.*/it('does not project proposal refresh outcomes without executable actions into decision actions', () => {- const projection = projectMaintenanceToolRuntimeRun({+ const projection = projectRun({outcomes: [{receiptId: 'receipt-refresh',resourceId: 'brief-proposal-1',status: 'proposed',summary: 'Refreshed existing proposal.',- toolName: 'refreshMaintenanceProposal',+ toolName: 'refreshSelfReviewProposal',},],- reviewScope: MaintenanceReviewScope.Nightly,+ reviewScope: Scope.Nightly,sourceId: 'source-1',toolCalls: [{- apiName: 'refreshMaintenanceProposal',+ apiName: 'refreshSelfReviewProposal',arguments: JSON.stringify({idempotencyKey: 'refresh-op-1',proposalId: 'brief-proposal-1',summary: 'Refreshed existing proposal.',}),id: 'call-refresh-1',- identifier: 'agent-signal-maintenance',+ identifier: 'agent-signal-self-iteration',type: 'builtin',},],@@ -373,25 +364,25 @@ describe('projectMaintenanceToolRuntimeRun', () => {/*** @example- * projectMaintenanceToolRuntimeRun must not turn malformed create proposal calls into approval work.+ * projectRun must not turn malformed create proposal calls into approval work.*/it('does not project create proposal outcomes without executable actions into decision actions', () => {- const projection = projectMaintenanceToolRuntimeRun({+ const projection = projectRun({outcomes: [{receiptId: 'receipt-create-proposal',resourceId: 'brief-proposal-1',status: 'proposed',summary: 'Malformed proposal.',- toolName: 'createMaintenanceProposal',+ toolName: 'createSelfReviewProposal',},],includeProposalLifecycleActions: true,- reviewScope: MaintenanceReviewScope.Nightly,+ reviewScope: Scope.Nightly,sourceId: 'source-1',toolCalls: [{- apiName: 'createMaintenanceProposal',+ apiName: 'createSelfReviewProposal',arguments: JSON.stringify({actions: [],idempotencyKey: 'create-proposal-op-1',@@ -399,7 +390,7 @@ describe('projectMaintenanceToolRuntimeRun', () => {summary: 'Malformed proposal.',}),id: 'call-create-proposal-1',- identifier: 'agent-signal-maintenance',+ identifier: 'agent-signal-self-iteration',type: 'builtin',},],@@ -413,30 +404,30 @@ describe('projectMaintenanceToolRuntimeRun', () => {/*** @example- * projectMaintenanceToolRuntimeRun accepts proposal actions that inherit the proposal operation id.+ * projectRun accepts proposal actions that inherit the proposal operation id.*/it('projects proposal actions that omit per-action idempotency keys', () => {- const projection = projectMaintenanceToolRuntimeRun({+ const projection = projectRun({outcomes: [{receiptId: 'receipt-create-proposal',resourceId: 'brief-proposal-1',status: 'proposed',summary: 'Review managed skill refinement.',- toolName: 'createMaintenanceProposal',+ toolName: 'createSelfReviewProposal',},],includeProposalLifecycleActions: true,- reviewScope: MaintenanceReviewScope.Nightly,+ reviewScope: Scope.Nightly,sourceId: 'source-1',toolCalls: [{- apiName: 'createMaintenanceProposal',+ apiName: 'createSelfReviewProposal',arguments: JSON.stringify({actions: [{actionType: 'refine_skill',- applyMode: MaintenanceApplyMode.ProposalOnly,+ applyMode: ApplyMode.ProposalOnly,baseSnapshot: {agentDocumentId: 'skill-doc-1',contentHash: 'hash-before',@@ -463,7 +454,7 @@ describe('projectMaintenanceToolRuntimeRun', () => {summary: 'Review managed skill refinement.',}),id: 'call-create-proposal-1',- identifier: 'agent-signal-maintenance',+ identifier: 'agent-signal-self-iteration',type: 'builtin',},],@@ -475,7 +466,7 @@ describe('projectMaintenanceToolRuntimeRun', () => {idempotencyKey: 'proposal-op-1:action:1',receiptId: 'receipt-create-proposal',resourceId: 'brief-proposal-1',- status: MaintenanceActionStatus.Proposed,+ status: ActionStatus.Proposed,summary: 'Review managed skill refinement.',},]);@@ -496,22 +487,22 @@ describe('projectMaintenanceToolRuntimeRun', () => {* proposal_only actions are retained as ideas, not approve-time proposal actions.*/it('extracts proposal-only actions as self-review ideas', () => {- const projection = projectMaintenanceToolRuntimeRun({+ const projection = projectRun({outcomes: [{receiptId: 'receipt-create-proposal',resourceId: 'brief-proposal-1',status: 'proposed',- summary: 'Saved maintenance ideas.',- toolName: 'createMaintenanceProposal',+ summary: 'Saved shared ideas.',+ toolName: 'createSelfReviewProposal',},],includeProposalLifecycleActions: true,- reviewScope: MaintenanceReviewScope.Nightly,+ reviewScope: Scope.Nightly,sourceId: 'source-1',toolCalls: [{- apiName: 'createMaintenanceProposal',+ apiName: 'createSelfReviewProposal',arguments: JSON.stringify({actions: [{@@ -519,17 +510,17 @@ describe('projectMaintenanceToolRuntimeRun', () => {evidenceRefs: [{ id: 'topic-1', type: 'topic' }],idempotencyKey: 'idea-1',rationale: 'The skill layout may need a future split.',- risk: MaintenanceRisk.Medium,+ risk: Risk.Medium,target: { skillDocumentId: 'skill-doc-1' },title: 'Consider splitting review skill',},],idempotencyKey: 'proposal-op-1',proposalKey: 'agent-1:proposal_only:agent_document:skill-doc-1',- summary: 'Saved maintenance ideas.',+ summary: 'Saved shared ideas.',}),id: 'call-create-proposal-1',- identifier: 'agent-signal-maintenance',+ identifier: 'agent-signal-self-iteration',type: 'builtin',},],@@ -542,7 +533,7 @@ describe('projectMaintenanceToolRuntimeRun', () => {evidenceRefs: [{ id: 'topic-1', type: 'topic' }],idempotencyKey: 'idea-1',rationale: 'The skill layout may need a future split.',- risk: MaintenanceRisk.Medium,+ risk: Risk.Medium,target: { skillDocumentId: 'skill-doc-1' },title: 'Consider splitting review skill',},@@ -554,27 +545,27 @@ describe('projectMaintenanceToolRuntimeRun', () => {* consolidate_skill proposal actions keep their frozen skill operation payload.*/it('preserves consolidate skill proposal operations for approve-time apply', () => {- const projection = projectMaintenanceToolRuntimeRun({+ const projection = projectRun({outcomes: [{receiptId: 'receipt-create-proposal',resourceId: 'brief-proposal-1',status: 'proposed',summary: 'Review consolidated skill.',- toolName: 'createMaintenanceProposal',+ toolName: 'createSelfReviewProposal',},],includeProposalLifecycleActions: true,- reviewScope: MaintenanceReviewScope.Nightly,+ reviewScope: Scope.Nightly,sourceId: 'source-1',toolCalls: [{- apiName: 'createMaintenanceProposal',+ apiName: 'createSelfReviewProposal',arguments: JSON.stringify({actions: [{actionType: 'consolidate_skill',- applyMode: MaintenanceApplyMode.ProposalOnly,+ applyMode: ApplyMode.ProposalOnly,baseSnapshot: {agentDocumentId: 'skill-doc-1',contentHash: 'hash-canonical',@@ -613,7 +604,7 @@ describe('projectMaintenanceToolRuntimeRun', () => {operation: 'consolidate',},rationale: 'Two review skills overlap.',- risk: MaintenanceRisk.Medium,+ risk: Risk.Medium,target: { skillDocumentId: 'skill-doc-1' },},],@@ -622,7 +613,7 @@ describe('projectMaintenanceToolRuntimeRun', () => {summary: 'Review consolidated skill.',}),id: 'call-create-proposal-1',- identifier: 'agent-signal-maintenance',+ identifier: 'agent-signal-self-iteration',type: 'builtin',},],@@ -646,7 +637,7 @@ describe('projectMaintenanceToolRuntimeRun', () => {},});expect(projection.execution.actions[0]).toMatchObject({- status: MaintenanceActionStatus.Proposed,+ status: ActionStatus.Proposed,});});});diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/types.test.ts b/src/server/services/agentSignal/services/selfIteration/__test__/types.test.tssimilarity index 66%rename from src/server/services/agentSignal/services/maintenance/__tests__/types.test.tsrename to src/server/services/agentSignal/services/selfIteration/__test__/types.test.tsindex a211422f92e..49cde4e4c19 100644--- a/src/server/services/agentSignal/services/maintenance/__tests__/types.test.ts+++ b/src/server/services/agentSignal/services/selfIteration/__test__/types.test.ts@@ -1,18 +1,18 @@import { describe, expect, it } from 'vitest';import {- buildMaintenanceActionIdempotencyKey,+ ActionStatus,+ ApplyMode,+ buildActionIdempotencyKey,buildNightlyReviewSourceId,- buildSelfIterationIntentSourceId,+ buildSelfFeedbackIntentSourceId,buildSelfReflectionSourceId,isActionExecutable,- MaintenanceActionStatus,- MaintenanceApplyMode,- MaintenanceReviewScope,ReviewRunStatus,+ Scope,} from '../types';-describe('maintenance contracts', () => {+describe('shared contracts', () => {/*** @example* buildNightlyReviewSourceId({ userId: 'u', agentId: 'a', localDate: '2026-05-04' })@@ -50,28 +50,28 @@ describe('maintenance contracts', () => {/*** @example- * buildSelfIterationIntentSourceId({ toolCallId: 'call-1' }) includes the tool call id.+ * buildSelfFeedbackIntentSourceId({ toolCallId: 'call-1' }) includes the tool call id.*/- it('builds stable self-iteration intent source ids', () => {+ it('builds stable self-feedback intent source ids', () => {expect(- buildSelfIterationIntentSourceId({+ buildSelfFeedbackIntentSourceId({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');+ ).toBe('self-feedback-intent:user-1:agent-1:topic:topic-1:tool-call-1');});/*** @example- * buildMaintenanceActionIdempotencyKey({ sourceId, actionType, dedupeKey })+ * buildActionIdempotencyKey({ sourceId, actionType, dedupeKey })* returns a stable action-specific idempotency key.*/it('builds action idempotency keys from source and action identity', () => {expect(- buildMaintenanceActionIdempotencyKey({+ buildActionIdempotencyKey({actionType: 'refine_skill',dedupeKey: 'skill:agent-doc-1',sourceId: 'source-1',@@ -84,9 +84,9 @@ describe('maintenance contracts', () => {* 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);+ expect(isActionExecutable(ApplyMode.AutoApply)).toBe(true);+ expect(isActionExecutable(ApplyMode.ProposalOnly)).toBe(false);+ expect(isActionExecutable(ApplyMode.Skip)).toBe(false);});/**@@ -94,10 +94,10 @@ describe('maintenance contracts', () => {* 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(Scope.Nightly).toBe('nightly');+ expect(Scope.SelfReflection).toBe('self_reflection');+ expect(Scope.SelfFeedback).toBe('self_feedback');expect(ReviewRunStatus.PartiallyApplied).toBe('partially_applied');- expect(MaintenanceActionStatus.Proposed).toBe('proposed');+ expect(ActionStatus.Proposed).toBe('proposed');});});diff --git a/src/server/services/agentSignal/services/selfIteration/execute.ts b/src/server/services/agentSignal/services/selfIteration/execute.tsnew file mode 100644index 00000000000..7ea3a1052f1--- /dev/null+++ b/src/server/services/agentSignal/services/selfIteration/execute.ts@@ -0,0 +1,1580 @@+import type { AgentRuntimeContext, AgentState } from '@lobechat/agent-runtime';+import { AgentRuntime, GeneralChatAgent } from '@lobechat/agent-runtime';+import { DEFAULT_MINI_SYSTEM_AGENT_ITEM } from '@lobechat/const';+import type { LobeToolManifest } from '@lobechat/context-engine';+import { generateToolsFromManifest, ToolNameResolver } from '@lobechat/context-engine';+import type { ChatStreamPayload, ModelRuntime } from '@lobechat/model-runtime';+import { consumeStreamUntilDone } from '@lobechat/model-runtime';+import { SpanStatusCode } from '@lobechat/observability-otel/api';+import { tracer } from '@lobechat/observability-otel/modules/agent-signal';+import type { ChatToolPayload, MessageToolCall, ModelUsage } from '@lobechat/types';+import { RequestTrigger } from '@lobechat/types';+import { u } from 'unist-builder';+import { toXml } from 'xast-util-to-xml';+import { x } from 'xastscript';++import type { NightlyReviewContext } from './review/collect';+import type { SelfReviewIdea, SelfReviewProposalBaseSnapshot } from './review/proposal';+import type {+ CloseSelfReviewProposalInput,+ CreateSelfReviewProposalInput,+ CreateSkillIfAbsentInput,+ RefreshSelfReviewProposalInput,+ ReplaceSkillContentCASInput,+ SupersedeSelfReviewProposalInput,+ ToolSet,+ ToolWriteInput,+ ToolWriteResult,+ WriteMemoryInput,+} from './tools/shared';+import type {+ ActionTarget,+ EvidenceRef,+ IterationMode,+ IterationWindow,+ Plan,+ RunResult,+ SelfFeedbackIntent,+} from './types';+import { ReviewRunStatus, Risk, Scope } from './types';++/** Built-in tool identifier used for self-iteration AgentRuntime tool calls. */+export const selfIterationToolIdentifier = 'agent-signal-self-iteration';++/** Read-only self-iteration tools exposed to the tool-first runtime. */+export type ReadToolName =+ | 'getEvidenceDigest'+ | 'getManagedSkill'+ | 'listSelfReviewProposals'+ | 'listManagedSkills'+ | 'readSelfReviewProposal';++/** Write self-iteration tools whose terminal outcomes must be retained by the runtime. */+export type WriteToolName =+ | 'closeSelfReviewProposal'+ | 'createSelfReviewProposal'+ | 'createSkillIfAbsent'+ | 'refreshSelfReviewProposal'+ | 'replaceSkillContentCAS'+ | 'supersedeSelfReviewProposal'+ | 'writeMemory';++/** Artifact-only tools that update runtime ideas or intents without direct resource mutation. */+export type ArtifactToolName =+ | 'recordReflectionIdea'+ | 'recordSelfFeedbackIntent'+ | 'recordSelfReviewIdea';++/** Self-iteration tool names exposed to the model. */+export type RuntimeToolName = ReadToolName | WriteToolName | ArtifactToolName;++/**+ * Context accepted by the self-iteration runtime.+ */+export interface ExecuteSelfIterationContext {+ /** Stable agent id being reviewed. */+ agentId: string;+ /** Agent document evidence serialized into the runtime prompt when available. */+ documentActivity?: unknown;+ /** User feedback evidence serialized into the runtime prompt when available. */+ feedbackActivity?: unknown;+ /** Managed skill summaries serialized into the runtime prompt when available. */+ managedSkills?: unknown;+ /** Existing proposal activity serialized into the runtime prompt when available. */+ proposalActivity?: unknown;+ /** Recent receipt evidence serialized into the runtime prompt when available. */+ receiptActivity?: unknown;+ /** Relevant memory evidence serialized into the runtime prompt when available. */+ relevantMemories?: unknown;+ /** Optional review-window end retained for nightly compatibility. */+ reviewWindowEnd?: string;+ /** Optional review-window start retained for nightly compatibility. */+ reviewWindowStart?: string;+ /** Candidate evidence from immediate self-feedback serialized into the runtime prompt when available. */+ selfFeedbackCandidates?: unknown;+ /** Derived self-review signal evidence serialized into the runtime prompt when available. */+ selfReviewSignals?: unknown;+ /** Tool activity evidence serialized into the runtime prompt when available. */+ toolActivity?: unknown;+ /** Topic activity evidence serialized into the runtime prompt when available. */+ topics?: unknown;+ /** Stable user id owning the reviewed agent. */+ userId: string;+}++/**+ * Input passed to the tool-first self-iteration AgentRuntime loop.+ */+export interface ExecuteSelfIterationInput {+ /** Stable agent id being reviewed. */+ agentId: string;+ /** Bounded nightly review context collected before the run. */+ context: ExecuteSelfIterationContext;+ /** Maximum AgentRuntime steps allowed for the LLM/tool loop. */+ maxSteps: number;+ /**+ * Self-iteration mode for prompt and downstream trace separation.+ *+ * @default 'review'+ */+ mode?: IterationMode;+ /** Model name passed to the injected model runtime. */+ model: string;+ /** Minimal model runtime dependency used to stream chat completions. */+ modelRuntime: Pick<ModelRuntime, 'chat'>;+ /** Stable source id used for tracing and fallback idempotency keys. */+ sourceId: string;+ /** Safe read/write self-iteration tools available to this run. */+ tools: ToolSet;+ /** Stable user id owning the reviewed agent. */+ userId: string;+ /** Evidence window exposed to tools and prompts. Defaults to the review context window. */+ window?: IterationWindow;+}++/**+ * Write result captured from one supported write tool call.+ */+export interface RuntimeWriteOutcome {+ /** Tool result returned by the safe write boundary. */+ result: ToolWriteResult;+ /** Supported write tool that produced this outcome. */+ toolName: WriteToolName;+}++/**+ * Result returned after the self-iteration AgentRuntime loop stops.+ */+export interface ExecuteSelfIterationResult {+ /** Normalized action outcomes for downstream sink-specific projection. */+ actions: RuntimeWriteOutcome[];+ /** Concatenated assistant text streamed across LLM calls. */+ content: string;+ /** Non-actionable self-review ideas captured by the runtime. */+ ideas: SelfReviewIdea[];+ /** Immediate self-feedback intents captured by reflection/intent modes. */+ intents: SelfFeedbackIntent[];+ /** Aggregate runtime status before sink-specific projection. */+ status: ReviewRunStatus;+ /** AgentRuntime steps consumed before stopping. */+ stepCount: number;+ /** Model tool calls resolved against the self-iteration manifest. */+ toolCalls: ChatToolPayload[];+ /** Per-call model usage emitted by streaming callbacks. */+ usage: ModelUsage[];+ /** Terminal write outcomes produced by supported write tools. */+ writeOutcomes: RuntimeWriteOutcome[];+}++interface ToolExecutionResult {+ data: unknown;+ idea?: SelfReviewIdea;+ intent?: SelfFeedbackIntent;+ isWrite: boolean;+ success: boolean;+ toolName?: WriteToolName;+}++type LegacyRuntimeToolName =+ | 'closeSelfReviewProposal'+ | 'createSelfReviewProposal'+ | 'listSelfReviewProposals'+ | 'readSelfReviewProposal'+ | 'refreshSelfReviewProposal'+ | 'supersedeSelfReviewProposal';++const createObjectSchema = (+ properties: Record<string, unknown>,+ required: string[] = [],+): Record<string, unknown> => ({+ additionalProperties: false,+ properties,+ required,+ type: 'object',+});++const stringSchema = { type: 'string' };+const stringArraySchema = { items: stringSchema, type: 'array' };+const freeformArraySchema = { items: {}, type: 'array' };+const freeformObjectSchema = { additionalProperties: true, type: 'object' };+const proposalActionSchema = createObjectSchema(+ {+ actionType: {+ enum: ['create_skill', 'refine_skill', 'consolidate_skill', 'record_idea'],+ type: 'string',+ },+ applyMode: { enum: ['auto_apply', 'review_required', 'skip'], type: 'string' },+ baseSnapshot: freeformObjectSchema,+ confidence: { type: 'number' },+ dedupeKey: stringSchema,+ evidenceRefs: freeformArraySchema,+ idempotencyKey: stringSchema,+ operation: freeformObjectSchema,+ rationale: stringSchema,+ risk: { enum: ['low', 'medium', 'high'], type: 'string' },+ target: freeformObjectSchema,+ },+ ['actionType', 'rationale', 'target'],+);+const proposalActionsSchema = { items: proposalActionSchema, type: 'array' };++const evidenceRefsSchema = freeformArraySchema;+const ideaSchema = createObjectSchema(+ {+ evidenceRefs: evidenceRefsSchema,+ idempotencyKey: stringSchema,+ rationale: stringSchema,+ risk: { enum: ['low', 'medium', 'high'], type: 'string' },+ target: freeformObjectSchema,+ title: stringSchema,+ },+ ['idempotencyKey', 'rationale', 'evidenceRefs'],+);+const intentOperationSchema = freeformObjectSchema;+const intentSchema = createObjectSchema(+ {+ actionType: stringSchema,+ confidence: { type: 'number' },+ downgradeReason: {+ enum: ['approval_required', 'low_confidence', 'unsupported_in_reflection'],+ type: 'string',+ },+ evidenceRefs: evidenceRefsSchema,+ idempotencyKey: stringSchema,+ intentType: { enum: ['memory', 'skill', 'tooling', 'workflow'], type: 'string' },+ operation: intentOperationSchema,+ rationale: stringSchema,+ risk: { enum: ['low', 'medium', 'high'], type: 'string' },+ target: freeformObjectSchema,+ title: stringSchema,+ urgency: { enum: ['immediate', 'soon', 'later'], type: 'string' },+ },+ ['idempotencyKey', 'intentType', 'confidence', 'urgency', 'rationale', 'evidenceRefs'],+);++/**+ * Tool manifest used to expose current safe read/write tools to the model.+ */+const createToolManifest = (mode: IterationMode): LobeToolManifest => {+ const resourceTools = [+ {+ description: 'List managed skills visible in the reviewed agent scope.',+ name: 'listManagedSkills',+ parameters: createObjectSchema({}),+ },+ {+ description: 'Read one managed skill by skill document id in the reviewed agent scope.',+ name: 'getManagedSkill',+ parameters: createObjectSchema({ skillDocumentId: stringSchema }, ['skillDocumentId']),+ },+ {+ description:+ 'Read bounded evidence details for cited topic, message, tool_call, or agent_document ids in the nightly review window. Use this for evidenceRefs; do not pass evidence ids to proposal tools.',+ name: 'getEvidenceDigest',+ parameters: createObjectSchema({+ evidenceIds: stringArraySchema,+ reviewWindowEnd: stringSchema,+ reviewWindowStart: stringSchema,+ }),+ },+ {+ description:+ 'Write one durable user memory when evidence explicitly states a stable normal-sensitivity user preference. Prefer this over skill tools for summary/style/preferences.',+ name: 'writeMemory',+ parameters: createObjectSchema(+ {+ content: stringSchema,+ evidenceRefs: freeformArraySchema,+ idempotencyKey: stringSchema,+ proposalKey: stringSchema,+ summary: stringSchema,+ },+ ['idempotencyKey', 'content', 'evidenceRefs'],+ ),+ },+ {+ description: 'Create one managed skill when no existing skill is selected.',+ name: 'createSkillIfAbsent',+ parameters: createObjectSchema(+ {+ bodyMarkdown: stringSchema,+ description: stringSchema,+ idempotencyKey: stringSchema,+ name: stringSchema,+ proposalKey: stringSchema,+ summary: stringSchema,+ title: stringSchema,+ },+ ['idempotencyKey', 'name', 'bodyMarkdown'],+ ),+ },+ {+ description:+ 'Replace one existing managed skill after compare-and-swap preflight. Provide baseSnapshot when available; the server completes it from skillDocumentId when omitted.',+ name: 'replaceSkillContentCAS',+ parameters: createObjectSchema(+ {+ baseSnapshot: freeformObjectSchema,+ bodyMarkdown: stringSchema,+ description: stringSchema,+ idempotencyKey: stringSchema,+ proposalKey: stringSchema,+ skillDocumentId: stringSchema,+ summary: stringSchema,+ },+ ['idempotencyKey', 'skillDocumentId', 'bodyMarkdown'],+ ),+ },+ ];++ const reviewTools = [+ {+ description: 'List active and historical self-review proposals in the reviewed agent scope.',+ name: 'listSelfReviewProposals',+ parameters: createObjectSchema({}),+ },+ {+ description:+ 'Read one self-review proposal by proposal id or proposalKey from proposalActivity.active or listSelfReviewProposals. Never use topic, message, tool_call, or document evidence ids here.',+ name: 'readSelfReviewProposal',+ parameters: createObjectSchema({+ proposalId: stringSchema,+ proposalKey: stringSchema,+ }),+ },+ {+ description: 'Create one user-visible self-review proposal for later approval.',+ name: 'createSelfReviewProposal',+ parameters: createObjectSchema(+ {+ actions: proposalActionsSchema,+ idempotencyKey: stringSchema,+ metadata: freeformObjectSchema,+ proposalKey: stringSchema,+ summary: stringSchema,+ },+ ['idempotencyKey', 'proposalKey', 'summary', 'actions'],+ ),+ },+ {+ description: 'Refresh an existing self-review proposal after rechecking evidence.',+ name: 'refreshSelfReviewProposal',+ parameters: createObjectSchema(+ {+ idempotencyKey: stringSchema,+ proposalId: stringSchema,+ proposalKey: stringSchema,+ summary: stringSchema,+ },+ ['idempotencyKey', 'proposalId'],+ ),+ },+ {+ description: 'Supersede an existing self-review proposal with a replacement proposal key.',+ name: 'supersedeSelfReviewProposal',+ parameters: createObjectSchema(+ {+ idempotencyKey: stringSchema,+ proposalId: stringSchema,+ proposalKey: stringSchema,+ summary: stringSchema,+ supersededBy: stringSchema,+ },+ ['idempotencyKey', 'proposalId', 'supersededBy'],+ ),+ },+ {+ description: 'Close an existing self-review proposal with an optional lifecycle reason.',+ name: 'closeSelfReviewProposal',+ parameters: createObjectSchema(+ {+ idempotencyKey: stringSchema,+ proposalId: stringSchema,+ proposalKey: stringSchema,+ reason: stringSchema,+ summary: stringSchema,+ },+ ['idempotencyKey', 'proposalId'],+ ),+ },+ {+ description:+ 'Record one non-actionable self-review idea or question as a Daily Brief artifact without creating an approval proposal.',+ name: 'recordSelfReviewIdea',+ parameters: ideaSchema,+ },+ ];++ const reflectionTools = [+ {+ description:+ 'Record one immediate reflection idea into receipt metadata without creating a Daily Brief proposal.',+ name: 'recordReflectionIdea',+ parameters: ideaSchema,+ },+ {+ description:+ 'Record one approval-gated, structural, unsupported, or low-confidence self-feedback intent into receipt metadata for later self-review.',+ name: 'recordSelfFeedbackIntent',+ parameters: intentSchema,+ },+ ];++ return {+ api: [...resourceTools, ...(mode === 'review' ? reviewTools : reflectionTools)],+ identifier: selfIterationToolIdentifier,+ meta: {+ description: 'Read evidence and apply safe resource operations.',+ title: 'Agent Signal Self-Iteration',+ },+ systemRole:+ mode === 'review'+ ? 'Use resource read tools before writes when evidence is incomplete. Use getEvidenceDigest for topic/message/tool_call/agent_document evidenceRefs. Use readSelfReviewProposal only with proposal keys from proposalActivity.active or listSelfReviewProposals, never with evidence ids. Treat write tool results as the source of truth.'+ : 'Use resource read tools before writes when evidence is incomplete. Direct-apply only safe memory or bounded skill updates. Record approval-gated or unsupported reflection output with recordSelfFeedbackIntent, and record non-actionable thoughts with recordReflectionIdea.',+ type: 'builtin',+ };+};++export const selfIterationToolManifest = createToolManifest('review');++const SELF_ITERATION_SYSTEM_ROLE = [+ 'You are the Agent Signal self-iteration agent.',+ 'Inspect the bounded nightly review context and use the provided self-iteration tools to read evidence or apply safe write operations.',+ 'Evidence ids and proposal keys are different namespaces: read topic/message/tool_call/agent_document evidence with getEvidenceDigest; read proposals with readSelfReviewProposal only when using proposalActivity.active[].proposalKey or keys returned from listSelfReviewProposals.',+ 'Never claim that a write happened unless a write tool result confirms it.',+ 'Use writeMemory for explicit durable user preferences such as response style, summary structure, or verification-reporting preferences. Do not turn those preference memories into skills or proposals.',+ 'Use createSkillIfAbsent only when evidence describes a reusable workflow and you can provide a non-empty skill name and full bodyMarkdown.',+ 'When review evidence supports an approval-gated change, call createSelfReviewProposal in this run; do not offer to draft it later.',+ 'For createSelfReviewProposal actions, use actionType exactly create_skill, refine_skill, consolidate_skill, or record_idea. For refine_skill include target.skillDocumentId and operation { domain: "skill", operation: "refine", input: { skillDocumentId, bodyMarkdown } }. For consolidate_skill include operation { domain: "skill", operation: "consolidate", input: { canonicalSkillDocumentId, sourceSkillIds, bodyMarkdown } }. Prefer recordSelfReviewIdea instead of proposal actions when the output is only a thought or question.',+ 'Stop after the useful self-iteration work is complete and summarize the confirmed outcome.',+].join('\n');++const TOOL_NAME_SEPARATOR = '____';+const SELF_ITERATION_TOOL_ERROR_MESSAGE = 'Self-iteration tool call failed.';+const FORCE_FINISH_EXTRA_STEPS = 4;++const getIterationMode = (input: ExecuteSelfIterationInput): IterationMode =>+ input.mode ?? 'review';++const getIterationWindow = (input: ExecuteSelfIterationInput): IterationWindow => ({+ end: input.window?.end ?? input.context.reviewWindowEnd ?? new Date(0).toISOString(),+ localDate: input.window?.localDate,+ start: input.window?.start ?? input.context.reviewWindowStart ?? new Date(0).toISOString(),+ timezone: input.window?.timezone,+});++const createNightlyReviewPromptXml = (+ input: ExecuteSelfIterationInput,+ window: IterationWindow,+) => {+ return toXml(+ u('root', [+ x(+ 'self_iteration_review',+ {+ agent_id: input.agentId,+ review_window_end: window.end,+ review_window_start: window.start,+ source_id: input.sourceId,+ user_id: input.userId,+ },+ x(+ 'review_objective',+ 'Inspect this nightly review context and create a self-review proposal when the evidence supports an approval-gated change. Do not finish with only text when a proposal is required.',+ ),+ x(+ 'review_policy_markdown',+ // Keep this as a rule table, not a precomputed proposal payload. The model still has+ // to decide and call the write tool, so local E2E proves the self-review path instead+ // of only proving that a hard-coded proposal candidate was copied into the tool call.+ [+ 'Use these deterministic self-review signal rules before deciding to finish without tools.',+ '',+ '| Signal kind | Required decision | Tool call | Notes |',+ '| --- | --- | --- | --- |',+ '| `skill_document_with_tool_failure` | Approval-gated skill refinement proposal | `createSelfReviewProposal` with one `refine_skill` action | Use the matching `managedSkills[].documentId` or `documentActivity.skillBucket[].agentDocumentId` as `target.skillDocumentId`; include `operation: { domain: "skill", operation: "refine", input: { skillDocumentId, bodyMarkdown } }`; cite topic/message/agent_document evidence refs. |',+ '| `repeated_tool_failure` involving `replaceSkillContentCAS` | Do not retry the write directly during nightly review | `createSelfReviewProposal` when the failed args contain a corrected skill body or a clear skill target | Prefer the failed tool args as the proposed body; call `getEvidenceDigest` first if the body or target is not visible in context. |',+ '| `skill_documents_maybe_overlap` | Consolidation candidate | `createSelfReviewProposal` with `consolidate_skill` only when there is a canonical skill and explicit source skills | Otherwise record no proposal for this signal alone. |',+ '',+ 'If a rule says `createSelfReviewProposal`, do not stop with only explanatory text. If required fields are missing, use read tools once to gather them; only skip when evidence remains insufficient after reading.',+ ].join('\n'),+ ),+ x('review_window', `Review window: ${window.start} to ${window.end}`),+ x('nightly_review_context_json', JSON.stringify(input.context)),+ ),+ ]),+ );+};++const createRuntimePrompt = (input: ExecuteSelfIterationInput) => {+ const window = getIterationWindow(input);+ const mode = getIterationMode(input);++ if (mode === 'review') {+ // TODO:+ // Rework this compatibility branch with the user before committing. The review prompt should+ // eventually share the self-iteration wording, but the current seeded local E2E proved that a+ // naive wording change can drop the Daily Brief proposal path.+ // NOTICE:+ // Keep the original nightly review prompt labels for the review mode.+ // Root cause summary: changing this to the generic self-iteration wording made the local E2E+ // review source complete without producing the expected Daily Brief proposal.+ // Source/context: `devtools/agent-signal/self-iteration-e2e/run-local-e2e.ts` requires one+ // review brief and one approval-gated proposal for the seeded nightly review data.+ // Removal condition: nightly self-review prompt/eval coverage proves the generic prompt still+ // produces equivalent proposal behavior.+ return createNightlyReviewPromptXml(input, window);+ }++ return [+ `Agent id: ${input.agentId}`,+ `User id: ${input.userId}`,+ `Source id: ${input.sourceId}`,+ `Mode: ${mode}`,+ `Evidence window: ${window.start} to ${window.end}`,+ 'Self-iteration context JSON:',+ JSON.stringify(input.context),+ ].join('\n');+};++const toNullableString = (value: unknown) =>+ typeof value === 'string' && value.trim().length > 0 ? value : undefined;++const toBoolean = (value: unknown) => (typeof value === 'boolean' ? value : undefined);++const toRecord = (value: unknown): Record<string, unknown> =>+ value && typeof value === 'object' && !Array.isArray(value)+ ? (value as Record<string, unknown>)+ : {};++const toUnknownArray = (value: unknown): unknown[] => (Array.isArray(value) ? value : []);++const toStringArray = (value: unknown) =>+ Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : [];++const toEvidenceRefs = (value: unknown): EvidenceRef[] =>+ Array.isArray(value)+ ? value.flatMap((item) => {+ const record = toRecord(item);+ const id = toNullableString(record.id);+ const type = toNullableString(record.type);++ if (+ !id ||+ !(+ type === 'topic' ||+ type === 'message' ||+ type === 'operation' ||+ type === 'source' ||+ type === 'receipt' ||+ type === 'tool_call' ||+ type === 'task' ||+ type === 'agent_document' ||+ type === 'memory'+ )+ ) {+ return [];+ }++ return [+ {+ id,+ ...(toNullableString(record.summary)+ ? { summary: toNullableString(record.summary) }+ : {}),+ type,+ },+ ];+ })+ : [];++const toRisk = (value: unknown): Risk => {+ if (value === Risk.High || value === 'high') return Risk.High;+ if (value === Risk.Low || value === 'low') return Risk.Low;++ return Risk.Medium;+};++const toTarget = (value: unknown): ActionTarget | undefined => {+ const record = toRecord(value);+ const target: ActionTarget = {+ memoryId: toNullableString(record.memoryId),+ skillDocumentId: toNullableString(record.skillDocumentId),+ skillName: toNullableString(record.skillName),+ targetReadonly: toBoolean(record.targetReadonly) ?? toBoolean(record.readonly),+ taskIds: toStringArray(record.taskIds),+ topicIds: toStringArray(record.topicIds),+ };++ return Object.values(target).some((item) => (Array.isArray(item) ? item.length > 0 : item))+ ? target+ : undefined;+};++const normalizeProposalActions = (value: unknown) =>+ toUnknownArray(value).map((item) => {+ const record = toRecord(item);++ return {+ ...record,+ actionType: record.actionType === 'record_idea' ? 'proposal_only' : record.actionType,+ applyMode: record.applyMode === 'review_required' ? 'proposal_only' : record.applyMode,+ };+ });++const toReviewIdea = (args: Record<string, unknown>): SelfReviewIdea => ({+ evidenceRefs: toEvidenceRefs(args.evidenceRefs),+ idempotencyKey: toNullableString(args.idempotencyKey) ?? 'shared-idea',+ rationale: toNullableString(args.rationale) ?? toNullableString(args.summary) ?? 'Recorded idea.',+ risk: toRisk(args.risk),+ target: toTarget(args.target),+ title: toNullableString(args.title),+});++const toIntentType = (value: unknown): SelfFeedbackIntent['intentType'] => {+ if (value === 'memory' || value === 'skill' || value === 'tooling' || value === 'workflow') {+ return value;+ }++ return 'workflow';+};++const toUrgency = (value: unknown): SelfFeedbackIntent['urgency'] => {+ if (value === 'immediate' || value === 'soon' || value === 'later') return value;++ return 'later';+};++const toDowngradeReason = (value: unknown): SelfFeedbackIntent['downgradeReason'] => {+ if (+ value === 'approval_required' ||+ value === 'low_confidence' ||+ value === 'unsupported_in_reflection'+ ) {+ return value;+ }+};++const toSelfFeedbackIntent = (args: Record<string, unknown>): SelfFeedbackIntent => ({+ ...toReviewIdea(args),+ actionType: toNullableString(args.actionType),+ confidence: typeof args.confidence === 'number' ? args.confidence : 0.5,+ downgradeReason: toDowngradeReason(args.downgradeReason),+ intentType: toIntentType(args.intentType),+ mode: 'reflection',+ operation: toRecord(args.operation) as SelfFeedbackIntent['operation'],+ urgency: toUrgency(args.urgency),+});++/**+ * Normalizes model-produced tool arguments.+ *+ * Before:+ * - `"{\"name\":\"skill\"}"`+ * - `"not json"`+ *+ * After:+ * - `{ name: "skill" }`+ * - `{}`+ */+const parseToolArguments = (value: string | undefined): Record<string, unknown> => {+ if (!value) return {};++ try {+ const parsed = JSON.parse(value) as unknown;++ return toRecord(parsed);+ } catch {+ return {};+ }+};++const getErrorMessage = (error: unknown) =>+ error instanceof Error ? error.message : String(error);++const getApiNameFromRawToolName = (name: string) => {+ const [identifier, apiName] = name.split(TOOL_NAME_SEPARATOR);++ return identifier === selfIterationToolIdentifier && apiName ? apiName : name;+};++const normalizeToolName = (name: string): RuntimeToolName | LegacyRuntimeToolName | string => {+ if (name === 'listSelfReviewProposals') return 'listSelfReviewProposals';+ if (name === 'readSelfReviewProposal') return 'readSelfReviewProposal';+ if (name === 'createSelfReviewProposal') return 'createSelfReviewProposal';+ if (name === 'refreshSelfReviewProposal') return 'refreshSelfReviewProposal';+ if (name === 'supersedeSelfReviewProposal') return 'supersedeSelfReviewProposal';+ if (name === 'closeSelfReviewProposal') return 'closeSelfReviewProposal';++ return name;+};++const resolveToolCalls = ({+ manifestMap,+ offeredToolNames,+ rawToolCalls,+ toolNameResolver,+}: {+ manifestMap: Record<string, LobeToolManifest>;+ offeredToolNames: string[];+ rawToolCalls: MessageToolCall[];+ toolNameResolver: ToolNameResolver;+}): ChatToolPayload[] => {+ const resolvedToolCalls = toolNameResolver.resolve(rawToolCalls, manifestMap, offeredToolNames);+ const resolvedIds = new Set(resolvedToolCalls.map((toolCall) => toolCall.id));+ const unresolvedToolCalls = rawToolCalls+ .filter((toolCall) => !resolvedIds.has(toolCall.id))+ .map(+ (toolCall): ChatToolPayload => ({+ apiName: getApiNameFromRawToolName(toolCall.function.name),+ arguments: toolCall.function.arguments,+ id: toolCall.id,+ identifier: selfIterationToolIdentifier,+ thoughtSignature: toolCall.thoughtSignature,+ type: 'builtin',+ }),+ );++ return [...resolvedToolCalls, ...unresolvedToolCalls];+};++const createToolError = (message: string): ToolExecutionResult => ({+ data: { error: message },+ isWrite: false,+ success: false,+});++const withUser = <TInput extends ToolWriteInput>(+ toolName: WriteToolName,+ args: Record<string, unknown>,+ input: ExecuteSelfIterationInput,+ toolCallId: string,+ fields: Omit<TInput, keyof ToolWriteInput>,+): TInput =>+ ({+ ...fields,+ idempotencyKey:+ toNullableString(args.idempotencyKey) ?? `${input.sourceId}:${toolName}:${toolCallId}`,+ proposalKey: toNullableString(args.proposalKey),+ summary: toNullableString(args.summary),+ userId: input.userId,+ }) as TInput;++const toBaseSnapshot = (value: unknown): SelfReviewProposalBaseSnapshot => {+ const record = toRecord(value);++ return {+ absent: toBoolean(record.absent),+ agentDocumentId: toNullableString(record.agentDocumentId),+ contentHash: toNullableString(record.contentHash),+ documentId: toNullableString(record.documentId),+ documentUpdatedAt: toNullableString(record.documentUpdatedAt),+ managed: toBoolean(record.managed),+ skillName: toNullableString(record.skillName),+ targetTitle: toNullableString(record.targetTitle),+ targetType: record.targetType === 'skill' ? 'skill' : undefined,+ writable: toBoolean(record.writable),+ };+};++const executeWriteTool = async (+ toolName: WriteToolName,+ operation: () => Promise<ToolWriteResult>,+): Promise<ToolExecutionResult> => ({+ data: await operation(),+ isWrite: true,+ success: true,+ toolName,+});++const executeRuntimeTool = async (+ toolCall: ChatToolPayload,+ input: ExecuteSelfIterationInput,+): Promise<ToolExecutionResult> => {+ const args = parseToolArguments(toolCall.arguments);+ const apiName = normalizeToolName(toolCall.apiName);++ if (apiName === 'listManagedSkills') {+ return {+ data: await input.tools.listManagedSkills({ agentId: input.agentId, userId: input.userId }),+ isWrite: false,+ success: true,+ };+ }++ if (apiName === 'getManagedSkill') {+ const skillDocumentId = toNullableString(args.skillDocumentId);+ if (!skillDocumentId) return createToolError('skillDocumentId is required');++ return {+ data: await input.tools.getManagedSkill({+ agentId: input.agentId,+ skillDocumentId,+ userId: input.userId,+ }),+ isWrite: false,+ success: true,+ };+ }++ if (apiName === 'getEvidenceDigest') {+ const window = getIterationWindow(input);++ return {+ data: await input.tools.getEvidenceDigest({+ agentId: input.agentId,+ evidenceIds: toStringArray(args.evidenceIds),+ reviewWindowEnd: toNullableString(args.reviewWindowEnd) ?? window.end,+ reviewWindowStart: toNullableString(args.reviewWindowStart) ?? window.start,+ userId: input.userId,+ }),+ isWrite: false,+ success: true,+ };+ }++ if (apiName === 'listSelfReviewProposals') {+ return {+ data: await input.tools.listSelfReviewProposals({+ agentId: input.agentId,+ userId: input.userId,+ }),+ isWrite: false,+ success: true,+ };+ }++ if (apiName === 'readSelfReviewProposal') {+ return {+ data: await input.tools.readSelfReviewProposal({+ proposalId: toNullableString(args.proposalId),+ proposalKey: toNullableString(args.proposalKey),+ userId: input.userId,+ }),+ isWrite: false,+ success: true,+ };+ }++ if (apiName === 'recordSelfReviewIdea' || apiName === 'recordReflectionIdea') {+ const idea = toReviewIdea(args);++ return {+ data: {+ idempotencyKey: idea.idempotencyKey,+ status: 'applied',+ summary: idea.title ?? idea.rationale,+ },+ idea,+ isWrite: false,+ success: true,+ };+ }++ if (apiName === 'recordSelfFeedbackIntent') {+ const intent = toSelfFeedbackIntent(args);++ return {+ data: {+ idempotencyKey: intent.idempotencyKey,+ status: 'applied',+ summary: intent.title ?? intent.rationale,+ },+ intent,+ isWrite: false,+ success: true,+ };+ }++ if (apiName === 'createSelfReviewProposal') {+ return executeWriteTool('createSelfReviewProposal', () =>+ input.tools.createSelfReviewProposal(+ withUser<CreateSelfReviewProposalInput>(+ 'createSelfReviewProposal',+ args,+ input,+ toolCall.id,+ {+ actions: normalizeProposalActions(args.actions),+ metadata: toRecord(args.metadata),+ },+ ),+ ),+ );+ }++ if (apiName === 'refreshSelfReviewProposal') {+ const proposalId = toNullableString(args.proposalId);+ if (!proposalId) return createToolError('proposalId is required');++ return executeWriteTool('refreshSelfReviewProposal', () =>+ input.tools.refreshSelfReviewProposal(+ withUser<RefreshSelfReviewProposalInput>(+ 'refreshSelfReviewProposal',+ args,+ input,+ toolCall.id,+ {+ proposalId,+ },+ ),+ ),+ );+ }++ if (apiName === 'supersedeSelfReviewProposal') {+ const proposalId = toNullableString(args.proposalId);+ const supersededBy = toNullableString(args.supersededBy);+ if (!proposalId) return createToolError('proposalId is required');+ if (!supersededBy) return createToolError('supersededBy is required');++ return executeWriteTool('supersedeSelfReviewProposal', () =>+ input.tools.supersedeSelfReviewProposal(+ withUser<SupersedeSelfReviewProposalInput>(+ 'supersedeSelfReviewProposal',+ args,+ input,+ toolCall.id,+ {+ proposalId,+ supersededBy,+ },+ ),+ ),+ );+ }++ if (apiName === 'closeSelfReviewProposal') {+ const proposalId = toNullableString(args.proposalId);+ if (!proposalId) return createToolError('proposalId is required');++ return executeWriteTool('closeSelfReviewProposal', () =>+ input.tools.closeSelfReviewProposal(+ withUser<CloseSelfReviewProposalInput>(+ 'closeSelfReviewProposal',+ args,+ input,+ toolCall.id,+ {+ proposalId,+ reason: toNullableString(args.reason),+ },+ ),+ ),+ );+ }++ if (apiName === 'writeMemory') {+ const content = toNullableString(args.content);+ if (!content) return createToolError('content is required');++ const evidenceRefs = toEvidenceRefs(args.evidenceRefs);+ if (evidenceRefs.length === 0) return createToolError('evidenceRefs are required');++ return executeWriteTool('writeMemory', () =>+ input.tools.writeMemory(+ withUser<WriteMemoryInput>('writeMemory', args, input, toolCall.id, {+ content,+ evidenceRefs,+ }),+ ),+ );+ }++ if (apiName === 'createSkillIfAbsent') {+ return executeWriteTool('createSkillIfAbsent', () =>+ input.tools.createSkillIfAbsent(+ withUser<CreateSkillIfAbsentInput>('createSkillIfAbsent', args, input, toolCall.id, {+ bodyMarkdown: toNullableString(args.bodyMarkdown) ?? '',+ description: toNullableString(args.description),+ name: toNullableString(args.name) ?? '',+ title: toNullableString(args.title),+ }),+ ),+ );+ }++ if (apiName === 'replaceSkillContentCAS') {+ const skillDocumentId = toNullableString(args.skillDocumentId);+ if (!skillDocumentId) return createToolError('skillDocumentId is required');++ return executeWriteTool('replaceSkillContentCAS', () =>+ input.tools.replaceSkillContentCAS(+ withUser<ReplaceSkillContentCASInput>('replaceSkillContentCAS', args, input, toolCall.id, {+ baseSnapshot: toBaseSnapshot(args.baseSnapshot),+ bodyMarkdown: toNullableString(args.bodyMarkdown) ?? '',+ description: toNullableString(args.description),+ skillDocumentId,+ }),+ ),+ );+ }++ return createToolError(`Unsupported self-iteration tool: ${apiName}`);+};++const createInitialState = ({+ input,+ manifestMap,+ runtimeTools,+}: {+ input: ExecuteSelfIterationInput;+ manifestMap: Record<string, LobeToolManifest>;+ runtimeTools: ReturnType<typeof generateToolsFromManifest>;+}): AgentState => {+ const createdAt = new Date().toISOString();+ const operationId = `agent-signal-self-iteration:${input.sourceId}`;+ const messages: ChatStreamPayload['messages'] = [+ { content: SELF_ITERATION_SYSTEM_ROLE, role: 'system' },+ { content: createRuntimePrompt(input), role: 'user' },+ ];++ return {+ cost: {+ calculatedAt: createdAt,+ currency: 'USD',+ llm: { byModel: [], currency: 'USD', total: 0 },+ tools: { byTool: [], currency: 'USD', total: 0 },+ total: 0,+ },+ createdAt,+ lastModified: createdAt,+ maxSteps: Math.max(1, input.maxSteps),+ messages,+ metadata: {+ agentId: input.agentId,+ sourceId: input.sourceId,+ trigger: RequestTrigger.AgentSignal,+ userId: input.userId,+ },+ modelRuntimeConfig: {+ model: input.model,+ provider: DEFAULT_MINI_SYSTEM_AGENT_ITEM.provider,+ },+ operationId,+ operationToolSet: {+ enabledToolIds: [selfIterationToolIdentifier],+ manifestMap,+ sourceMap: { [selfIterationToolIdentifier]: 'builtin' },+ tools: runtimeTools,+ },+ status: 'idle',+ stepCount: 0,+ toolManifestMap: manifestMap,+ toolSourceMap: { [selfIterationToolIdentifier]: 'builtin' },+ tools: runtimeTools,+ usage: {+ humanInteraction: {+ approvalRequests: 0,+ promptRequests: 0,+ selectRequests: 0,+ totalWaitingTimeMs: 0,+ },+ llm: {+ apiCalls: 0,+ processingTimeMs: 0,+ tokens: { input: 0, output: 0, total: 0 },+ },+ tools: {+ byTool: [],+ totalCalls: 0,+ totalTimeMs: 0,+ },+ },+ userInterventionConfig: { approvalMode: 'headless' },+ };+};++/**+ * Runs the tool-first self-iteration agent with a bounded AgentRuntime LLM/tool loop.+ *+ * Triggering workflow:+ *+ * createAgentRunner+ * -> future server runtime backend+ * -> `agent_signal.self_iteration_agent.run`+ * -> {@link executeSelfIteration}+ *+ * Upstream:+ * - {@link createInitialState}+ *+ * Downstream:+ * - {@link executeRuntimeTool}+ *+ * Use when:+ * - Nightly self-review needs real LLM -> tool -> LLM behavior+ * - The caller already has scoped safe self-iteration tools and a model runtime+ *+ * Expects:+ * - Tools enforce their own idempotency, preflight, and receipt contracts+ * - `maxSteps` is a positive finite loop budget+ *+ * Returns:+ * - Final streamed assistant content, step count, model usage, tool calls, and write outcomes+ */+export const executeSelfIteration = async (+ input: ExecuteSelfIterationInput,+): Promise<ExecuteSelfIterationResult> =>+ tracer.startActiveSpan(+ 'agent_signal.self_iteration_agent.run',+ {+ attributes: {+ 'agent.signal.agent_id': input.agentId,+ 'agent.signal.self_iteration.mode': getIterationMode(input),+ 'agent.signal.self_iteration_agent.max_steps': input.maxSteps,+ 'agent.signal.source_id': input.sourceId,+ 'agent.signal.user_id': input.userId,+ },+ },+ async (runSpan) => {+ const maxSteps = Math.max(1, input.maxSteps);+ const toolNameResolver = new ToolNameResolver();+ const manifest = createToolManifest(getIterationMode(input));+ const manifestMap = {+ [selfIterationToolIdentifier]: manifest,+ };+ const runtimeTools = generateToolsFromManifest(manifest);+ const offeredToolNames = runtimeTools.map((tool) => tool.function.name);+ const contentParts: string[] = [];+ const ideas: SelfReviewIdea[] = [];+ const intents: SelfFeedbackIntent[] = [];+ const toolCalls: ChatToolPayload[] = [];+ const usage: ModelUsage[] = [];+ const writeOutcomes: RuntimeWriteOutcome[] = [];+ const runtime = new AgentRuntime(+ new GeneralChatAgent({+ compressionConfig: { enabled: false },+ modelRuntimeConfig: {+ model: input.model,+ provider: DEFAULT_MINI_SYSTEM_AGENT_ITEM.provider,+ },+ operationId: `agent-signal-self-iteration:${input.sourceId}`,+ userId: input.userId,+ }),+ {+ executors: {+ call_llm: async (instruction, state) => {+ const payload = (+ instruction as { payload: { messages: ChatStreamPayload['messages'] } }+ ).payload;+ let content = '';+ let modelUsage: ModelUsage | undefined;+ let rawToolCalls: MessageToolCall[] = [];++ const response = await input.modelRuntime.chat(+ {+ messages: payload.messages,+ model: input.model,+ stream: true,+ tools: state.forceFinish ? [] : runtimeTools,+ },+ {+ callback: {+ onCompletion: (data) => {+ modelUsage = data.usage;+ },+ onText: (text) => {+ content += text;+ },+ onToolsCalling: ({ toolsCalling }) => {+ rawToolCalls = toolsCalling;+ },+ },+ metadata: { trigger: RequestTrigger.AgentSignal },+ },+ );+ await consumeStreamUntilDone(response);++ if (content) contentParts.push(content);+ if (modelUsage) usage.push(modelUsage);++ const assistantMessageId = `shared-assistant-${state.stepCount}`;+ const resolvedToolCalls = resolveToolCalls({+ manifestMap,+ offeredToolNames,+ rawToolCalls,+ toolNameResolver,+ });+ toolCalls.push(...resolvedToolCalls);++ const newState = structuredClone(state);+ newState.messages.push({+ content,+ id: assistantMessageId,+ role: 'assistant',+ ...(rawToolCalls.length > 0 ? { tool_calls: rawToolCalls } : {}),+ });++ return {+ events: [+ {+ result: { content, tool_calls: rawToolCalls, usage: modelUsage },+ type: 'llm_result',+ },+ ],+ newState,+ nextContext: {+ payload: {+ hasToolsCalling: resolvedToolCalls.length > 0,+ parentMessageId: assistantMessageId,+ result: { content, tool_calls: rawToolCalls },+ toolsCalling: resolvedToolCalls,+ },+ phase: 'llm_result',+ session: {+ messageCount: newState.messages.length,+ sessionId: newState.operationId,+ status: newState.status,+ stepCount: newState.stepCount,+ },+ stepUsage: modelUsage,+ } satisfies AgentRuntimeContext,+ };+ },+ call_tool: async (instruction, state) => {+ const payload = (+ instruction as {+ payload: {+ parentMessageId: string;+ toolCalling: ChatToolPayload;+ };+ }+ ).payload;+ const startedAt = Date.now();+ let execution: ToolExecutionResult;++ try {+ execution = await executeRuntimeTool(payload.toolCalling, input);+ } catch {+ execution = {+ data: { error: SELF_ITERATION_TOOL_ERROR_MESSAGE },+ isWrite: false,+ success: false,+ };+ }++ if (execution.isWrite && execution.toolName && execution.success) {+ writeOutcomes.push({+ result: execution.data as ToolWriteResult,+ toolName: execution.toolName,+ });+ }+ if (execution.idea && execution.success) ideas.push(execution.idea);+ if (execution.intent && execution.success) intents.push(execution.intent);++ const content = JSON.stringify(execution.data);+ const newState = structuredClone(state);+ newState.messages.push({+ content,+ role: 'tool',+ tool_call_id: payload.toolCalling.id,+ });++ return {+ events: [+ {+ id: payload.toolCalling.id,+ result: { content, success: execution.success },+ type: 'tool_result',+ },+ ],+ newState,+ nextContext: {+ payload: {+ data: execution.data,+ executionTime: Date.now() - startedAt,+ isSuccess: execution.success,+ parentMessageId: payload.parentMessageId,+ toolCall: payload.toolCalling,+ toolCallId: payload.toolCalling.id,+ },+ phase: 'tool_result',+ session: {+ messageCount: newState.messages.length,+ sessionId: newState.operationId,+ status: newState.status,+ stepCount: newState.stepCount,+ },+ } satisfies AgentRuntimeContext,+ };+ },+ },+ },+ );+ let state = createInitialState({ input, manifestMap, runtimeTools });+ let context: AgentRuntimeContext = {+ payload: {+ model: input.model,+ provider: DEFAULT_MINI_SYSTEM_AGENT_ITEM.provider,+ tools: runtimeTools,+ },+ phase: 'user_input',+ session: {+ messageCount: state.messages.length,+ sessionId: state.operationId,+ status: state.status,+ stepCount: state.stepCount,+ },+ };++ try {+ // NOTICE:+ // The public maxSteps policy lives in AgentRuntime via state.maxSteps.+ // The outer loop is only a hard safety cap so force-finish and the final+ // tool-result continuation can run after AgentRuntime crosses maxSteps.+ // Source/context: packages/agent-runtime/src/core/runtime.ts forceFinish handling.+ // Removal condition: AgentRuntime exposes a bounded run-until-done API.+ const hardSafetyStepCap = maxSteps + FORCE_FINISH_EXTRA_STEPS;++ for (let stepIndex = 0; stepIndex < hardSafetyStepCap; stepIndex += 1) {+ if (+ state.status === 'done' ||+ state.status === 'error' ||+ state.status === 'interrupted'+ ) {+ break;+ }++ const result = await tracer.startActiveSpan(+ 'agent_signal.self_iteration_agent.step',+ {+ attributes: {+ 'agent.signal.agent_id': input.agentId,+ 'agent.signal.self_iteration.mode': getIterationMode(input),+ 'agent.signal.self_iteration_agent.max_steps': maxSteps,+ 'agent.signal.self_iteration_agent.step_count': state.stepCount + 1,+ 'agent.signal.source_id': input.sourceId,+ 'agent.signal.user_id': input.userId,+ },+ },+ async (stepSpan) => {+ try {+ const stepResult = await runtime.step(state, context);+ stepSpan.setAttribute(+ 'agent.signal.self_iteration_agent.step_count',+ stepResult.newState.stepCount,+ );++ if (stepResult.newState.status === 'error') {+ stepSpan.setStatus({ code: SpanStatusCode.ERROR });+ } else {+ stepSpan.setStatus({ code: SpanStatusCode.OK });+ }++ return stepResult;+ } catch (error) {+ stepSpan.recordException(error as Error);+ stepSpan.setStatus({+ code: SpanStatusCode.ERROR,+ message: getErrorMessage(error),+ });++ throw error;+ } finally {+ stepSpan.end();+ }+ },+ );++ state = result.newState;++ if (!result.nextContext) break;+ context = result.nextContext;+ }++ runSpan.setAttribute('agent.signal.self_iteration_agent.step_count', state.stepCount);+ runSpan.setStatus({+ code: state.status === 'error' ? SpanStatusCode.ERROR : SpanStatusCode.OK,+ });++ return {+ actions: writeOutcomes,+ content: contentParts.join(''),+ ideas,+ intents,+ status: state.status === 'error' ? ReviewRunStatus.Failed : ReviewRunStatus.Completed,+ stepCount: state.stepCount,+ toolCalls,+ usage,+ writeOutcomes,+ };+ } catch (error) {+ runSpan.recordException(error as Error);+ runSpan.setStatus({ code: SpanStatusCode.ERROR, message: getErrorMessage(error) });++ throw error;+ } finally {+ runSpan.end();+ }+ },+ );++/** Default step budget for one self-iteration agent run. */+const DEFAULT_MAX_SELF_ITERATION_AGENT_STEPS = 10;++/**+ * Result envelope returned by the bounded self-iteration agent runner.+ */+export interface AgentRunResult {+ /** Executed tool or legacy executor result to persist as receipts. */+ execution: RunResult;+ /** Non-actionable ideas collected during the run. */+ ideas?: SelfReviewIdea[];+ /** Frozen deterministic plan used for Daily Brief proposal projection. */+ projectionPlan: Plan;+ /** Optional number of agent/tool steps consumed by the backend runner. */+ stepCount?: number;+}++/**+ * Input passed to a shared runner backend.+ */+export interface AgentRunnerRunInput {+ /** Bounded digest context collected for one nightly review window. */+ context: NightlyReviewContext;+ /** User-local nightly date used in projected self-iteration plans. */+ localDate?: string;+ /** Maximum backend agent/tool steps allowed for this run. */+ maxSteps: number;+ /** Review scope attached to projected plans and tracing. */+ reviewScope: Scope;+ /** Stable source id used to generate action idempotency keys. */+ sourceId: string;+ /** Safe read/write tools available to the backend runner. */+ tools: ToolSet;+ /** Stable user id owning this run. */+ userId: string;+}++/**+ * Options for creating a bounded self-iteration agent runner.+ */+export interface AgentRunnerOptions {+ /**+ * Maximum backend agent/tool steps.+ *+ * @default 10+ */+ maxSteps?: number;+ /** Backend implementation that may call tools and must return a projected plan. */+ run: (input: AgentRunnerRunInput) => Promise<AgentRunResult>;+ /** Safe tools exposed to the backend implementation. */+ tools: ToolSet;+}++/**+ * Input for one bounded nightly shared run.+ */+export interface AgentRunnerInput {+ /** Bounded digest context collected for one nightly review window. */+ context: NightlyReviewContext;+ /** User-local nightly date used in projected self-iteration plans. */+ localDate?: string;+ /** Stable source id used to generate action idempotency keys. */+ sourceId: string;+ /** Stable user id owning this run. */+ userId: string;+}++const createFailedProjectionPlan = (input: AgentRunnerInput): Plan => ({+ actions: [],+ localDate: input.localDate,+ plannerVersion: 'shared-agent-runner-fallback-v1',+ reviewScope: Scope.Nightly,+ summary: 'Self-iteration review runner failed before producing a valid plan.',+});++/**+ * Creates a bounded runner for nightly self-iteration agent execution.+ *+ * Call stack:+ *+ * createNightlyReviewSourceHandler+ * -> {@link createAgentRunner}+ * -> injected `run`+ * -> safe self-iteration tools+ *+ * Use when:+ * - Nightly self-review should execute through one bounded runner boundary+ * - Tests need to verify fallback and source-id normalization without DB or LLMs+ *+ * Expects:+ * - `sourceId` is stable for idempotency+ * - The backend `run` returns both execution output and the frozen projection plan+ *+ * Returns:+ * - A runner that traces the run, injects tools, enforces the configured step budget, and+ * returns a conservative failed result if the backend cannot produce a result+ */+export const createAgentRunner = (options: AgentRunnerOptions) => {+ const maxSteps = Math.max(1, options.maxSteps ?? DEFAULT_MAX_SELF_ITERATION_AGENT_STEPS);++ return {+ run: async (input: AgentRunnerInput): Promise<AgentRunResult> =>+ tracer.startActiveSpan(+ 'agent_signal.self_iteration_agent.runner.run',+ {+ attributes: {+ 'agent.signal.agent_id': input.context.agentId,+ 'agent.signal.review_scope': Scope.Nightly,+ 'agent.signal.self_iteration_agent.max_steps': maxSteps,+ 'agent.signal.source_id': input.sourceId,+ 'agent.signal.user_id': input.userId,+ },+ },+ async (span) => {+ try {+ const result = await options.run({+ ...input,+ maxSteps,+ reviewScope: Scope.Nightly,+ tools: options.tools,+ });+ const execution = {+ ...result.execution,+ sourceId: result.execution.sourceId ?? input.sourceId,+ };++ span.setAttribute(+ 'agent.signal.self_iteration_agent.plan_action_count',+ result.projectionPlan.actions.length,+ );+ span.setAttribute(+ 'agent.signal.self_iteration_agent.execution_action_count',+ execution.actions.length,+ );+ if (typeof result.stepCount === 'number') {+ span.setAttribute('agent.signal.self_iteration_agent.step_count', result.stepCount);+ }+ span.setStatus({ code: SpanStatusCode.OK });++ return {+ ...result,+ execution,+ };+ } catch (error) {+ span.setStatus({+ code: SpanStatusCode.ERROR,+ message:+ error instanceof Error+ ? error.message+ : 'AgentSignal self-iteration agent runner failed',+ });+ span.recordException(error as Error);++ return {+ execution: {+ actions: [],+ sourceId: input.sourceId,+ status: ReviewRunStatus.Failed,+ },+ projectionPlan: createFailedProjectionPlan(input),+ stepCount: maxSteps,+ };+ } finally {+ span.end();+ }+ },+ ),+ };+};diff --git a/src/server/services/agentSignal/services/selfIteration/feedback/__test__/handler.test.ts b/src/server/services/agentSignal/services/selfIteration/feedback/__test__/handler.test.tsnew file mode 100644index 00000000000..a5e3b610ee7--- /dev/null+++ b/src/server/services/agentSignal/services/selfIteration/feedback/__test__/handler.test.ts@@ -0,0 +1,479 @@+// @vitest-environment node+import { createSource } from '@lobechat/agent-signal';+import type { SourceAgentSelfFeedbackIntentDeclared } from '@lobechat/agent-signal/source';+import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';+import { describe, expect, it, vi } from 'vitest';++import { createDefaultAgentSignalPolicies } from '../../../../policies';+import type { RuntimeProcessorContext } from '../../../../runtime/context';+import type {+ AgentSignalActionHandlerDefinition,+ AgentSignalSignalHandlerDefinition,+ AgentSignalSourceHandlerDefinition,+} from '../../../../runtime/middleware';+import type { ExecuteSelfIterationResult } from '../../execute';+import type { EvidenceRef } from '../../types';+import { ReviewRunStatus } from '../../types';+import type { CreateSelfFeedbackIntentSourceHandlerDependencies } from '../handler';+import {+ createSelfFeedbackIntentSourceHandler,+ createSelfFeedbackIntentSourcePolicyHandler,+} from '../handler';++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-feedback-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 runtimeResult = {+ actions: [+ {+ result: {+ receiptId: 'runtime-memory-receipt',+ resourceId: 'memory-1',+ status: 'applied',+ summary: 'Memory written.',+ },+ toolName: 'writeMemory',+ },+ ],+ content: 'Runtime intent wrote one memory.',+ ideas: [],+ intents: [+ {+ confidence: 0.94,+ evidenceRefs: [intentPayload.evidenceRefs[0]],+ idempotencyKey: `${intentSourceId}:intent:memory`,+ intentType: 'memory',+ mode: 'reflection',+ rationale: 'The user gave a durable preference.',+ risk: 'low',+ urgency: 'immediate',+ },+ ],+ status: ReviewRunStatus.Completed,+ stepCount: 2,+ toolCalls: [+ {+ apiName: 'writeMemory',+ arguments: JSON.stringify({+ content: 'User prefers concise release summaries.',+ evidenceRefs: [intentPayload.evidenceRefs[0]],+ idempotencyKey: `${intentSourceId}:writeMemory:tool-call-1`,+ }),+ id: 'tool-call-1',+ identifier: 'agent-signal-self-iteration',+ type: 'builtin',+ },+ ],+ usage: [],+ writeOutcomes: [+ {+ result: {+ receiptId: 'runtime-memory-receipt',+ resourceId: 'memory-1',+ status: 'applied',+ summary: 'Memory written.',+ },+ toolName: 'writeMemory',+ },+ ],+} satisfies ExecuteSelfIterationResult;++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.agentSelfFeedbackIntentDeclared,+): SourceAgentSelfFeedbackIntentDeclared =>+ createSource({+ payload,+ scope: { agentId: 'agent-1', userId: 'user-1' },+ scopeKey: 'topic:topic-1',+ sourceId,+ sourceType,+ timestamp: 100,+ }) as SourceAgentSelfFeedbackIntentDeclared;++const createDependencies = (+ overrides: Partial<CreateSelfFeedbackIntentSourceHandlerDependencies> = {},+): CreateSelfFeedbackIntentSourceHandlerDependencies => ({+ acquireReviewGuard: vi.fn(async () => true),+ canRunReview: vi.fn(async () => true),+ enrichEvidence: vi.fn(async () => ({+ evidenceRefs: [topicEvidence],+ })),+ executeSelfIteration: vi.fn(async () => runtimeResult),+ maxSteps: 3,+ model: 'gpt-test',+ modelRuntime: { chat: vi.fn() },+ tools: {} as never,+ writeReceipt: vi.fn(async () => {}),+ ...overrides,+});++describe('self-feedback intent source handler', () => {+ /**+ * @example+ * expect(deps.executeSelfIteration).toHaveBeenCalledWith(expect.objectContaining({ mode: 'feedback' }));+ */+ it('runs self-iteration executor for declared intent and records intent metadata on receipts', async () => {+ const deps = createDependencies({ writeReceipts: vi.fn(async () => {}) });+ const handler = createSelfFeedbackIntentSourceHandler(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.executeSelfIteration).toHaveBeenCalledWith(+ expect.objectContaining({+ agentId: 'agent-1',+ context: expect.objectContaining({+ evidenceRefs: [intentPayload.evidenceRefs[0], topicEvidence],+ intent: expect.objectContaining({ summary: intentPayload.summary }),+ sourceId: intentSourceId,+ }),+ maxSteps: 3,+ mode: 'feedback',+ sourceId: intentSourceId,+ userId: 'user-1',+ }),+ );+ expect(deps.writeReceipts).toHaveBeenCalledWith([+ expect.objectContaining({+ id: `${intentSourceId}:review-summary`,+ metadata: expect.objectContaining({+ selfIteration: expect.objectContaining({+ intents: runtimeResult.intents,+ mode: 'feedback',+ sourceId: intentSourceId,+ toolCallId: 'tool-call-1',+ }),+ }),+ }),+ expect.objectContaining({ id: `${intentSourceId}:writeMemory:tool-call-1:action` }),+ ]);+ expect(result).toEqual(+ expect.objectContaining({+ plannedActionCount: 1,+ planSummary: 'Runtime intent wrote one memory.',+ status: ReviewRunStatus.Completed,+ }),+ );+ });++ /**+ * @example+ * expect(runtimeFactory.createRuntime).toHaveBeenCalledWith(expect.objectContaining({ enrichment }));+ */+ it('builds self-iteration executor dependencies through the per-source runtime factory', async () => {+ const executeSelfIteration = vi.fn(async () => runtimeResult);+ const modelRuntime = { chat: vi.fn() };+ const tools = {} as never;+ const runtimeFactory = {+ createRuntime: vi.fn(async () => ({+ executeSelfIteration,+ maxSteps: 4,+ model: 'gpt-factory',+ modelRuntime,+ tools,+ })),+ };+ const deps = createDependencies({+ executeSelfIteration: undefined,+ model: undefined,+ modelRuntime: undefined,+ runtimeFactory,+ tools: undefined,+ writeReceipts: vi.fn(async () => {}),+ });+ const handler = createSelfFeedbackIntentSourceHandler(deps);++ await handler.handle(createIntentSource());++ expect(runtimeFactory.createRuntime).toHaveBeenCalledWith({+ enrichment: { evidenceRefs: [topicEvidence] },+ payload: expect.objectContaining(intentPayload),+ source: expect.objectContaining({ sourceId: intentSourceId }),+ });+ expect(executeSelfIteration).toHaveBeenCalledWith(+ expect.objectContaining({+ maxSteps: 4,+ model: 'gpt-factory',+ modelRuntime,+ mode: 'feedback',+ tools,+ }),+ );+ });++ /**+ * @example+ * await handler.handle(operationSource);+ */+ it('validates operation-scoped source ids and forwards operation context', async () => {+ const deps = createDependencies();+ const handler = createSelfFeedbackIntentSourceHandler(deps);+ const operationSourceId =+ 'self-feedback-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.executeSelfIteration).toHaveBeenCalledWith(+ expect.objectContaining({+ context: expect.objectContaining({+ sourceId: operationSourceId,+ }),+ sourceId: operationSourceId,+ }),+ );+ });++ /**+ * @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 = createSelfFeedbackIntentSourceHandler(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-feedback intent receipt:',+ receiptError,+ );+ consoleError.mockRestore();+ });++ /**+ * @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 = createSelfFeedbackIntentSourceHandler(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.executeSelfIteration).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 = createSelfFeedbackIntentSourceHandler(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.executeSelfIteration).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 = createSelfFeedbackIntentSourceHandler(deps);++ const result = await handler.handle(createIntentSource());++ expect(result).toEqual(+ expect.objectContaining({+ guardKey: intentSourceId,+ status: ReviewRunStatus.Deduped,+ }),+ );+ expect(deps.enrichEvidence).not.toHaveBeenCalled();+ expect(deps.executeSelfIteration).not.toHaveBeenCalled();+ });++ /**+ * @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 = createSelfFeedbackIntentSourceHandler(deps);++ const result = await handler.handle(+ createIntentSource(intentPayload, 'self-feedback-intent:wrong'),+ );++ expect(result).toEqual(+ expect.objectContaining({+ reason: 'invalid_payload',+ sourceId: 'self-feedback-intent:wrong',+ status: ReviewRunStatus.Skipped,+ }),+ );+ expect(deps.canRunReview).not.toHaveBeenCalled();+ expect(deps.executeSelfIteration).not.toHaveBeenCalled();+ });++ /**+ * @example+ * expect(sourceHandlers[0].listen).toBe('agent.self_feedback_intent.declared');+ */+ it('installs an optional self-feedback 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 shared registration test.',+ result: 'neutral',+ }),+ },+ },+ selfFeedbackIntent: 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 selfFeedbackIntentHandler = sourceHandlers.find(+ (handler) => handler.listen === AGENT_SIGNAL_SOURCE_TYPES.agentSelfFeedbackIntentDeclared,+ );++ expect(selfFeedbackIntentHandler).toEqual(+ expect.objectContaining({+ id: `${AGENT_SIGNAL_SOURCE_TYPES.agentSelfFeedbackIntentDeclared}:shared-review`,+ type: 'source',+ }),+ );++ const runtimeResult = await selfFeedbackIntentHandler?.handle(+ createIntentSource(),+ runtimeContext,+ );++ expect(runtimeResult).toEqual(+ expect.objectContaining({+ concluded: expect.objectContaining({ status: ReviewRunStatus.Completed }),+ status: 'conclude',+ }),+ );+ });+});++describe('self-feedback intent source policy handler', () => {+ /**+ * @example+ * expect(handler.listen).toBe('agent.self_feedback_intent.declared');+ */+ it('listens to the self-feedback intent declared source type', () => {+ const handler = createSelfFeedbackIntentSourcePolicyHandler(createDependencies());++ expect(handler.listen).toBe(AGENT_SIGNAL_SOURCE_TYPES.agentSelfFeedbackIntentDeclared);+ });+});diff --git a/src/server/services/agentSignal/services/selfIteration/feedback/__test__/server.test.ts b/src/server/services/agentSignal/services/selfIteration/feedback/__test__/server.test.tsnew file mode 100644index 00000000000..dd924a25557--- /dev/null+++ b/src/server/services/agentSignal/services/selfIteration/feedback/__test__/server.test.ts@@ -0,0 +1,171 @@+// @vitest-environment node+import { createSource } from '@lobechat/agent-signal';+import type { SourceAgentSelfFeedbackIntentDeclared } from '@lobechat/agent-signal/source';+import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';+import { describe, expect, it, vi } from 'vitest';++import type { LobeChatDatabase } from '@/database/type';++import type * as ExecuteModule from '../../execute';+import { ActionStatus, ReviewRunStatus } from '../../types';+import { createSelfFeedbackIntentSourceHandler } from '../handler';+import { createServerSelfFeedbackIntentPolicyOptions } from '../server';++const mocks = vi.hoisted(() => ({+ executeSelfIteration: vi.fn(),+ initModelRuntimeFromDB: vi.fn(async () => ({ chat: vi.fn() })),+ persistAgentSignalReceipts: vi.fn(async () => {}),+ redisTryDedupe: vi.fn(async () => true),+}));++vi.mock('@/server/modules/ModelRuntime', () => ({+ initModelRuntimeFromDB: mocks.initModelRuntimeFromDB,+}));++vi.mock('@/database/models/agentSignal/reviewContext', () => ({+ AgentSignalReviewContextModel: class {+ canAgentRunSelfIteration = vi.fn(async () => true);+ },+}));++vi.mock('@/server/services/agentSignal/store/adapters/redis/sourceEventStore', () => ({+ redisSourceEventStore: {+ readWindow: vi.fn(async () => undefined),+ tryDedupe: mocks.redisTryDedupe,+ writeWindow: vi.fn(async () => undefined),+ },+}));++vi.mock('../../../receiptService', () => ({+ createSelfFeedbackReceipts: vi.fn(({ plan, result, selfIteration, sourceId }) => [+ {+ agentId: 'agent-1',+ detail: plan.summary,+ id: `${sourceId}:review-summary`,+ kind: 'review',+ metadata: { selfIteration },+ sourceId,+ status: result.status,+ title: plan.summary,+ userId: 'user-1',+ },+ ]),+ persistAgentSignalReceipts: mocks.persistAgentSignalReceipts,+}));++vi.mock('../../execute', async (importOriginal) => ({+ ...(await importOriginal<typeof ExecuteModule>()),+ executeSelfIteration: mocks.executeSelfIteration,+}));++const intentPayload = {+ action: 'write',+ agentId: 'agent-1',+ confidence: 0.94,+ evidenceRefs: [{ id: 'msg-1', summary: '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-feedback-intent:user-1:agent-1:topic:topic-1:tool-call-1';++const createIntentSource = (): SourceAgentSelfFeedbackIntentDeclared =>+ createSource({+ payload: intentPayload,+ scope: { agentId: 'agent-1', userId: 'user-1' },+ scopeKey: 'topic:topic-1',+ sourceId: intentSourceId,+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentSelfFeedbackIntentDeclared,+ timestamp: 100,+ }) as SourceAgentSelfFeedbackIntentDeclared;++describe('createServerSelfFeedbackIntentPolicyOptions', () => {+ /**+ * @example+ * expect(mocks.executeSelfIteration).toHaveBeenCalledWith(expect.objectContaining({ mode: 'feedback' }));+ * expect(mocks.executeSelfIteration).toHaveBeenCalledWith(expect.objectContaining({ mode: 'feedback' }));+ */+ it('runs declared intent through the self-iteration executor', async () => {+ mocks.executeSelfIteration.mockResolvedValue({+ actions: [+ {+ result: {+ resourceId: 'memory-1',+ status: 'applied',+ summary: 'Memory written.',+ },+ toolName: 'writeMemory',+ },+ ],+ content: 'Runtime intent wrote one memory.',+ ideas: [],+ intents: [],+ status: ReviewRunStatus.Completed,+ stepCount: 1,+ toolCalls: [],+ usage: [],+ writeOutcomes: [+ {+ result: {+ resourceId: 'memory-1',+ status: 'applied',+ summary: 'Memory written.',+ },+ toolName: 'writeMemory',+ },+ ],+ });++ const options = createServerSelfFeedbackIntentPolicyOptions({+ agentId: 'agent-1',+ db: {} as unknown as LobeChatDatabase,+ selfIterationEnabled: true,+ userId: 'user-1',+ });+ const handler = createSelfFeedbackIntentSourceHandler(options);+ const result = await handler.handle(createIntentSource());++ expect(mocks.initModelRuntimeFromDB).toHaveBeenCalledTimes(1);+ expect(mocks.executeSelfIteration).toHaveBeenCalledWith(+ expect.objectContaining({+ agentId: 'agent-1',+ mode: 'feedback',+ sourceId: intentSourceId,+ userId: 'user-1',+ }),+ );+ expect(mocks.executeSelfIteration.mock.calls[0]?.[0].tools).toEqual(+ expect.objectContaining({+ getEvidenceDigest: expect.any(Function),+ writeMemory: expect.any(Function),+ }),+ );+ expect(mocks.persistAgentSignalReceipts).toHaveBeenCalledWith([+ expect.objectContaining({+ id: `${intentSourceId}:review-summary`,+ metadata: expect.objectContaining({+ selfIteration: expect.objectContaining({+ mode: 'feedback',+ sourceId: intentSourceId,+ }),+ }),+ }),+ ]);+ expect(result).toEqual(+ expect.objectContaining({+ plannedActionCount: 1,+ status: ReviewRunStatus.Completed,+ }),+ );+ expect(result.execution?.actions[0]).toEqual(+ expect.objectContaining({+ resourceId: 'memory-1',+ status: ActionStatus.Applied,+ }),+ );+ });+});diff --git a/src/server/services/agentSignal/services/selfIteration/feedback/handler.ts b/src/server/services/agentSignal/services/selfIteration/feedback/handler.tsnew file mode 100644index 00000000000..d1e27ccfc6d--- /dev/null+++ b/src/server/services/agentSignal/services/selfIteration/feedback/handler.ts@@ -0,0 +1,709 @@+import type { SourceAgentSelfFeedbackIntentDeclared } from '@lobechat/agent-signal/source';+import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';+import type { ModelRuntime } from '@lobechat/model-runtime';++import { defineSourceHandler } from '../../../runtime/middleware';+import type { AgentSignalReceipt } from '../../receiptService';+import { createSelfFeedbackReceipts } from '../../receiptService';+import type { ExecuteSelfIterationInput, ExecuteSelfIterationResult } from '../execute';+import { projectRun } from '../projection';+import type { ToolSet } from '../tools/shared';+import type { EvidenceRef, Idea, Plan, RunResult, SelfFeedbackIntent } from '../types';+import { buildSelfFeedbackIntentSourceId, ReviewRunStatus, Scope } from '../types';++/** Source scope supported by self-feedback intent declarations. */+export type SelfFeedbackIntentSourceScopeType = 'operation' | 'topic';++/** Actions that an agent may declare as self-feedback intent. */+export type SelfFeedbackIntentDeclaredAction =+ | 'write'+ | 'create'+ | 'refine'+ | 'consolidate'+ | 'proposal';++/** Self-feedback target category declared by the running agent. */+export type SelfFeedbackIntentDeclaredKind = 'memory' | 'skill' | 'gap';++/**+ * Validated self-feedback intent source payload consumed by the handler.+ */+export interface SelfFeedbackIntentSourcePayload {+ /** Declared self-review action. */+ action: SelfFeedbackIntentDeclaredAction;+ /** Stable agent id being reviewed. */+ agentId: string;+ /** Agent-declared confidence from 0 to 1. */+ confidence: number;+ /** Source-provided evidence references. */+ evidenceRefs: EvidenceRef[];+ /** Declared shared target category. */+ kind: SelfFeedbackIntentDeclaredKind;+ /** 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: SelfFeedbackIntentSourceScopeType;+ /** 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-feedback intent handler dependencies.+ */+export interface SelfFeedbackIntentSourceGuardInput extends SelfFeedbackIntentSourcePayload {+ /** 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-feedback intent.+ */+export interface EnrichSelfFeedbackIntentEvidenceInput {+ /** Declared self-review action. */+ action: SelfFeedbackIntentDeclaredAction;+ /** Stable agent id being reviewed. */+ agentId: string;+ /** Declared shared target category. */+ kind: SelfFeedbackIntentDeclaredKind;+ /** 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: SelfFeedbackIntentSourceScopeType;+ /** 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 SelfFeedbackIntentEvidenceEnrichment {+ /** Additional evidence references to append before deterministic planning. */+ evidenceRefs: EvidenceRef[];+ /** Whether current context shows an explicit user instruction conflict. */+ hasUserInstructionConflict?: boolean;+}++/**+ * Per-run runtime dependencies for the self-iteration executor.+ */+export interface SelfFeedbackIntentRuntimeConfig {+ /** Runs the self-iteration executor. */+ executeSelfIteration: (input: ExecuteSelfIterationInput) => Promise<ExecuteSelfIterationResult>;+ /**+ * Maximum self-iteration runtime steps.+ *+ * @default 10+ */+ maxSteps?: number;+ /** Model name used by the self-iteration runtime. */+ model: string;+ /** Model runtime used by the self-iteration runtime. */+ modelRuntime: Pick<ModelRuntime, 'chat'>;+ /** Source-scoped safe tools exposed to the self-iteration runtime. */+ tools: ToolSet;+}++/**+ * Input used to create source-scoped runtime dependencies for declared intent handling.+ */+export interface SelfFeedbackIntentRuntimeFactoryInput {+ /** Evidence enrichment already collected for this declaration source. */+ enrichment: SelfFeedbackIntentEvidenceEnrichment;+ /** Validated declaration payload. */+ payload: SelfFeedbackIntentSourcePayload;+ /** Source event that triggered the handler. */+ source: SourceAgentSelfFeedbackIntentDeclared;+}++/**+ * Class-backed boundary that creates source-scoped runtime dependencies.+ */+export interface SelfFeedbackIntentRuntimeFactory {+ /** Builds the model/runtime/tools bundle for one declared intent source. */+ createRuntime: (+ input: SelfFeedbackIntentRuntimeFactoryInput,+ ) => Promise<SelfFeedbackIntentRuntimeConfig> | SelfFeedbackIntentRuntimeConfig;+}++/**+ * Receipt input emitted after one self-feedback execution.+ */+export interface SelfFeedbackIntentReceiptInput {+ /** Executor result for the completed declaration run. */+ execution: RunResult;+ /** Non-actionable ideas captured by the self-iteration runtime. */+ ideas?: Idea[];+ /** Immediate intents captured by the self-iteration runtime. */+ intents?: SelfFeedbackIntent[];+ /** Normalized self-iteration plan sent to the executor. */+ plan: Plan;+ /** Runtime scope id reviewed by the run. */+ scopeId: string;+ /** Runtime scope family reviewed by the run. */+ scopeType: SelfFeedbackIntentSourceScopeType;+ /** Source id that triggered the run. */+ sourceId: string;+ /** Tool-call id that produced the declaration. */+ toolCallId: string;+}++/**+ * Result returned by the self-feedback intent source handler.+ */+export interface SelfFeedbackIntentSourceHandlerResult extends Record<string, unknown> {+ /** Stable agent id being reviewed when payload validation succeeds. */+ agentId?: string;+ /** Executor result for completed runs. */+ execution?: RunResult;+ /** Stable guard key used for idempotency when payload validation succeeds. */+ guardKey?: string;+ /** Number of planned self-review 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?: SelfFeedbackIntentSourceScopeType;+ /** 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-feedback intent source handler.+ */+export interface CreateSelfFeedbackIntentSourceHandlerDependencies {+ /** Acquires the per-declaration idempotency guard. */+ acquireReviewGuard: (input: SelfFeedbackIntentSourceGuardInput) => Promise<boolean>;+ /** Re-checks runtime gates before doing reviewer work. */+ canRunReview: (input: SelfFeedbackIntentSourceGuardInput) => Promise<boolean>;+ /** Adds topic or operation evidence without mutating shared resources. */+ enrichEvidence?: (+ input: EnrichSelfFeedbackIntentEvidenceInput,+ ) => Promise<SelfFeedbackIntentEvidenceEnrichment>;+ /** Runs the self-iteration runtime when no source-scoped factory is injected. */+ executeSelfIteration?: (input: ExecuteSelfIterationInput) => Promise<ExecuteSelfIterationResult>;+ /**+ * Maximum self-iteration runtime steps.+ *+ * @default 10+ */+ maxSteps?: number;+ /** Model name used by the self-iteration runtime. */+ model?: string;+ /** Model runtime used by the self-iteration runtime. */+ modelRuntime?: Pick<ModelRuntime, 'chat'>;+ /** Builds source-scoped shared-runtime dependencies for intent mode. */+ runtimeFactory?: SelfFeedbackIntentRuntimeFactory;+ /** Safe tools exposed to the self-iteration runtime. */+ tools?: ToolSet;+ /** Writes durable receipt metadata for the declaration run. */+ writeReceipt: (input: SelfFeedbackIntentReceiptInput) => 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 isSelfFeedbackIntentAction = (value: unknown): value is SelfFeedbackIntentDeclaredAction =>+ value === 'write' ||+ value === 'create' ||+ value === 'refine' ||+ value === 'consolidate' ||+ value === 'proposal';++const isSelfFeedbackIntentKind = (value: unknown): value is SelfFeedbackIntentDeclaredKind =>+ 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 readSelfFeedbackIntentPayload = (+ source: SourceAgentSelfFeedbackIntentDeclared,+): SelfFeedbackIntentSourcePayload | undefined => {+ if (source.sourceType !== AGENT_SIGNAL_SOURCE_TYPES.agentSelfFeedbackIntentDeclared) return;++ const payload = source.payload;+ if (+ !isSelfFeedbackIntentAction(payload.action) ||+ !isNonEmptyString(payload.agentId) ||+ !isValidConfidence(payload.confidence) ||+ !isSelfFeedbackIntentKind(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: SelfFeedbackIntentSourcePayload,+ source: SourceAgentSelfFeedbackIntentDeclared,+): SelfFeedbackIntentSourceGuardInput => {+ return {+ ...payload,+ guardKey: buildSelfFeedbackIntentSourceId({+ agentId: payload.agentId,+ scopeId: payload.scopeId,+ scopeType: payload.scopeType,+ toolCallId: payload.toolCallId,+ userId: payload.userId,+ }),+ sourceId: source.sourceId,+ };+};++const toEnrichEvidenceInput = (+ payload: SelfFeedbackIntentSourcePayload,+): EnrichSelfFeedbackIntentEvidenceInput => ({+ 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: SelfFeedbackIntentSourceGuardInput,+): Omit<SelfFeedbackIntentSourceHandlerResult, 'status'> => ({+ agentId: guardInput.agentId,+ guardKey: guardInput.guardKey,+ scopeId: guardInput.scopeId,+ scopeType: guardInput.scopeType,+ sourceId: guardInput.sourceId,+ toolCallId: guardInput.toolCallId,+ userId: guardInput.userId,+});++const writeSelfFeedbackIntentReceipt = async (+ deps: CreateSelfFeedbackIntentSourceHandlerDependencies,+ input: SelfFeedbackIntentReceiptInput,+) => {+ try {+ await deps.writeReceipt(input);+ } catch (error) {+ console.error('[AgentSignal] Failed to write self-feedback intent receipt:', error);+ }+};++const writeSelfFeedbackIntentReceipts = async (+ deps: CreateSelfFeedbackIntentSourceHandlerDependencies,+ receipts: AgentSignalReceipt[],+) => {+ if (!deps.writeReceipts || receipts.length === 0) return;++ try {+ await deps.writeReceipts(receipts);+ } catch (error) {+ console.error('[AgentSignal] Failed to write self-feedback intent receipts:', error);+ }+};++const applyReceiptIdsToExecution = (+ execution: RunResult,+ receipts: AgentSignalReceipt[],+): RunResult => {+ 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 canExecuteSharedSelfIteration = (+ deps: CreateSelfFeedbackIntentSourceHandlerDependencies,+): deps is CreateSelfFeedbackIntentSourceHandlerDependencies & {+ executeSelfIteration: (input: ExecuteSelfIterationInput) => Promise<ExecuteSelfIterationResult>;+ model: string;+ modelRuntime: Pick<ModelRuntime, 'chat'>;+ tools: ToolSet;+} => Boolean(deps.executeSelfIteration && deps.model && deps.modelRuntime && deps.tools);++const createIntentRuntimeContext = ({+ enrichment,+ payload,+ sourceId,+}: {+ enrichment: SelfFeedbackIntentEvidenceEnrichment;+ payload: SelfFeedbackIntentSourcePayload;+ sourceId: string;+}) => ({+ agentId: payload.agentId,+ evidenceRefs: [...payload.evidenceRefs, ...enrichment.evidenceRefs],+ intent: payload,+ sourceId,+ userId: payload.userId,+});++const runSharedSelfFeedbackIntent = async ({+ deps,+ enrichment,+ payload,+ runtime,+ source,+}: {+ deps: CreateSelfFeedbackIntentSourceHandlerDependencies;+ enrichment: SelfFeedbackIntentEvidenceEnrichment;+ payload: SelfFeedbackIntentSourcePayload;+ runtime: SelfFeedbackIntentRuntimeConfig;+ source: SourceAgentSelfFeedbackIntentDeclared;+}) => {+ const timestamp = new Date(source.timestamp).toISOString();+ const runtimeResult = await runtime.executeSelfIteration({+ agentId: payload.agentId,+ context: createIntentRuntimeContext({ enrichment, payload, sourceId: source.sourceId }),+ maxSteps: runtime.maxSteps ?? deps.maxSteps ?? 10,+ mode: 'feedback',+ model: runtime.model,+ modelRuntime: runtime.modelRuntime,+ sourceId: source.sourceId,+ tools: runtime.tools,+ userId: payload.userId,+ window: {+ end: timestamp,+ start: timestamp,+ },+ });+ const projected = projectRun({+ content: runtimeResult.content,+ outcomes: runtimeResult.writeOutcomes.map((outcome) => ({+ ...outcome.result,+ toolName: outcome.toolName,+ })),+ reviewScope: Scope.SelfFeedback,+ sourceId: source.sourceId,+ toolCalls: runtimeResult.toolCalls,+ userId: payload.userId,+ });++ return {+ execution: projected.execution,+ ideas: runtimeResult.ideas,+ plan: projected.projectionPlan,+ runtimeIntents: runtimeResult.intents,+ window: { end: timestamp, start: timestamp },+ };+};++const resolveSharedSelfFeedbackIntentRuntime = async ({+ deps,+ enrichment,+ payload,+ source,+}: {+ deps: CreateSelfFeedbackIntentSourceHandlerDependencies;+ enrichment: SelfFeedbackIntentEvidenceEnrichment;+ payload: SelfFeedbackIntentSourcePayload;+ source: SourceAgentSelfFeedbackIntentDeclared;+}): Promise<SelfFeedbackIntentRuntimeConfig | undefined> => {+ if (deps.runtimeFactory) {+ return deps.runtimeFactory.createRuntime({ enrichment, payload, source });+ }++ if (!canExecuteSharedSelfIteration(deps)) return;++ return {+ executeSelfIteration: deps.executeSelfIteration,+ maxSteps: deps.maxSteps,+ model: deps.model,+ modelRuntime: deps.modelRuntime,+ tools: deps.tools,+ };+};++/**+ * Creates the DI-friendly handler for self-feedback intent declaration sources.+ *+ * Triggering workflow:+ *+ * {@link createSelfFeedbackIntentSourcePolicyHandler}+ * -> `agent.self_feedback_intent.declared`+ * -> {@link createSelfFeedbackIntentSourceHandler}+ *+ * Upstream:+ * - `agent.self_feedback_intent.declared`+ *+ * Downstream:+ * - injected self-iteration executor+ * - 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 self-iteration plans+ *+ * Expects:+ * - `source` is an `agent.self_feedback_intent.declared` source with service-produced payload+ * - Dependencies enforce gates, idempotency, executor persistence, and receipts+ *+ * Returns:+ * - A run result with status and enough plan metadata for self-feedback intent receipts+ */+export const createSelfFeedbackIntentSourceHandler = (+ deps: CreateSelfFeedbackIntentSourceHandlerDependencies,+) => ({+ handle: async (+ source: SourceAgentSelfFeedbackIntentDeclared,+ ): Promise<SelfFeedbackIntentSourceHandlerResult> => {+ const payload = readSelfFeedbackIntentPayload(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 runtime = await resolveSharedSelfFeedbackIntentRuntime({+ deps,+ enrichment,+ payload,+ source,+ });++ if (!runtime) throw new Error('Self-iteration intent self-iteration runtime is required.');++ const runtimeRun = await runSharedSelfFeedbackIntent({+ deps,+ enrichment,+ payload,+ runtime,+ source,+ });+ const plan: Plan = runtimeRun.plan;+ const execution: RunResult = runtimeRun.execution;++ const receipts = createSelfFeedbackReceipts({+ agentId: payload.agentId,+ createdAt: source.timestamp,+ plan,+ result: {+ ...execution,+ sourceId: source.sourceId,+ },+ selfIteration: {+ ideas: runtimeRun.ideas,+ intents: runtimeRun.runtimeIntents,+ mode: 'feedback',+ scope: { id: payload.scopeId, type: payload.scopeType },+ sourceId: source.sourceId,+ toolCallId: payload.toolCallId,+ window: runtimeRun.window,+ },+ 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 writeSelfFeedbackIntentReceipts(deps, receipts);++ await writeSelfFeedbackIntentReceipt(deps, {+ execution: executionWithReceipts,+ ideas: runtimeRun?.ideas,+ intents: runtimeRun?.runtimeIntents,+ 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-feedback intent policy composition.+ *+ * Triggering workflow:+ *+ * {@link defineSourceHandler}+ * -> `agent.self_feedback_intent.declared`+ * -> {@link createSelfFeedbackIntentSourcePolicyHandler}+ *+ * Upstream:+ * - `agent.self_feedback_intent.declared`+ *+ * Downstream:+ * - {@link createSelfFeedbackIntentSourceHandler}+ *+ * Use when:+ * - Default Agent Signal policies are composed with self-feedback 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 createSelfFeedbackIntentSourcePolicyHandler = (+ deps: CreateSelfFeedbackIntentSourceHandlerDependencies,+) => {+ const handler = createSelfFeedbackIntentSourceHandler(deps);++ return defineSourceHandler(+ AGENT_SIGNAL_SOURCE_TYPES.agentSelfFeedbackIntentDeclared,+ `${AGENT_SIGNAL_SOURCE_TYPES.agentSelfFeedbackIntentDeclared}:shared-review`,+ async (source: SourceAgentSelfFeedbackIntentDeclared) => {+ const result = await handler.handle(source);++ return {+ concluded: result,+ status: 'conclude',+ };+ },+ );+};diff --git a/src/server/services/agentSignal/services/selfIteration/feedback/server.ts b/src/server/services/agentSignal/services/selfIteration/feedback/server.tsnew file mode 100644index 00000000000..ca28543e35a--- /dev/null+++ b/src/server/services/agentSignal/services/selfIteration/feedback/server.ts@@ -0,0 +1,501 @@+import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';+import { DEFAULT_MINI_SYSTEM_AGENT_ITEM } from '@lobechat/const';++import { AgentSignalReviewContextModel } from '@/database/models/agentSignal/reviewContext';+import type { LobeChatDatabase } from '@/database/type';+import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';+import { AGENT_SIGNAL_DEFAULTS } from '@/server/services/agentSignal/constants';+import { runMemoryActionAgent } from '@/server/services/agentSignal/policies/analyzeIntent/actions/userMemory';+import { redisSourceEventStore } from '@/server/services/agentSignal/store/adapters/redis/sourceEventStore';+import { SkillManagementDocumentService } from '@/server/services/skillManagement';++import { persistAgentSignalReceipts } from '../../receiptService';+import { executeSelfIteration } from '../execute';+import { createSelfReviewProposalPreflightService } from '../review/proposalPreflight';+import { createSelfReviewProposalSnapshotService } from '../review/proposalSnapshot';+import type { CreateServerSelfIterationPolicyOptions } from '../server';+import { canRunSelfIterationSource } from '../server';+import type {+ OperationReservation,+ ReplaceSkillContentCASInput,+ ToolReceiptInput,+ ToolWriteResult,+} from '../tools/shared';+import { createMemoryService, createSkillManagementService, createToolSet } from '../tools/shared';+import { Risk } from '../types';+import type {+ CreateSelfFeedbackIntentSourceHandlerDependencies,+ SelfFeedbackIntentEvidenceEnrichment,+ SelfFeedbackIntentRuntimeFactory,+} from './handler';++const SELF_FEEDBACK_INTENT_OPERATION_STATE_TTL_SECONDS = AGENT_SIGNAL_DEFAULTS.receiptTtlSeconds;++const selfFeedbackIntentOperationScopeKey = (idempotencyKey: string) =>+ `self-feedback-intent-operation:${idempotencyKey}`;++const selfFeedbackIntentOperationReserveKey = (idempotencyKey: string) =>+ `self-feedback-intent-operation-reserve:${idempotencyKey}`;++const parseStoredOperationResult = (+ payload: Record<string, string> | undefined,+): ToolWriteResult | undefined => {+ if (!payload?.result) return;++ try {+ const result = JSON.parse(payload.result) as ToolWriteResult;++ if (+ result.status === 'applied' ||+ result.status === 'deduped' ||+ result.status === 'failed' ||+ result.status === 'proposed' ||+ result.status === 'skipped_stale' ||+ result.status === 'skipped_unsupported'+ ) {+ return result;+ }+ } catch {+ return;+ }+};++const reserveSelfFeedbackIntentOperation = async (+ idempotencyKey: string,+): Promise<OperationReservation> => {+ const scopeKey = selfFeedbackIntentOperationScopeKey(idempotencyKey);+ const existing = parseStoredOperationResult(await redisSourceEventStore.readWindow(scopeKey));++ if (existing) return { existing, reserved: false };++ const reserved = await redisSourceEventStore.tryDedupe(+ selfFeedbackIntentOperationReserveKey(idempotencyKey),+ SELF_FEEDBACK_INTENT_OPERATION_STATE_TTL_SECONDS,+ );++ if (reserved) return { reserved: true };++ return {+ existing: parseStoredOperationResult(await redisSourceEventStore.readWindow(scopeKey)) ?? {+ status: 'skipped_unsupported',+ summary:+ 'Self-iteration intent operation is already reserved or Redis is unavailable; skipped to avoid duplicate mutation.',+ },+ reserved: false,+ };+};++const completeSelfFeedbackIntentOperation = async (input: ToolReceiptInput) => {+ await redisSourceEventStore.writeWindow(+ selfFeedbackIntentOperationScopeKey(input.idempotencyKey),+ {+ result: JSON.stringify({+ ...(input.receiptId ? { receiptId: input.receiptId } : {}),+ ...(input.resourceId ? { resourceId: input.resourceId } : {}),+ status: input.status,+ ...(input.summary ? { summary: input.summary } : {}),+ } satisfies ToolWriteResult),+ },+ SELF_FEEDBACK_INTENT_OPERATION_STATE_TTL_SECONDS,+ );+};++const getToolReceiptStatus = (+ status: ToolReceiptInput['status'],+): 'applied' | 'failed' | 'proposed' | 'skipped' => {+ if (status === 'applied') return 'applied';+ if (status === 'failed') return 'failed';+ if (status === 'proposed') return 'proposed';++ return 'skipped';+};++const writeSelfFeedbackIntentToolReceipt = async ({+ agentId,+ input,+ sourceId,+ userId,+}: {+ agentId: string;+ input: ToolReceiptInput;+ sourceId: string;+ userId: string;+}) => {+ await persistAgentSignalReceipts([+ {+ agentId,+ createdAt: Date.now(),+ detail:+ input.summary ??+ `Self-iteration intent tool ${input.toolName} finished with ${input.status}.`,+ id: input.idempotencyKey,+ kind:+ input.toolName === 'createSkillIfAbsent' || input.toolName === 'replaceSkillContentCAS'+ ? 'skill'+ : 'review',+ metadata: {+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentSelfFeedbackIntentDeclared,+ },+ sourceId,+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentSelfFeedbackIntentDeclared,+ status: getToolReceiptStatus(input.status),+ ...(input.resourceId &&+ (input.toolName === 'createSkillIfAbsent' || input.toolName === 'replaceSkillContentCAS')+ ? {+ target: {+ id: input.resourceId,+ ...(input.summary ? { summary: input.summary } : {}),+ title: input.summary ?? input.resourceId,+ type: 'skill',+ },+ }+ : {}),+ title: input.summary ?? 'Self-iteration intent tool outcome',+ topicId: sourceId,+ userId,+ },+ ]);++ return { receiptId: input.idempotencyKey };+};++const createIntentEvidenceDigest = ({+ enrichment,+ payload,+ sourceId,+}: {+ enrichment: SelfFeedbackIntentEvidenceEnrichment;+ payload: Parameters<SelfFeedbackIntentRuntimeFactory['createRuntime']>[0]['payload'];+ sourceId: string;+}) => ({+ evidenceRefs: [...payload.evidenceRefs, ...enrichment.evidenceRefs],+ intent: payload,+ scope: {+ id: payload.scopeId,+ type: payload.scopeType,+ },+ sourceId,+});++const createIntentRuntimeTools = ({+ agentId,+ db,+ enrichment,+ payload,+ skillDocumentService,+ sourceId,+ userId,+}: {+ agentId: string;+ db: LobeChatDatabase;+ enrichment: SelfFeedbackIntentEvidenceEnrichment;+ payload: Parameters<SelfFeedbackIntentRuntimeFactory['createRuntime']>[0]['payload'];+ skillDocumentService: SkillManagementDocumentService;+ sourceId: string;+ userId: string;+}) => {+ const evidenceRefs = createIntentEvidenceDigest({ enrichment, payload, sourceId }).evidenceRefs;+ const proposalPreflight = createSelfReviewProposalPreflightService({+ isSkillNameAvailable: async ({ agentId: targetAgentId, name }) => {+ const skills = await skillDocumentService.listSkills({ agentId: targetAgentId ?? agentId });++ return !skills.some((skill) => skill.name === name);+ },+ readSkillTargetSnapshot: (skillDocumentId) =>+ skillDocumentService.readSkillTargetSnapshot({+ agentDocumentId: skillDocumentId,+ agentId,+ }),+ });+ const proposalSnapshot = createSelfReviewProposalSnapshotService({+ isSkillNameAvailable: async ({ agentId: targetAgentId, name }) => {+ const skills = await skillDocumentService.listSkills({ agentId: targetAgentId ?? agentId });++ return !skills.some((skill) => skill.name === name);+ },+ readSkillTargetSnapshot: (skillDocumentId) =>+ skillDocumentService.readSkillTargetSnapshot({+ agentDocumentId: skillDocumentId,+ agentId,+ }),+ });+ const skillService = createSkillManagementService({+ createSkill: async ({ input }) => {+ const result = await skillDocumentService.createSkill({+ agentId,+ bodyMarkdown: input.bodyMarkdown ?? '',+ description: input.description ?? 'Agent Signal managed skill.',+ name: input.name ?? input.title ?? 'agent-signal-skill',+ title: input.title ?? input.name ?? 'Agent Signal skill',+ });++ return {+ skillDocumentId: result.bundle.agentDocumentId,+ summary: `Created managed skill ${result.name}.`,+ };+ },+ refineSkill: async ({ input }) => {+ const result = await skillDocumentService.replaceSkillIndex({+ agentDocumentId: input.skillDocumentId,+ agentId,+ bodyMarkdown: input.bodyMarkdown ?? '',+ });++ if (!result) throw new Error('Skill target not found');++ return {+ skillDocumentId: result.bundle.agentDocumentId,+ summary: `Refined managed skill ${result.name}.`,+ };+ },+ });++ return createToolSet({+ completeOperation: completeSelfFeedbackIntentOperation,+ completeReplaceSkillInput: async (input: ReplaceSkillContentCASInput) => {+ const baseSnapshot = await proposalSnapshot.captureActionSnapshot({+ actionType: 'refine_skill',+ agentId,+ input: { skillDocumentId: input.skillDocumentId },+ userId,+ });++ return {+ ...input,+ baseSnapshot,+ skillDocumentId: baseSnapshot.agentDocumentId ?? input.skillDocumentId,+ };+ },+ createSkill: async (input) => {+ const result = await skillService.createSkill({+ evidenceRefs,+ idempotencyKey: input.idempotencyKey,+ input,+ });++ return {+ resourceId: result.skillDocumentId,+ summary: result.summary,+ };+ },+ getEvidenceDigest: async () =>+ createIntentEvidenceDigest({+ enrichment,+ payload,+ sourceId,+ }),+ getManagedSkill: ({ agentId: targetAgentId, skillDocumentId }) =>+ skillDocumentService.getSkill({+ agentDocumentId: skillDocumentId,+ agentId: targetAgentId,+ includeContent: true,+ }),+ listManagedSkills: ({ agentId: targetAgentId }) =>+ skillDocumentService.listSkills({ agentId: targetAgentId }),+ preflight: async (input) => {+ if ('skillDocumentId' in input) {+ const preflight = await proposalPreflight.checkAction({+ actionType: 'refine_skill',+ baseSnapshot: input.baseSnapshot,+ evidenceRefs: [],+ idempotencyKey: input.idempotencyKey,+ operation: {+ domain: 'skill',+ input: {+ bodyMarkdown: input.bodyMarkdown,+ patch: input.summary,+ skillDocumentId: input.skillDocumentId,+ userId: input.userId,+ },+ operation: 'refine',+ },+ rationale: input.summary ?? `Refine managed skill ${input.skillDocumentId}.`,+ risk: Risk.Low,+ target: { skillDocumentId: input.skillDocumentId },+ });++ return preflight.allowed ? { allowed: true } : { allowed: false, reason: preflight.reason };+ }++ return { allowed: true };+ },+ replaceSkill: async (input) => {+ const result = await skillService.refineSkill({+ evidenceRefs,+ idempotencyKey: input.idempotencyKey,+ input,+ });++ return {+ resourceId: result.skillDocumentId,+ summary: result.summary,+ };+ },+ reserveOperation: reserveSelfFeedbackIntentOperation,+ writeMemory: async (input) => {+ const memoryService = createMemoryService({+ writeMemory: async ({ content, evidenceRefs, idempotencyKey }) => {+ const result = await runMemoryActionAgent(+ {+ agentId,+ message: content,+ reason: `Agent Signal self-feedback intent memory candidate from ${evidenceRefs.length} evidence refs.`,+ },+ {+ db,+ 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,+ };+ },+ });+ const result = await memoryService.writeMemory({+ evidenceRefs: input.evidenceRefs,+ idempotencyKey: input.idempotencyKey,+ input: {+ content: input.content,+ userId: input.userId,+ },+ });++ return {+ resourceId: result.memoryId,+ summary: result.summary,+ };+ },+ writeReceipt: (input) =>+ writeSelfFeedbackIntentToolReceipt({ agentId, input, sourceId, userId }),+ });+};++/**+ * Creates source-scoped runtime dependencies for server self-feedback intent runs.+ *+ * Call stack:+ *+ * createServerSelfFeedbackIntentPolicyOptions+ * -> {@link SelfFeedbackIntentServerRuntimeFactory.createRuntime}+ * -> {@link executeSelfIteration}+ * -> self-feedback intent tools and receipt persistence+ *+ * Use when:+ * - The Agent Signal workflow consumes `agent.self_feedback_intent.declared`+ * - Declared agent feedback must use the self-iteration executor instead of legacy planner/executor+ *+ * Expects:+ * - The handler has already validated the source payload and guard+ * - Tools are scoped to one user/agent/source id+ *+ * Returns:+ * - Model runtime, toolset, and executor callback for one intent run+ */+export class SelfFeedbackIntentServerRuntimeFactory implements SelfFeedbackIntentRuntimeFactory {+ constructor(+ private readonly input: {+ db: LobeChatDatabase;+ skillDocumentService: SkillManagementDocumentService;+ userId: string;+ },+ ) {}++ async createRuntime({+ enrichment,+ payload,+ source,+ }: Parameters<SelfFeedbackIntentRuntimeFactory['createRuntime']>[0]) {+ const modelRuntime = await initModelRuntimeFromDB(+ this.input.db,+ this.input.userId,+ DEFAULT_MINI_SYSTEM_AGENT_ITEM.provider,+ );++ return {+ executeSelfIteration,+ model: DEFAULT_MINI_SYSTEM_AGENT_ITEM.model,+ modelRuntime,+ tools: createIntentRuntimeTools({+ agentId: payload.agentId,+ db: this.input.db,+ enrichment,+ payload,+ skillDocumentService: this.input.skillDocumentService,+ sourceId: source.sourceId,+ userId: this.input.userId,+ }),+ };+ }+}++/**+ * Creates server runtime handlers for agent-declared self-feedback intent sources.+ *+ * Call stack:+ *+ * runAgentSignalWorkflow+ * -> {@link createServerSelfFeedbackIntentPolicyOptions}+ * -> intent source handler dependencies+ * -> {@link SelfFeedbackIntentServerRuntimeFactory}+ *+ * Use when:+ * - The Agent Signal workflow consumes `agent.self_feedback_intent.declared`+ * - Runtime policy composition needs scoped shared execution and receipts+ *+ * Expects:+ * - The source was emitted by `declareSelfFeedbackIntent`+ * - The handler will re-check gates and idempotency before reviewer work+ *+ * Returns:+ * - Intent handler options ready for `createDefaultAgentSignalPolicies`+ */+export const createServerSelfFeedbackIntentPolicyOptions = ({+ agentId,+ db,+ selfIterationEnabled = false,+ userId,+}: CreateServerSelfIterationPolicyOptions): CreateSelfFeedbackIntentSourceHandlerDependencies => {+ const reviewContextModel = new AgentSignalReviewContextModel(db, userId);+ const skillDocumentService = new SkillManagementDocumentService(db, userId);++ return {+ acquireReviewGuard: (input) =>+ redisSourceEventStore.tryDedupe(+ `self-feedback-intent-guard:${input.guardKey}`,+ AGENT_SIGNAL_DEFAULTS.receiptTtlSeconds,+ ),+ canRunReview: async (input) => {+ if (input.userId !== userId) return false;++ return canRunSelfIterationSource({+ agentId: input.agentId,+ expectedAgentId: agentId,+ reviewContextModel,+ selfIterationEnabled,+ });+ },+ enrichEvidence: async (input) => ({+ evidenceRefs: [+ {+ id: input.scopeId,+ type: input.scopeType,+ },+ ],+ }),+ runtimeFactory: new SelfFeedbackIntentServerRuntimeFactory({+ db,+ skillDocumentService,+ userId,+ }),+ writeReceipt: async () => {},+ writeReceipts: (receipts) => persistAgentSignalReceipts(receipts),+ };+};diff --git a/src/server/services/agentSignal/services/selfIteration/index.ts b/src/server/services/agentSignal/services/selfIteration/index.tsnew file mode 100644index 00000000000..fcb073fefcd--- /dev/null+++ b/src/server/services/agentSignal/services/selfIteration/index.ts@@ -0,0 +1 @@+export * from './types';diff --git a/src/server/services/agentSignal/services/maintenance/briefProjection.ts b/src/server/services/agentSignal/services/selfIteration/projection.tssimilarity index 72%rename from src/server/services/agentSignal/services/maintenance/briefProjection.tsrename to src/server/services/agentSignal/services/selfIteration/projection.tsindex 2af98048875..266c0f9d36c 100644--- a/src/server/services/agentSignal/services/maintenance/briefProjection.ts+++ b/src/server/services/agentSignal/services/selfIteration/projection.ts@@ -1,50 +1,45 @@import type { ChatToolPayload } from '@lobechat/types';import type {- MaintenanceProposalBaseSnapshot,- MaintenanceProposalPlan,- MaintenanceReviewIdea,-} from './proposal';-import type { MaintenanceToolWriteResult } from './tools';+ SelfReviewIdea,+ SelfReviewProposalBaseSnapshot,+ SelfReviewProposalPlan,+} from './review/proposal';+import type { ToolWriteResult } from './tools/shared';import type {- MaintenanceActionPlan,- MaintenanceActionStatus as MaintenanceActionStatusValue,- MaintenanceActionTarget,- MaintenanceReviewRunResult,- MaintenanceReviewScope,-} from './types';-import {- MaintenanceActionStatus,- MaintenanceApplyMode,- MaintenanceRisk,- ReviewRunStatus,+ ActionPlan,+ ActionStatus as ActionStatusValue,+ ActionTarget,+ RunResult,+ Scope,} from './types';+import { ActionStatus, ApplyMode, ReviewRunStatus, Risk } from './types';-/** Brief category selected from maintenance write-tool outcomes. */-export type MaintenanceBriefKind = 'decision' | 'insight' | 'none';+/** Brief category selected from write-tool outcomes. */+export type SelfReviewBriefKind = 'decision' | 'insight' | 'none';/** Write-tool result enriched with the tool name that produced it. */-export interface MaintenanceToolOutcome extends MaintenanceToolWriteResult {+export interface ToolOutcome extends ToolWriteResult {/** Stable write-tool name used for brief metadata and diagnostics. */toolName: string;}-/** Input for projecting maintenance write-tool outcomes to Daily Brief metadata. */-export interface ProjectMaintenanceToolOutcomesInput {- /** Terminal write-tool outcomes collected from one maintenance turn. */- outcomes: MaintenanceToolOutcome[];+/** Input for projecting write-tool outcomes to Daily Brief metadata. */+export interface ProjectOutcomesInput {+ /** Terminal write-tool outcomes collected from one runtime turn. */+ outcomes: ToolOutcome[];}/** Input for projecting a complete tool-first runtime result into legacy brief contracts. */-export interface ProjectMaintenanceToolRuntimeRunInput extends ProjectMaintenanceToolOutcomesInput {+export interface ProjectRunInput extends ProjectOutcomesInput {/** Assistant summary emitted by the tool-first runtime. */content?: string;/** Whether proposal lifecycle tool calls should project embedded resource actions. */includeProposalLifecycleActions?: boolean;- /** User-local nightly date used in the projected maintenance plan. */+ /** User-local nightly date used in the projected self-iteration plan. */localDate?: string;- /** Review scope attached to the projected maintenance plan. */- reviewScope: MaintenanceReviewScope;+ /** Review scope attached to the projected self-iteration plan. */+ reviewScope: Scope;/** Stable source id used for idempotency-key fallbacks. */sourceId: string;/** Tool calls captured by the runtime in execution order. */@@ -54,17 +49,17 @@ export interface ProjectMaintenanceToolRuntimeRunInput extends ProjectMaintenanc}/** Legacy contracts projected from a tool-first runtime run. */-export interface ProjectedMaintenanceToolRuntimeRun {+export interface ProjectedRun {/** Executor-shaped result consumed by receipt and brief projection. */- execution: MaintenanceReviewRunResult;+ execution: RunResult;/** Non-actionable ideas extracted from proposal-only actions. */- ideas: MaintenanceReviewIdea[];+ ideas: SelfReviewIdea[];/** Plan-shaped projection consumed by Daily Brief proposal metadata. */- projectionPlan: MaintenanceProposalPlan;+ projectionPlan: SelfReviewProposalPlan;}/** Per-status counts retained in brief-compatible metadata. */-export interface ProjectedMaintenanceToolOutcomeCounts {+export interface ProjectedOutcomeCounts {/** Number of write tools that mutated durable state. */applied: number;/** Number of write tools that failed. */@@ -75,14 +70,14 @@ export interface ProjectedMaintenanceToolOutcomeCounts {skipped: number;}-/** Brief-compatible metadata projected from maintenance write-tool outcomes. */-export interface ProjectedMaintenanceToolOutcomes {+/** Brief-compatible metadata projected from write-tool outcomes. */+export interface ProjectedOutcomes {/** Per-status counts used by brief copy and filtering. */- actionCounts: ProjectedMaintenanceToolOutcomeCounts;+ actionCounts: ProjectedOutcomeCounts;/** Bounded write-tool action fields safe to retain in brief metadata. */- actions: MaintenanceToolOutcome[];+ actions: ToolOutcome[];/** Coarse brief kind selected from visible write-tool outcomes. */- briefKind: MaintenanceBriefKind;+ briefKind: SelfReviewBriefKind;/** Number of proposed write outcomes that should request a decision brief. */proposalCount: number;/** Durable receipt ids linked to the projected outcomes. */@@ -90,12 +85,21 @@ export interface ProjectedMaintenanceToolOutcomes {}const PROPOSAL_LIFECYCLE_TOOL_NAMES = new Set([- 'closeMaintenanceProposal',- 'createMaintenanceProposal',- 'refreshMaintenanceProposal',- 'supersedeMaintenanceProposal',+ 'closeSelfReviewProposal',+ 'createSelfReviewProposal',+ 'refreshSelfReviewProposal',+ 'supersedeSelfReviewProposal',]);+const normalizeProjectionToolName = (toolName: string) => {+ if (toolName === 'closeSelfReviewProposal') return 'closeSelfReviewProposal';+ if (toolName === 'createSelfReviewProposal') return 'createSelfReviewProposal';+ if (toolName === 'refreshSelfReviewProposal') return 'refreshSelfReviewProposal';+ if (toolName === 'supersedeSelfReviewProposal') return 'supersedeSelfReviewProposal';++ return toolName;+};+const isProposalLifecycleTool = (toolName: string) => PROPOSAL_LIFECYCLE_TOOL_NAMES.has(toolName);/**@@ -107,7 +111,7 @@ const isProposalLifecycleTool = (toolName: string) => PROPOSAL_LIFECYCLE_TOOL_NA* After:* - `{ toolName: "writeMemory", status: "applied" }`*/-const projectAction = (outcome: MaintenanceToolOutcome): MaintenanceToolOutcome => ({+const projectAction = (outcome: ToolOutcome): ToolOutcome => ({...(outcome.receiptId === undefined ? {} : { receiptId: outcome.receiptId }),...(outcome.resourceId === undefined ? {} : { resourceId: outcome.resourceId }),status: outcome.status,@@ -116,10 +120,10 @@ const projectAction = (outcome: MaintenanceToolOutcome): MaintenanceToolOutcome});/**- * Projects maintenance write-tool outcomes into brief-compatible metadata.+ * Projects shared write-tool outcomes into brief-compatible metadata.** Use when:- * - Maintenance tools need a compact Daily Brief projection+ * - Self-review tools need a compact Daily Brief projection* - Tool outcomes should be classified as decision, insight, or silent metadata** Expects:@@ -129,10 +133,8 @@ const projectAction = (outcome: MaintenanceToolOutcome): MaintenanceToolOutcome* Returns:* - Counts, receipt ids, bounded actions, and the selected brief kind*/-export const projectMaintenanceToolOutcomes = (- input: ProjectMaintenanceToolOutcomesInput,-): ProjectedMaintenanceToolOutcomes => {- const actionCounts: ProjectedMaintenanceToolOutcomeCounts = {+export const projectOutcomes = (input: ProjectOutcomesInput): ProjectedOutcomes => {+ const actionCounts: ProjectedOutcomeCounts = {applied: 0,failed: 0,proposed: 0,@@ -161,7 +163,7 @@ export const projectMaintenanceToolOutcomes = (const hasVisibleRiskOutcome = input.outcomes.some((outcome) => outcome.status === 'failed' || outcome.status === 'skipped_stale',);- const briefKind: MaintenanceBriefKind =+ const briefKind: SelfReviewBriefKind =proposalCount > 0? 'decision': actionCounts.applied > 0 || hasVisibleRiskOutcome@@ -178,12 +180,17 @@ export const projectMaintenanceToolOutcomes = (};const WRITE_TOOL_NAMES = new Set([- 'closeMaintenanceProposal',- 'createMaintenanceProposal',+ 'closeSelfReviewProposal',+ 'closeSelfReviewProposal',+ 'createSelfReviewProposal',+ 'createSelfReviewProposal','createSkillIfAbsent',- 'refreshMaintenanceProposal',+ 'refreshSelfReviewProposal',+ 'refreshSelfReviewProposal','replaceSkillContentCAS',- 'supersedeMaintenanceProposal',+ 'supersedeSelfReviewProposal',+ 'supersedeSelfReviewProposal',+ 'writeMemory',]);const parseToolArguments = (value: string | undefined): Record<string, unknown> => {@@ -213,7 +220,7 @@ const getRecord = (value: unknown): Record<string, unknown> =>? (value as Record<string, unknown>): {};-const getBaseSnapshot = (value: unknown): MaintenanceProposalBaseSnapshot | undefined => {+const getBaseSnapshot = (value: unknown): SelfReviewProposalBaseSnapshot | undefined => {const record = getRecord(value);if (Object.keys(record).length === 0) return;@@ -231,30 +238,24 @@ const getBaseSnapshot = (value: unknown): MaintenanceProposalBaseSnapshot | unde};};-const getBaseSnapshots = (value: unknown): MaintenanceProposalBaseSnapshot[] =>+const getBaseSnapshots = (value: unknown): SelfReviewProposalBaseSnapshot[] =>Array.isArray(value) ? value.flatMap((item) => getBaseSnapshot(item) ?? []) : [];-const toActionStatus = (- status: MaintenanceToolWriteResult['status'],-): MaintenanceActionStatusValue => {- if (status === 'applied') return MaintenanceActionStatus.Applied;- if (status === 'deduped') return MaintenanceActionStatus.Deduped;- if (status === 'failed') return MaintenanceActionStatus.Failed;- if (status === 'proposed') return MaintenanceActionStatus.Proposed;+const toActionStatus = (status: ToolWriteResult['status']): ActionStatusValue => {+ if (status === 'applied') return ActionStatus.Applied;+ if (status === 'deduped') return ActionStatus.Deduped;+ if (status === 'failed') return ActionStatus.Failed;+ if (status === 'proposed') return ActionStatus.Proposed;- return MaintenanceActionStatus.Skipped;+ return ActionStatus.Skipped;};-const getRunStatus = (actions: MaintenanceReviewRunResult['actions']): ReviewRunStatus => {+const getRunStatus = (actions: RunResult['actions']): ReviewRunStatus => {if (actions.length === 0) return ReviewRunStatus.Skipped;- const failedCount = actions.filter(- (action) => action.status === MaintenanceActionStatus.Failed,- ).length;+ const failedCount = actions.filter((action) => action.status === ActionStatus.Failed).length;const successfulCount = actions.filter(- (action) =>- action.status === MaintenanceActionStatus.Applied ||- action.status === MaintenanceActionStatus.Proposed,+ (action) => action.status === ActionStatus.Applied || action.status === ActionStatus.Proposed,).length;if (failedCount > 0 && successfulCount > 0) return ReviewRunStatus.PartiallyApplied;@@ -264,9 +265,12 @@ const getRunStatus = (actions: MaintenanceReviewRunResult['actions']): ReviewRunreturn ReviewRunStatus.Completed;};-const getActionType = (toolName: string): MaintenanceActionPlan['actionType'] => {- if (toolName === 'createSkillIfAbsent') return 'create_skill';- if (toolName === 'replaceSkillContentCAS') return 'refine_skill';+const getActionType = (toolName: string): ActionPlan['actionType'] => {+ const normalizedToolName = normalizeProjectionToolName(toolName);++ if (normalizedToolName === 'writeMemory') return 'write_memory';+ if (normalizedToolName === 'createSkillIfAbsent') return 'create_skill';+ if (normalizedToolName === 'replaceSkillContentCAS') return 'refine_skill';return 'proposal_only';};@@ -276,12 +280,15 @@ const getWriteToolCalls = (toolCalls: ChatToolPayload[]) =>const getToolCallForOutcome = (writeToolCalls: ChatToolPayload[],- outcome: MaintenanceToolOutcome,+ outcome: ToolOutcome,cursors: Map<string, number>,) => {const startIndex = cursors.get(outcome.toolName) ?? 0;const matchingIndex = writeToolCalls.findIndex(- (toolCall, index) => index >= startIndex && toolCall.apiName === outcome.toolName,+ (toolCall, index) =>+ index >= startIndex &&+ normalizeProjectionToolName(toolCall.apiName) ===+ normalizeProjectionToolName(outcome.toolName),);if (matchingIndex === -1) return;@@ -331,6 +338,17 @@ const getSkillCreateOperation = (args: Record<string, unknown>, userId: string)operation: 'create' as const,});+const getMemoryWriteOperation = (args: Record<string, unknown>, userId: string) => {+ const content = getString(args.content);+ if (!content) return;++ return {+ domain: 'memory' as const,+ input: { content, userId },+ operation: 'write' as const,+ };+};+const getSkillRefineOperation = (args: Record<string, unknown>, userId: string) => {const skillDocumentId = getString(args.skillDocumentId);if (!skillDocumentId) return;@@ -347,20 +365,18 @@ const getSkillRefineOperation = (args: Record<string, unknown>, userId: string)};};-const toEvidenceRefs = (value: unknown): MaintenanceActionPlan['evidenceRefs'] =>+const toEvidenceRefs = (value: unknown): ActionPlan['evidenceRefs'] =>Array.isArray(value)? value.flatMap((item) => {const record = getRecord(item);const id = getString(record.id);const type = getString(record.type);- return id && type- ? [{ id, type: type as MaintenanceActionPlan['evidenceRefs'][number]['type'] }]- : [];+ return id && type ? [{ id, type: type as ActionPlan['evidenceRefs'][number]['type'] }] : [];}): [];-const toTarget = (value: unknown): MaintenanceActionTarget | undefined => {+const toTarget = (value: unknown): ActionTarget | undefined => {const record = getRecord(value);const memoryId = getString(record.memoryId);const skillDocumentId = getString(record.skillDocumentId);@@ -378,26 +394,24 @@ const toTarget = (value: unknown): MaintenanceActionTarget | undefined => {};const toRisk = (value: unknown) => {- if (value === MaintenanceRisk.High) return MaintenanceRisk.High;- if (value === MaintenanceRisk.Medium) return MaintenanceRisk.Medium;+ if (value === Risk.High) return Risk.High;+ if (value === Risk.Medium) return Risk.Medium;- return MaintenanceRisk.Low;+ return Risk.Low;};-const toApplyMode = (value: unknown, outcome: MaintenanceToolOutcome) => {- if (value === MaintenanceApplyMode.AutoApply) return MaintenanceApplyMode.AutoApply;- if (value === MaintenanceApplyMode.Skip) return MaintenanceApplyMode.Skip;- if (value === MaintenanceApplyMode.ProposalOnly) return MaintenanceApplyMode.ProposalOnly;+const toApplyMode = (value: unknown, outcome: ToolOutcome) => {+ if (value === ApplyMode.AutoApply) return ApplyMode.AutoApply;+ if (value === ApplyMode.Skip) return ApplyMode.Skip;+ if (value === ApplyMode.ProposalOnly) return ApplyMode.ProposalOnly;- return outcome.status === 'proposed'- ? MaintenanceApplyMode.ProposalOnly- : MaintenanceApplyMode.AutoApply;+ return outcome.status === 'proposed' ? ApplyMode.ProposalOnly : ApplyMode.AutoApply;};const toConfidence = (value: unknown) =>typeof value === 'number' && Number.isFinite(value) ? Math.min(1, Math.max(0, value)) : 1;-const toSkillOperation = (value: unknown, userId: string): MaintenanceActionPlan['operation'] => {+const toSkillOperation = (value: unknown, userId: string): ActionPlan['operation'] => {const record = getRecord(value);if (record.domain !== 'skill') return;@@ -454,7 +468,7 @@ const toSkillOperation = (value: unknown, userId: string): MaintenanceActionPlan}};-const getRawActionType = (value: unknown): MaintenanceActionPlan['actionType'] | undefined => {+const getRawActionType = (value: unknown): ActionPlan['actionType'] | undefined => {if (value === 'write_memory' ||value === 'create_skill' ||@@ -467,28 +481,17 @@ const getRawActionType = (value: unknown): MaintenanceActionPlan['actionType'] |}};-const getTargetDedupeKey = (- actionType: MaintenanceActionPlan['actionType'],- target: MaintenanceActionTarget | undefined,-) => {- if (target?.skillDocumentId) return `skill:${target.skillDocumentId}`;- if (target?.skillName) return `skill:${target.skillName}`;- if (target?.memoryId) return `memory:${target.memoryId}`;-- return actionType;-};-const getCompleteBaseSnapshot = ({actionType,baseSnapshot,operation,target,}: {- actionType: MaintenanceActionPlan['actionType'];- baseSnapshot: MaintenanceProposalBaseSnapshot | undefined;- operation: MaintenanceActionPlan['operation'];- target: MaintenanceActionTarget | undefined;-}): MaintenanceProposalBaseSnapshot | undefined => {+ actionType: ActionPlan['actionType'];+ baseSnapshot: SelfReviewProposalBaseSnapshot | undefined;+ operation: ActionPlan['operation'];+ target: ActionTarget | undefined;+}): SelfReviewProposalBaseSnapshot | undefined => {if (actionType === 'create_skill') {return {absent: true,@@ -517,10 +520,10 @@ const getProjectionActionFromRaw = ({}: {fallbackIdempotencyKey: string;index: number;- outcome: MaintenanceToolOutcome;+ outcome: ToolOutcome;rawAction: unknown;userId: string;-}): MaintenanceProposalPlan['actions'][number] | undefined => {+}): SelfReviewProposalPlan['actions'][number] | undefined => {const record = getRecord(rawAction);const actionType = getRawActionType(record.actionType);const idempotencyKey =@@ -539,10 +542,18 @@ const getProjectionActionFromRaw = ({const baseAction = {applyMode: toApplyMode(record.applyMode, outcome),confidence: toConfidence(record.confidence),- dedupeKey: getString(record.dedupeKey) ?? getTargetDedupeKey(actionType, target),+ dedupeKey:+ getString(record.dedupeKey) ??+ (target?.skillDocumentId+ ? `skill:${target.skillDocumentId}`+ : target?.skillName+ ? `skill:${target.skillName}`+ : target?.memoryId+ ? `memory:${target.memoryId}`+ : actionType),evidenceRefs: toEvidenceRefs(record.evidenceRefs),idempotencyKey,- rationale: getString(record.rationale) ?? outcome.summary ?? 'Maintenance proposal action.',+ rationale: getString(record.rationale) ?? outcome.summary ?? 'Self-review proposal action.',risk: toRisk(record.risk),...(operation ? { operation } : {}),...(target ? { target } : {}),@@ -556,6 +567,17 @@ const getProjectionActionFromRaw = ({};}+ if (actionType === 'write_memory') {+ return {+ ...baseAction,+ actionType,+ evidenceRefs: toEvidenceRefs(record.evidenceRefs),+ ...(getMemoryWriteOperation(record, userId)+ ? { operation: getMemoryWriteOperation(record, userId) }+ : {}),+ };+ }+if (actionType === 'refine_skill') {if (!baseSnapshot) return;@@ -581,7 +603,7 @@ const getIdeaFromRaw = ({fallbackIdempotencyKey: string;index: number;rawAction: unknown;-}): MaintenanceReviewIdea | undefined => {+}): SelfReviewIdea | undefined => {const record = getRecord(rawAction);if (getRawActionType(record.actionType) !== 'proposal_only') return;@@ -591,7 +613,7 @@ const getIdeaFromRaw = ({evidenceRefs: toEvidenceRefs(record.evidenceRefs),idempotencyKey:getString(record.idempotencyKey) ?? `${fallbackIdempotencyKey}:idea:${index + 1}`,- rationale: getString(record.rationale) ?? 'Maintenance self-review idea.',+ rationale: getString(record.rationale) ?? 'SelfIteration self-review idea.',risk: toRisk(record.risk),...(target ? { target } : {}),...(getString(record.title) ? { title: getString(record.title) } : {}),@@ -606,11 +628,11 @@ const getProjectionPayloadFromProposalArgs = ({}: {args: Record<string, unknown>;idempotencyKey: string;- outcome: MaintenanceToolOutcome;+ outcome: ToolOutcome;userId: string;-}): { actions: MaintenanceProposalPlan['actions']; ideas: MaintenanceReviewIdea[] } => {- const actions: MaintenanceProposalPlan['actions'] = [];- const ideas: MaintenanceReviewIdea[] = [];+}): { actions: SelfReviewProposalPlan['actions']; ideas: SelfReviewIdea[] } => {+ const actions: SelfReviewProposalPlan['actions'] = [];+ const ideas: SelfReviewIdea[] = [];if (Array.isArray(args.actions)) {for (const [index, rawAction] of args.actions.entries()) {@@ -649,25 +671,22 @@ const getProjectionAction = ({}: {args: Record<string, unknown>;idempotencyKey: string;- outcome: MaintenanceToolOutcome;+ outcome: ToolOutcome;toolName: string;userId: string;-}): MaintenanceProposalPlan['actions'][number] => {+}): SelfReviewProposalPlan['actions'][number] => {const actionType = getActionType(toolName);const skillDocumentId = getString(args.skillDocumentId) ?? outcome.resourceId;const skillName = getString(args.name);const baseSnapshot = getBaseSnapshot(args.baseSnapshot);const baseAction = {- applyMode:- outcome.status === 'proposed'- ? MaintenanceApplyMode.ProposalOnly- : MaintenanceApplyMode.AutoApply,+ applyMode: outcome.status === 'proposed' ? ApplyMode.ProposalOnly : ApplyMode.AutoApply,confidence: 1,dedupeKey: getString(args.proposalKey) ?? outcome.resourceId ?? idempotencyKey,evidenceRefs: [],idempotencyKey,- rationale: outcome.summary ?? 'Maintenance tool write outcome.',- risk: outcome.status === 'failed' ? MaintenanceRisk.Medium : MaintenanceRisk.Low,+ rationale: outcome.summary ?? 'Self-review tool write outcome.',+ risk: outcome.status === 'failed' ? Risk.Medium : Risk.Low,...(skillDocumentId || skillName? {target: {@@ -719,7 +738,7 @@ const getProjectionAction = ({** Use when:* - The nightly server runtime has write-tool outcomes instead of executor results- * - Daily Brief projection still expects `MaintenanceReviewRunResult` and `MaintenanceProposalPlan`+ * - Daily Brief projection still expects `RunResult` and `SelfReviewProposalPlan`** Expects:* - Runtime write outcomes and write tool calls are in execution order@@ -728,13 +747,11 @@ const getProjectionAction = ({* Returns:* - A completed/skipped/failed execution result plus a plan containing only confirmed tool writes*/-export const projectMaintenanceToolRuntimeRun = (- input: ProjectMaintenanceToolRuntimeRunInput,-): ProjectedMaintenanceToolRuntimeRun => {+export const projectRun = (input: ProjectRunInput): ProjectedRun => {const writeToolCalls = getWriteToolCalls(input.toolCalls);- const ideas: MaintenanceReviewIdea[] = [];- const projectionActions: MaintenanceProposalPlan['actions'] = [];- const executionActions: MaintenanceReviewRunResult['actions'] = [];+ const ideas: SelfReviewIdea[] = [];+ const projectionActions: SelfReviewProposalPlan['actions'] = [];+ const executionActions: RunResult['actions'] = [];const toolCallCursors = new Map<string, number>();for (const outcome of input.outcomes) {@@ -780,8 +797,8 @@ export const projectMaintenanceToolRuntimeRun = (idempotencyKey,...(outcome.receiptId ? { receiptId: outcome.receiptId } : {}),...(outcome.resourceId ? { resourceId: outcome.resourceId } : {}),- status: MaintenanceActionStatus.Skipped,- summary: outcome.summary ?? 'Maintenance proposal created self-review ideas.',+ status: ActionStatus.Skipped,+ summary: outcome.summary ?? 'Self-review proposal created self-review ideas.',});}continue;@@ -805,14 +822,14 @@ export const projectMaintenanceToolRuntimeRun = (});}- const projectionPlan: MaintenanceProposalPlan = {+ const projectionPlan: SelfReviewProposalPlan = {actions: projectionActions,...(input.localDate ? { localDate: input.localDate } : {}),- plannerVersion: 'maintenance-tool-first-runtime-v1',+ plannerVersion: 'shared-tool-first-runtime-v1',reviewScope: input.reviewScope,- summary: input.content?.trim() || 'Maintenance tool-first runtime completed.',+ summary: input.content?.trim() || 'Self-review tool-first runtime completed.',};- const execution: MaintenanceReviewRunResult = {+ const execution: RunResult = {actions: executionActions,sourceId: input.sourceId,status: getRunStatus(executionActions),diff --git a/src/server/services/agentSignal/policies/reviewNightly/__tests__/selfReflection.test.ts b/src/server/services/agentSignal/services/selfIteration/reflection/__test__/handler.test.tssimilarity index 67%rename from src/server/services/agentSignal/policies/reviewNightly/__tests__/selfReflection.test.tsrename to src/server/services/agentSignal/services/selfIteration/reflection/__test__/handler.test.tsindex 76fbea75f36..f2e7d76bd10 100644--- a/src/server/services/agentSignal/policies/reviewNightly/__tests__/selfReflection.test.ts+++ b/src/server/services/agentSignal/services/selfIteration/reflection/__test__/handler.test.ts@@ -4,33 +4,23 @@ import type { SourceAgentSelfReflectionRequested } from '@lobechat/agent-signal/import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';import { describe, expect, it, vi } from 'vitest';-import type { RuntimeProcessorContext } from '../../../runtime/context';+import { createDefaultAgentSignalPolicies } from '../../../../policies';+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 '../..';+} from '../../../../runtime/middleware';+import type { ExecuteSelfIterationResult } from '../../execute';+import { ReviewRunStatus, Scope } from '../../types';import type {CreateSelfReflectionSourceHandlerDependencies,SelfReflectionReviewContext,-} from '../selfReflection';+} from '../handler';import {createSelfReflectionSourceHandler,createSelfReflectionSourcePolicyHandler,-} from '../selfReflection';+} from '../handler';const reflectionPayload = {agentId: 'agent-1',@@ -83,54 +73,60 @@ const reflectionContext = {windowStart: reflectionPayload.windowStart,} satisfies SelfReflectionReviewContext;-const reflectionDraft = {+const runtimeResult = {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.' },+ result: {+ receiptId: 'runtime-receipt-1',+ resourceId: 'memory-1',+ status: 'applied',+ summary: 'Memory written.',+ },+ toolName: 'writeMemory',},],- findings: [],- summary: 'Task-scoped reflection found one durable preference.',-} satisfies MaintenancePlanDraft;--const reflectionPlan = {- actions: [+ content: 'Runtime reflection wrote one memory.',+ ideas: [],+ intents: [{- actionType: 'write_memory',- applyMode: MaintenanceApplyMode.AutoApply,- confidence: 0.9,- dedupeKey: 'memory:User prefers scoped task follow-up.',+ confidence: 0.82,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,+ idempotencyKey: `${reflectionSourceId}:intent:memory`,+ intentType: 'memory',+ mode: 'reflection',+ rationale: 'Capture the same-turn preference.',+ risk: 'low',+ urgency: 'soon',},],- plannerVersion: 'test-planner',- reviewScope: MaintenanceReviewScope.SelfReflection,- summary: 'Task-scoped reflection found one durable preference.',-} satisfies MaintenancePlan;--const executionResult = {- actions: [+ status: ReviewRunStatus.Completed,+ stepCount: 2,+ toolCalls: [{- idempotencyKey: `${reflectionSourceId}:write_memory:memory:User prefers scoped task follow-up.`,- receiptId: 'receipt-1',- status: MaintenanceActionStatus.Applied,- summary: 'Memory written.',+ apiName: 'writeMemory',+ arguments: JSON.stringify({+ content: 'User prefers scoped task follow-up.',+ evidenceRefs: [{ id: 'task-1', type: 'task' }],+ idempotencyKey: `${reflectionSourceId}:writeMemory:tool-call-1`,+ }),+ id: 'tool-call-1',+ identifier: 'agent-signal-self-iteration',+ type: 'builtin',},],- status: ReviewRunStatus.Completed,-} satisfies MaintenanceReviewRunResult;+ usage: [],+ writeOutcomes: [+ {+ result: {+ receiptId: 'runtime-receipt-1',+ resourceId: 'memory-1',+ status: 'applied',+ summary: 'Memory written.',+ },+ toolName: 'writeMemory',+ },+ ],+} satisfies ExecuteSelfIterationResult;const createDependencies = (overrides: Partial<CreateSelfReflectionSourceHandlerDependencies> = {},@@ -138,19 +134,111 @@ const createDependencies = (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),+ executeSelfIteration: vi.fn(async () => runtimeResult),+ maxSteps: 3,+ model: 'gpt-test',+ modelRuntime: { chat: vi.fn() },+ tools: {} as never,writeReceipt: vi.fn(async () => {}),...overrides,});describe('self-reflection source handler', () => {+ /**+ * @example+ * expect(deps.executeSelfIteration).toHaveBeenCalledWith(expect.objectContaining({ mode: 'reflection' }));+ * expect(deps.executeSelfIteration).toHaveBeenCalledWith(expect.objectContaining({ mode: 'reflection' }));+ */+ it('runs self-iteration executor for reflection and records reflection metadata on receipts', async () => {+ const deps = createDependencies({ writeReceipts: vi.fn(async () => {}) });+ const handler = createSelfReflectionSourceHandler(deps);++ const result = await handler.handle(createReflectionSource());++ expect(deps.executeSelfIteration).toHaveBeenCalledWith(+ expect.objectContaining({+ agentId: 'agent-1',+ context: reflectionContext,+ maxSteps: 3,+ mode: 'reflection',+ sourceId: reflectionSourceId,+ userId: 'user-1',+ window: {+ end: reflectionPayload.windowEnd,+ start: reflectionPayload.windowStart,+ },+ }),+ );+ expect(deps.writeReceipts).toHaveBeenCalledWith([+ expect.objectContaining({+ id: `${reflectionSourceId}:review-summary`,+ metadata: expect.objectContaining({+ selfIteration: expect.objectContaining({+ intents: runtimeResult.intents,+ mode: 'reflection',+ reason: 'failed_tool_count',+ sourceId: reflectionSourceId,+ }),+ }),+ }),+ expect.objectContaining({ id: `${reflectionSourceId}:writeMemory:tool-call-1:action` }),+ ]);+ expect(result).toEqual(+ expect.objectContaining({+ plannedActionCount: 1,+ planSummary: 'Runtime reflection wrote one memory.',+ status: ReviewRunStatus.Completed,+ }),+ );+ });++ /**+ * @example+ * expect(runtimeFactory.createRuntime).toHaveBeenCalledWith(expect.objectContaining({ context }));+ * expect(executeSelfIteration).toHaveBeenCalledWith(expect.objectContaining({ tools }));+ */+ it('builds self-iteration executor dependencies through the per-source runtime factory', async () => {+ const executeSelfIteration = vi.fn(async () => runtimeResult);+ const modelRuntime = { chat: vi.fn() };+ const tools = {} as never;+ const runtimeFactory = {+ createRuntime: vi.fn(async () => ({+ executeSelfIteration,+ maxSteps: 4,+ model: 'gpt-factory',+ modelRuntime,+ tools,+ })),+ };+ const deps = createDependencies({+ runtimeFactory,+ writeReceipts: vi.fn(async () => {}),+ });+ const handler = createSelfReflectionSourceHandler(deps);++ await handler.handle(createReflectionSource());++ expect(runtimeFactory.createRuntime).toHaveBeenCalledWith({+ context: reflectionContext,+ payload: reflectionPayload,+ source: expect.objectContaining({ sourceId: reflectionSourceId }),+ });+ expect(executeSelfIteration).toHaveBeenCalledWith(+ expect.objectContaining({+ maxSteps: 4,+ model: 'gpt-factory',+ modelRuntime,+ mode: 'reflection',+ tools,+ }),+ );+ });+/*** @example* expect(result.status).toBe('completed');*/- it('orchestrates scoped collector reviewer planner executor and receipt writer', async () => {+ it('orchestrates scoped collector self-iteration executor and receipt writer', async () => {const deps = createDependencies();const handler = createSelfReflectionSourceHandler(deps);@@ -180,31 +268,36 @@ describe('self-reflection source handler', () => {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`,+ expect(deps.executeSelfIteration).toHaveBeenCalledWith(+ expect.objectContaining({+ context: reflectionContext,+ mode: 'reflection',+ sourceId: reflectionSourceId,}),- plan: reflectionPlan,- reason: 'failed_tool_count',- scopeId: 'task-1',- scopeType: 'task',- sourceId: reflectionSourceId,- });+ );+ expect(deps.writeReceipt).toHaveBeenCalledWith(+ expect.objectContaining({+ execution: expect.objectContaining({+ status: runtimeResult.status,+ summaryReceiptId: `${reflectionSourceId}:review-summary`,+ }),+ intents: runtimeResult.intents,+ plan: expect.objectContaining({+ reviewScope: Scope.SelfReflection,+ summary: runtimeResult.content,+ }),+ 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 }),+ execution: expect.objectContaining({ status: runtimeResult.status }),plannedActionCount: 1,- planSummary: 'Task-scoped reflection found one durable preference.',+ planSummary: 'Runtime reflection wrote one memory.',sourceId: reflectionSourceId,status: ReviewRunStatus.Completed,userId: 'user-1',@@ -212,94 +305,6 @@ describe('self-reflection source handler', () => {);});- /**- * @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);@@ -310,12 +315,14 @@ describe('self-reflection source handler', () => {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.writeReceipts).toHaveBeenCalledWith(+ expect.arrayContaining([+ expect.objectContaining({ id: `${reflectionSourceId}:review-summary` }),+ expect.objectContaining({+ id: `${reflectionSourceId}:writeMemory:tool-call-1:action`,+ }),+ ]),+ );expect(deps.writeReceipt).toHaveBeenCalledTimes(1);expect('writeDailyBrief' in deps).toBe(false);});@@ -336,10 +343,9 @@ describe('self-reflection source handler', () => {const result = await handler.handle(createReflectionSource());- expect(deps.executePlan).toHaveBeenCalledWith(reflectionPlan);expect(result).toEqual(expect.objectContaining({- execution: expect.objectContaining({ status: executionResult.status }),+ execution: expect.objectContaining({ status: runtimeResult.status }),status: ReviewRunStatus.Completed,}),);@@ -369,8 +375,7 @@ describe('self-reflection source handler', () => {}),);expect(deps.collectContext).not.toHaveBeenCalled();- expect(deps.runMaintenanceReviewAgent).not.toHaveBeenCalled();- expect(deps.executePlan).not.toHaveBeenCalled();+ expect(deps.executeSelfIteration).not.toHaveBeenCalled();expect(deps.writeReceipt).not.toHaveBeenCalled();});@@ -512,7 +517,7 @@ describe('self-reflection source handler', () => {expect(selfReflectionHandler).toEqual(expect.objectContaining({- id: `${AGENT_SIGNAL_SOURCE_TYPES.agentSelfReflectionRequested}:maintenance-review`,+ id: `${AGENT_SIGNAL_SOURCE_TYPES.agentSelfReflectionRequested}:shared-review`,type: 'source',}),);diff --git a/src/server/services/agentSignal/services/selfIteration/reflection/__test__/server.test.ts b/src/server/services/agentSignal/services/selfIteration/reflection/__test__/server.test.tsnew file mode 100644index 00000000000..afedb7ff753--- /dev/null+++ b/src/server/services/agentSignal/services/selfIteration/reflection/__test__/server.test.ts@@ -0,0 +1,76 @@+// @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 { LobeChatDatabase } from '@/database/type';++import type { SelfReflectionReviewContext } from '../handler';+import { createServerSelfReflectionPolicyOptions } from '../server';++const mocks = vi.hoisted(() => ({+ initModelRuntimeFromDB: vi.fn(async () => ({ chat: vi.fn() })),+}));++vi.mock('@/server/modules/ModelRuntime', () => ({+ initModelRuntimeFromDB: mocks.initModelRuntimeFromDB,+}));++const payload = {+ agentId: 'agent-1',+ reason: 'tool_failed',+ scopeId: 'topic-1',+ scopeType: 'topic',+ topicId: 'topic-1',+ userId: 'user-1',+ windowEnd: '2026-05-11T01:00:00.000Z',+ windowStart: '2026-05-11T00:00:00.000Z',+} as const;++const source = createSource({+ payload,+ scope: { agentId: 'agent-1', userId: 'user-1' },+ scopeKey: 'topic:topic-1',+ sourceId: 'self-reflection:user-1:agent-1:topic:topic-1',+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentSelfReflectionRequested,+ timestamp: 100,+}) as SourceAgentSelfReflectionRequested;++const context = {+ ...payload,+ evidenceRefs: [{ id: 'topic-1', type: 'topic' }],+ topics: [],+} satisfies SelfReflectionReviewContext;++describe('createServerSelfReflectionPolicyOptions', () => {+ /**+ * @example+ * expect(runtime.tools).toEqual(expect.objectContaining({ writeMemory: expect.any(Function) }));+ */+ it('builds source-scoped self-iteration executor runtime and disables legacy planner execution', async () => {+ const options = createServerSelfReflectionPolicyOptions({+ agentId: 'agent-1',+ db: {} as unknown as LobeChatDatabase,+ selfIterationEnabled: true,+ userId: 'user-1',+ });++ const runtime = await options.runtimeFactory?.createRuntime({ context, payload, source });++ expect(mocks.initModelRuntimeFromDB).toHaveBeenCalledOnce();+ expect(runtime).toEqual(+ expect.objectContaining({+ executeSelfIteration: expect.any(Function),+ model: expect.any(String),+ modelRuntime: expect.objectContaining({ chat: expect.any(Function) }),+ tools: expect.objectContaining({+ getEvidenceDigest: expect.any(Function),+ writeMemory: expect.any(Function),+ }),+ }),+ );+ expect('planReviewOutput' in options).toBe(false);+ expect('executePlan' in options).toBe(false);+ });+});diff --git a/src/server/services/agentSignal/policies/reviewNightly/selfReflection.ts b/src/server/services/agentSignal/services/selfIteration/reflection/handler.tssimilarity index 66%rename from src/server/services/agentSignal/policies/reviewNightly/selfReflection.tsrename to src/server/services/agentSignal/services/selfIteration/reflection/handler.tsindex 2f626835835..9e85da5606c 100644--- a/src/server/services/agentSignal/policies/reviewNightly/selfReflection.ts+++ b/src/server/services/agentSignal/services/selfIteration/reflection/handler.ts@@ -1,20 +1,15 @@import type { SourceAgentSelfReflectionRequested } from '@lobechat/agent-signal/source';import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';+import type { ModelRuntime } from '@lobechat/model-runtime';-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';+import { defineSourceHandler } from '../../../runtime/middleware';+import type { AgentSignalReceipt } from '../../receiptService';+import { createSelfFeedbackReceipts } from '../../receiptService';+import type { ExecuteSelfIterationInput, ExecuteSelfIterationResult } from '../execute';+import { projectRun } from '../projection';+import type { ToolSet } from '../tools/shared';+import type { Idea, Plan, RunResult, SelfFeedbackIntent } from '../types';+import { buildSelfReflectionSourceId, ReviewRunStatus, Scope } from '../types';/** Runtime scope supported by self-reflection source handlers. */export type SelfReflectionSourceScopeType = 'operation' | 'task' | 'topic';@@ -88,13 +83,17 @@ export interface SelfReflectionReviewContext extends CollectSelfReflectionContex}/**- * Receipt input emitted after one self-reflection maintenance execution.+ * Receipt input emitted after one self-reflection shared execution.*/export interface SelfReflectionReceiptInput {/** Executor result for the completed self-reflection run. */- execution: MaintenanceReviewRunResult;- /** Normalized maintenance plan sent to the executor. */- plan: MaintenancePlan;+ execution: RunResult;+ /** Non-actionable ideas captured by the self-iteration runtime. */+ ideas?: Idea[];+ /** Immediate intents captured by the self-iteration runtime. */+ intents?: SelfFeedbackIntent[];+ /** Normalized self-iteration plan sent to the executor. */+ plan: Plan;/** Stable reason that requested reflection. */reason: string;/** Runtime scope id reviewed by the run. */@@ -105,6 +104,48 @@ export interface SelfReflectionReceiptInput {sourceId: string;}+/**+ * Input passed to a reflection runtime factory before one self-iteration run.+ */+export interface SelfReflectionRuntimeFactoryInput {+ /** Source-scoped evidence context collected for this reflection. */+ context: SelfReflectionReviewContext;+ /** Validated source payload that requested reflection. */+ payload: SelfReflectionSourcePayload;+ /** Original source event being handled. */+ source: SourceAgentSelfReflectionRequested;+}++/**+ * Per-run runtime dependencies for the self-iteration executor.+ */+export interface SelfReflectionRuntimeConfig {+ /** Runs the self-iteration executor. */+ executeSelfIteration: (input: ExecuteSelfIterationInput) => Promise<ExecuteSelfIterationResult>;+ /**+ * Maximum self-iteration runtime steps.+ *+ * @default 10+ */+ maxSteps?: number;+ /** Model name used by the self-iteration runtime. */+ model: string;+ /** Model runtime used by the self-iteration runtime. */+ modelRuntime: Pick<ModelRuntime, 'chat'>;+ /** Source-scoped safe tools exposed to the self-iteration runtime. */+ tools: ToolSet;+}++/**+ * Class-backed boundary that creates source-scoped runtime dependencies.+ */+export interface SelfReflectionRuntimeFactory {+ /** Builds the model/runtime/tools bundle for one reflection source. */+ createRuntime: (+ input: SelfReflectionRuntimeFactoryInput,+ ) => Promise<SelfReflectionRuntimeConfig> | SelfReflectionRuntimeConfig;+}+/*** Result returned by the self-reflection source handler.*/@@ -112,10 +153,10 @@ export interface SelfReflectionSourceHandlerResult extends Record<string, unknow/** Stable agent id being reviewed when payload validation succeeds. */agentId?: string;/** Executor result for completed runs. */- execution?: MaintenanceReviewRunResult;+ execution?: RunResult;/** Stable guard key used for idempotency when payload validation succeeds. */guardKey?: string;- /** Number of planned maintenance actions before execution. */+ /** Number of planned self-review actions before execution. */plannedActionCount?: number;/** Planner summary for receipt construction. */planSummary?: string;@@ -145,18 +186,26 @@ export interface CreateSelfReflectionSourceHandlerDependencies {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. */+ /** Collects only source-scoped evidence without mutating shared 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>;+ /** Runs the self-iteration runtime when no source-scoped factory is injected. */+ executeSelfIteration?: (input: ExecuteSelfIterationInput) => Promise<ExecuteSelfIterationResult>;+ /**+ * Maximum self-iteration runtime steps.+ *+ * @default 10+ */+ maxSteps?: number;+ /** Model name used by the self-iteration runtime. */+ model?: string;+ /** Model runtime used by the self-iteration runtime. */+ modelRuntime?: Pick<ModelRuntime, 'chat'>;+ /** Builds source-scoped shared-runtime dependencies for reflection mode. */+ runtimeFactory?: SelfReflectionRuntimeFactory;+ /** Safe tools exposed to the self-iteration runtime. */+ tools?: ToolSet;/** 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. */@@ -272,9 +321,9 @@ const writeSelfReflectionReceipts = async (};const applyReceiptIdsToExecution = (- execution: MaintenanceReviewRunResult,+ execution: RunResult,receipts: AgentSignalReceipt[],-): MaintenanceReviewRunResult => {+): RunResult => {const receiptByActionKey = new Map(receipts.filter((receipt) => receipt.id.endsWith(':action'))@@ -293,6 +342,87 @@ const applyReceiptIdsToExecution = (};};+const canExecuteSharedSelfIteration = (+ deps: CreateSelfReflectionSourceHandlerDependencies,+): deps is CreateSelfReflectionSourceHandlerDependencies & {+ executeSelfIteration: (input: ExecuteSelfIterationInput) => Promise<ExecuteSelfIterationResult>;+ model: string;+ modelRuntime: Pick<ModelRuntime, 'chat'>;+ tools: ToolSet;+} => Boolean(deps.executeSelfIteration && deps.model && deps.modelRuntime && deps.tools);++const runSharedSelfReflection = async ({+ context,+ payload,+ runtime,+ source,+}: {+ context: SelfReflectionReviewContext;+ payload: SelfReflectionSourcePayload;+ runtime: SelfReflectionRuntimeConfig;+ source: SourceAgentSelfReflectionRequested;+}) => {+ const runtimeResult = await runtime.executeSelfIteration({+ agentId: payload.agentId,+ context,+ maxSteps: runtime.maxSteps ?? 10,+ mode: 'reflection',+ model: runtime.model,+ modelRuntime: runtime.modelRuntime,+ sourceId: source.sourceId,+ tools: runtime.tools,+ userId: payload.userId,+ window: {+ end: payload.windowEnd,+ start: payload.windowStart,+ },+ });+ const projected = projectRun({+ content: runtimeResult.content,+ outcomes: runtimeResult.writeOutcomes.map((outcome) => ({+ ...outcome.result,+ toolName: outcome.toolName,+ })),+ reviewScope: Scope.SelfReflection,+ sourceId: source.sourceId,+ toolCalls: runtimeResult.toolCalls,+ userId: payload.userId,+ });++ return {+ execution: projected.execution,+ ideas: runtimeResult.ideas,+ plan: projected.projectionPlan,+ runtimeIntents: runtimeResult.intents,+ };+};++const resolveSharedSelfReflectionRuntime = async ({+ context,+ deps,+ payload,+ source,+}: {+ context: SelfReflectionReviewContext;+ deps: CreateSelfReflectionSourceHandlerDependencies;+ payload: SelfReflectionSourcePayload;+ source: SourceAgentSelfReflectionRequested;+}): Promise<SelfReflectionRuntimeConfig | undefined> => {+ if (deps.runtimeFactory) {+ return deps.runtimeFactory.createRuntime({ context, payload, source });+ }++ if (!canExecuteSharedSelfIteration(deps)) return;++ return {+ executeSelfIteration: deps.executeSelfIteration,+ maxSteps: deps.maxSteps,+ model: deps.model,+ modelRuntime: deps.modelRuntime,+ tools: deps.tools,+ };+};+/*** Creates the DI-friendly handler for self-reflection request sources.*@@ -306,16 +436,16 @@ const applyReceiptIdsToExecution = (* - `agent.self_reflection.requested`** Downstream:- * - injected `executePlan`+ * - injected self-iteration executor* - 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+ * - Runtime policy composition needs a side-effect boundary before executing self-iteration plans** Expects:* - `source` is an `agent.self_reflection.requested` source with service-produced payload- * - Dependencies enforce gates, idempotency, reviewer limits, executor persistence, and receipts+ * - Dependencies enforce gates, idempotency, executor persistence, and receipts** Returns:* - A run result with status and enough plan metadata for self-reflection receipts@@ -363,15 +493,15 @@ export const createSelfReflectionSourceHandler = (}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({+ const runtime = await resolveSharedSelfReflectionRuntime({ context, deps, payload, source });++ if (!runtime) throw new Error('Self-reflection self-iteration runtime is required.');++ const runtimeRun = await runSharedSelfReflection({ context, payload, runtime, source });+ const plan: Plan = runtimeRun.plan;+ const execution: RunResult = runtimeRun.execution;++ const receipts = createSelfFeedbackReceipts({agentId: payload.agentId,createdAt: source.timestamp,plan,@@ -379,6 +509,15 @@ export const createSelfReflectionSourceHandler = (...execution,sourceId: source.sourceId,},+ selfIteration: {+ ideas: runtimeRun.ideas,+ intents: runtimeRun.runtimeIntents,+ mode: 'reflection',+ reason: payload.reason,+ scope: { id: payload.scopeId, type: payload.scopeType },+ sourceId: source.sourceId,+ window: { end: payload.windowEnd, start: payload.windowStart },+ },scopeId: payload.scopeId,scopeType: payload.scopeType,sourceId: source.sourceId,@@ -398,6 +537,8 @@ export const createSelfReflectionSourceHandler = (await writeSelfReflectionReceipt(deps, {execution: executionWithReceipts,+ ideas: runtimeRun?.ideas,+ intents: runtimeRun?.runtimeIntents,plan,reason: payload.reason,scopeId: payload.scopeId,@@ -447,7 +588,7 @@ export const createSelfReflectionSourcePolicyHandler = (return defineSourceHandler(AGENT_SIGNAL_SOURCE_TYPES.agentSelfReflectionRequested,- `${AGENT_SIGNAL_SOURCE_TYPES.agentSelfReflectionRequested}:maintenance-review`,+ `${AGENT_SIGNAL_SOURCE_TYPES.agentSelfReflectionRequested}:shared-review`,async (source: SourceAgentSelfReflectionRequested) => {const result = await handler.handle(source);diff --git a/src/server/services/agentSignal/services/selfIteration/reflection/server.ts b/src/server/services/agentSignal/services/selfIteration/reflection/server.tsnew file mode 100644index 00000000000..b5407928015--- /dev/null+++ b/src/server/services/agentSignal/services/selfIteration/reflection/server.ts@@ -0,0 +1,636 @@+import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';+import { DEFAULT_MINI_SYSTEM_AGENT_ITEM } from '@lobechat/const';++import { AgentSignalReviewContextModel } from '@/database/models/agentSignal/reviewContext';+import { BriefModel } from '@/database/models/brief';+import type { LobeChatDatabase } from '@/database/type';+import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';+import { AGENT_SIGNAL_DEFAULTS } from '@/server/services/agentSignal/constants';+import { runMemoryActionAgent } from '@/server/services/agentSignal/policies/analyzeIntent/actions/userMemory';+import {+ createDurableSelfReflectionAccumulator,+ createProcedurePolicyOptions,+} from '@/server/services/agentSignal/procedure';+import { redisPolicyStateStore } from '@/server/services/agentSignal/store/adapters/redis/policyStateStore';+import { redisSourceEventStore } from '@/server/services/agentSignal/store/adapters/redis/sourceEventStore';+import { SkillManagementDocumentService } from '@/server/services/skillManagement';++import { persistAgentSignalReceipts } from '../../receiptService';+import { createSelfReflectionService } from '../../selfReflection';+import { executeSelfIteration } from '../execute';+import { createSelfReviewProposalPreflightService } from '../review/proposalPreflight';+import { createSelfReviewProposalSnapshotService } from '../review/proposalSnapshot';+import type { CreateServerSelfIterationPolicyOptions } from '../server';+import { canRunSelfIterationSource, listServerSelfReviewProposalActivity } from '../server';+import type {+ OperationReservation,+ ReplaceSkillContentCASInput,+ ToolReceiptInput,+ ToolWriteResult,+} from '../tools/shared';+import { createMemoryService, createSkillManagementService, createToolSet } from '../tools/shared';+import { Risk } from '../types';+import type {+ CollectSelfReflectionContextInput,+ CreateSelfReflectionSourceHandlerDependencies,+ SelfReflectionReviewContext,+ SelfReflectionRuntimeFactory,+} from './handler';++const SELF_REFLECTION_OPERATION_STATE_TTL_SECONDS = AGENT_SIGNAL_DEFAULTS.receiptTtlSeconds;++const selfReflectionOperationScopeKey = (idempotencyKey: string) =>+ `self-reflection-operation:${idempotencyKey}`;++const selfReflectionOperationReserveKey = (idempotencyKey: string) =>+ `self-reflection-operation-reserve:${idempotencyKey}`;++const parseStoredOperationResult = (+ payload: Record<string, string> | undefined,+): ToolWriteResult | undefined => {+ if (!payload?.result) return;++ try {+ const result = JSON.parse(payload.result) as ToolWriteResult;++ if (+ result.status === 'applied' ||+ result.status === 'deduped' ||+ result.status === 'failed' ||+ result.status === 'proposed' ||+ result.status === 'skipped_stale' ||+ result.status === 'skipped_unsupported'+ ) {+ return result;+ }+ } catch {+ return;+ }+};++const reserveSelfReflectionOperation = async (+ idempotencyKey: string,+): Promise<OperationReservation> => {+ const scopeKey = selfReflectionOperationScopeKey(idempotencyKey);+ const existing = parseStoredOperationResult(await redisSourceEventStore.readWindow(scopeKey));++ if (existing) return { existing, reserved: false };++ const reserved = await redisSourceEventStore.tryDedupe(+ selfReflectionOperationReserveKey(idempotencyKey),+ SELF_REFLECTION_OPERATION_STATE_TTL_SECONDS,+ );++ if (reserved) return { reserved: true };++ return {+ existing: parseStoredOperationResult(await redisSourceEventStore.readWindow(scopeKey)) ?? {+ status: 'skipped_unsupported',+ summary:+ 'Self-reflection operation is already reserved or Redis is unavailable; skipped to avoid duplicate mutation.',+ },+ reserved: false,+ };+};++const completeSelfReflectionOperation = async (input: ToolReceiptInput) => {+ await redisSourceEventStore.writeWindow(+ selfReflectionOperationScopeKey(input.idempotencyKey),+ {+ result: JSON.stringify({+ ...(input.receiptId ? { receiptId: input.receiptId } : {}),+ ...(input.resourceId ? { resourceId: input.resourceId } : {}),+ status: input.status,+ ...(input.summary ? { summary: input.summary } : {}),+ } satisfies ToolWriteResult),+ },+ SELF_REFLECTION_OPERATION_STATE_TTL_SECONDS,+ );+};++const getToolReceiptStatus = (+ status: ToolReceiptInput['status'],+): 'applied' | 'failed' | 'proposed' | 'skipped' => {+ if (status === 'applied') return 'applied';+ if (status === 'failed') return 'failed';+ if (status === 'proposed') return 'proposed';++ return 'skipped';+};++const writeSelfReflectionToolReceipt = async ({+ agentId,+ input,+ sourceId,+ userId,+}: {+ agentId: string;+ input: ToolReceiptInput;+ sourceId: string;+ userId: string;+}) => {+ await persistAgentSignalReceipts([+ {+ agentId,+ createdAt: Date.now(),+ detail:+ input.summary ?? `Self-reflection tool ${input.toolName} finished with ${input.status}.`,+ id: input.idempotencyKey,+ kind:+ input.toolName === 'createSkillIfAbsent' || input.toolName === 'replaceSkillContentCAS'+ ? 'skill'+ : 'review',+ metadata: {+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentSelfReflectionRequested,+ },+ sourceId,+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentSelfReflectionRequested,+ status: getToolReceiptStatus(input.status),+ ...(input.resourceId &&+ (input.toolName === 'createSkillIfAbsent' || input.toolName === 'replaceSkillContentCAS')+ ? {+ target: {+ id: input.resourceId,+ ...(input.summary ? { summary: input.summary } : {}),+ title: input.summary ?? input.resourceId,+ type: 'skill',+ },+ }+ : {}),+ title: input.summary ?? 'Self-reflection tool outcome',+ topicId: sourceId,+ userId,+ },+ ]);++ return { receiptId: input.idempotencyKey };+};++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,+ })),+ };+};++const toReadonlyArray = (value: unknown): readonly unknown[] => (Array.isArray(value) ? value : []);++const createReflectionEvidenceDigest = ({+ context,+ evidenceIds,+}: {+ context: SelfReflectionReviewContext;+ evidenceIds?: string[];+}) => {+ const selectedEvidenceIds = new Set(evidenceIds ?? []);+ const includeAll = selectedEvidenceIds.size === 0;+ const topics = toReadonlyArray(context.topics).filter((topic) => {+ if (includeAll) return true;+ if (!topic || typeof topic !== 'object') return false;++ const refs = 'evidenceRefs' in topic ? toReadonlyArray(topic.evidenceRefs) : [];++ return refs.some(+ (ref) =>+ ref &&+ typeof ref === 'object' &&+ 'id' in ref &&+ typeof ref.id === 'string' &&+ selectedEvidenceIds.has(ref.id),+ );+ });++ return {+ evidenceRefs: context.evidenceRefs,+ scope: {+ id: context.scopeId,+ type: context.scopeType,+ },+ topics,+ };+};++const createReflectionRuntimeTools = ({+ agentId,+ briefModel,+ context,+ db,+ skillDocumentService,+ sourceId,+ userId,+}: {+ agentId: string;+ briefModel: BriefModel;+ context: SelfReflectionReviewContext;+ db: LobeChatDatabase;+ skillDocumentService: SkillManagementDocumentService;+ sourceId: string;+ userId: string;+}) => {+ const proposalPreflight = createSelfReviewProposalPreflightService({+ isSkillNameAvailable: async ({ agentId: targetAgentId, name }) => {+ const skills = await skillDocumentService.listSkills({ agentId: targetAgentId ?? agentId });++ return !skills.some((skill) => skill.name === name);+ },+ readSkillTargetSnapshot: (skillDocumentId) =>+ skillDocumentService.readSkillTargetSnapshot({+ agentDocumentId: skillDocumentId,+ agentId,+ }),+ });+ const proposalSnapshot = createSelfReviewProposalSnapshotService({+ isSkillNameAvailable: async ({ agentId: targetAgentId, name }) => {+ const skills = await skillDocumentService.listSkills({ agentId: targetAgentId ?? agentId });++ return !skills.some((skill) => skill.name === name);+ },+ readSkillTargetSnapshot: (skillDocumentId) =>+ skillDocumentService.readSkillTargetSnapshot({+ agentDocumentId: skillDocumentId,+ agentId,+ }),+ });+ const skillService = createSkillManagementService({+ createSkill: async ({ input }) => {+ const result = await skillDocumentService.createSkill({+ agentId,+ bodyMarkdown: input.bodyMarkdown ?? '',+ description: input.description ?? 'Agent Signal managed skill.',+ name: input.name ?? input.title ?? 'agent-signal-skill',+ title: input.title ?? input.name ?? 'Agent Signal skill',+ });++ return {+ skillDocumentId: result.bundle.agentDocumentId,+ summary: `Created managed skill ${result.name}.`,+ };+ },+ refineSkill: async ({ input }) => {+ const result = await skillDocumentService.replaceSkillIndex({+ agentDocumentId: input.skillDocumentId,+ agentId,+ bodyMarkdown: input.bodyMarkdown ?? '',+ });++ if (!result) throw new Error('Skill target not found');++ return {+ skillDocumentId: result.bundle.agentDocumentId,+ summary: `Refined managed skill ${result.name}.`,+ };+ },+ });++ return createToolSet({+ completeOperation: completeSelfReflectionOperation,+ completeReplaceSkillInput: async (input: ReplaceSkillContentCASInput) => {+ const baseSnapshot = await proposalSnapshot.captureActionSnapshot({+ actionType: 'refine_skill',+ agentId,+ input: { skillDocumentId: input.skillDocumentId },+ userId,+ });++ return {+ ...input,+ baseSnapshot,+ skillDocumentId: baseSnapshot.agentDocumentId ?? input.skillDocumentId,+ };+ },+ createSkill: async (input) => {+ const result = await skillService.createSkill({+ evidenceRefs: [],+ idempotencyKey: input.idempotencyKey,+ input,+ });++ return {+ resourceId: result.skillDocumentId,+ summary: result.summary,+ };+ },+ getEvidenceDigest: async ({ evidenceIds }) =>+ createReflectionEvidenceDigest({ context, evidenceIds }),+ getManagedSkill: ({ agentId: targetAgentId, skillDocumentId }) =>+ skillDocumentService.getSkill({+ agentDocumentId: skillDocumentId,+ agentId: targetAgentId,+ includeContent: true,+ }),+ listSelfReviewProposals: ({ agentId: targetAgentId }) =>+ listServerSelfReviewProposalActivity({+ agentId: targetAgentId,+ briefModel,+ userId,+ }).then((digest) => [digest]),+ listManagedSkills: ({ agentId: targetAgentId }) =>+ skillDocumentService.listSkills({ agentId: targetAgentId }),+ preflight: async (input) => {+ if ('skillDocumentId' in input) {+ const preflight = await proposalPreflight.checkAction({+ actionType: 'refine_skill',+ baseSnapshot: input.baseSnapshot,+ evidenceRefs: [],+ idempotencyKey: input.idempotencyKey,+ operation: {+ domain: 'skill',+ input: {+ bodyMarkdown: input.bodyMarkdown,+ patch: input.summary,+ skillDocumentId: input.skillDocumentId,+ userId: input.userId,+ },+ operation: 'refine',+ },+ rationale: input.summary ?? `Refine managed skill ${input.skillDocumentId}.`,+ risk: Risk.Low,+ target: { skillDocumentId: input.skillDocumentId },+ });++ return preflight.allowed ? { allowed: true } : { allowed: false, reason: preflight.reason };+ }++ return { allowed: true };+ },+ readProposal: async ({ proposalId, proposalKey }) => {+ const digest = await listServerSelfReviewProposalActivity({ agentId, briefModel, userId });++ return digest.active.find(+ (proposal) =>+ (proposalId && proposal.proposalId === proposalId) ||+ (proposalKey && proposal.proposalKey === proposalKey),+ );+ },+ replaceSkill: async (input) => {+ const result = await skillService.refineSkill({+ evidenceRefs: [],+ idempotencyKey: input.idempotencyKey,+ input,+ });++ return {+ resourceId: result.skillDocumentId,+ summary: result.summary,+ };+ },+ reserveOperation: reserveSelfReflectionOperation,+ writeMemory: async (input) => {+ const memoryService = createMemoryService({+ writeMemory: async ({ content, evidenceRefs, idempotencyKey }) => {+ const result = await runMemoryActionAgent(+ {+ agentId,+ message: content,+ reason: `Agent Signal self-reflection memory candidate from ${evidenceRefs.length} evidence refs.`,+ },+ {+ db,+ 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,+ };+ },+ });+ const result = await memoryService.writeMemory({+ evidenceRefs: input.evidenceRefs,+ idempotencyKey: input.idempotencyKey,+ input: {+ content: input.content,+ userId: input.userId,+ },+ });++ return {+ resourceId: result.memoryId,+ summary: result.summary,+ };+ },+ writeReceipt: (input) => writeSelfReflectionToolReceipt({ agentId, input, sourceId, userId }),+ });+};++/**+ * Creates source-scoped runtime dependencies for server self-reflection runs.+ *+ * Call stack:+ *+ * createServerSelfReflectionPolicyOptions+ * -> {@link SelfReflectionServerRuntimeFactory.createRuntime}+ * -> {@link executeSelfIteration}+ * -> self-reflection tools and receipt persistence+ *+ * Use when:+ * - The Agent Signal workflow consumes `agent.self_reflection.requested`+ * - Reflection needs source-scoped evidence tools rather than nightly brief proposal tools+ *+ * Expects:+ * - `context` was collected for the same source payload+ * - Tools are scoped to one user/agent/source id+ *+ * Returns:+ * - Model runtime, toolset, and executor callback for one reflection run+ */+export class SelfReflectionServerRuntimeFactory implements SelfReflectionRuntimeFactory {+ constructor(+ private readonly input: {+ agentId: string;+ briefModel: BriefModel;+ db: LobeChatDatabase;+ skillDocumentService: SkillManagementDocumentService;+ userId: string;+ },+ ) {}++ async createRuntime({+ context,+ source,+ }: Parameters<SelfReflectionRuntimeFactory['createRuntime']>[0]) {+ const modelRuntime = await initModelRuntimeFromDB(+ this.input.db,+ this.input.userId,+ DEFAULT_MINI_SYSTEM_AGENT_ITEM.provider,+ );++ return {+ executeSelfIteration,+ model: DEFAULT_MINI_SYSTEM_AGENT_ITEM.model,+ modelRuntime,+ tools: createReflectionRuntimeTools({+ agentId: this.input.agentId,+ briefModel: this.input.briefModel,+ context,+ db: this.input.db,+ skillDocumentService: this.input.skillDocumentService,+ sourceId: source.sourceId,+ userId: this.input.userId,+ }),+ };+ }+}++/**+ * Creates server runtime handlers for immediate self-feedback reflection sources.+ *+ * Call stack:+ *+ * runAgentSignalWorkflow+ * -> {@link createServerSelfReflectionPolicyOptions}+ * -> reflection source handler dependencies+ * -> {@link SelfReflectionServerRuntimeFactory}+ *+ * Use when:+ * - The Agent Signal workflow consumes `agent.self_reflection.requested`+ * - Runtime policy composition needs scoped collection, self-iteration 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,+}: CreateServerSelfIterationPolicyOptions): CreateSelfReflectionSourceHandlerDependencies => {+ const reviewContextModel = new AgentSignalReviewContextModel(db, userId);+ const briefModel = new BriefModel(db, userId);+ const skillDocumentService = new SkillManagementDocumentService(db, userId);+ const targetAgentId = agentId ?? '';++ return {+ acquireReviewGuard: (input) =>+ redisSourceEventStore.tryDedupe(+ `self-reflection-guard:${input.guardKey}`,+ AGENT_SIGNAL_DEFAULTS.receiptTtlSeconds,+ ),+ canRunReview: async (input) => {+ if (input.userId !== userId) return false;++ return canRunSelfIterationSource({+ agentId: input.agentId,+ expectedAgentId: agentId,+ reviewContextModel,+ selfIterationEnabled,+ });+ },+ collectContext: (input) => collectSelfReflectionContext(reviewContextModel, input),+ runtimeFactory: new SelfReflectionServerRuntimeFactory({+ agentId: targetAgentId,+ briefModel,+ db,+ skillDocumentService,+ userId,+ }),+ writeReceipt: async () => {},+ writeReceipts: (receipts) => persistAgentSignalReceipts(receipts),+ };+};++/**+ * Creates server procedure policy options with fast-loop self-reflection enabled.+ *+ * Call stack:+ *+ * runAgentSignalWorkflow+ * -> {@link createServerProcedurePolicyOptions}+ * -> {@link createProcedurePolicyOptions}+ * -> durable weak-signal self-reflection accumulator+ *+ * 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 procedure-aware Agent Signal policies+ */+export const createServerProcedurePolicyOptions = ({+ agentId,+ db,+ selfIterationEnabled = false,+ userId,+}: CreateServerSelfIterationPolicyOptions) => {+ 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 canRunSelfIterationSource({+ 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,+ });+};diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/brief.test.ts b/src/server/services/agentSignal/services/selfIteration/review/__test__/brief.test.tssimilarity index 80%rename from src/server/services/agentSignal/services/maintenance/__tests__/brief.test.tsrename to src/server/services/agentSignal/services/selfIteration/review/__test__/brief.test.tsindex 43d1da0a0a2..700c0b4080a 100644--- a/src/server/services/agentSignal/services/maintenance/__tests__/brief.test.ts+++ b/src/server/services/agentSignal/services/selfIteration/review/__test__/brief.test.ts@@ -3,14 +3,8 @@ import { afterEach, describe, expect, it, vi } from 'vitest';import { BriefModel } from '@/database/models/brief';-import { createBriefMaintenanceService, createServerMaintenanceBriefWriter } from '../brief';-import {- MaintenanceActionStatus,- MaintenanceApplyMode,- MaintenanceReviewScope,- MaintenanceRisk,- ReviewRunStatus,-} from '../types';+import { ActionStatus, ApplyMode, ReviewRunStatus, Risk, Scope } from '../../types';+import { createBriefSelfReviewService, createServerSelfReviewBriefWriter } from '../brief';afterEach(() => {vi.restoreAllMocks();@@ -26,20 +20,20 @@ const completeRefineSkillBaseSnapshot = (agentDocumentId: string) => ({});const getNightlySelfReview = (- brief: ReturnType<ReturnType<typeof createBriefMaintenanceService>['projectNightlyReviewBrief']>,+ brief: ReturnType<ReturnType<typeof createBriefSelfReviewService>['projectNightlyReviewBrief']>,) => brief?.metadata.agentSignal.nightlySelfReview;-const getMaintenanceProposal = (- brief: ReturnType<ReturnType<typeof createBriefMaintenanceService>['projectNightlyReviewBrief']>,-) => getNightlySelfReview(brief)?.maintenanceProposal;+const getSelfReviewProposal = (+ brief: ReturnType<ReturnType<typeof createBriefSelfReviewService>['projectNightlyReviewBrief']>,+) => getNightlySelfReview(brief)?.selfReviewProposal;-describe('briefMaintenanceService', () => {+describe('briefSelfReviewService', () => {/*** @example* Applied nightly actions produce an insight brief with stable trigger metadata.*/it('projects applied nightly results to insight briefs', () => {- const service = createBriefMaintenanceService();+ const service = createBriefSelfReviewService();const brief = service.projectNightlyReviewBrief({agentId: 'agent-1',@@ -50,7 +44,7 @@ describe('briefMaintenanceService', () => {idempotencyKey: 'source:write_memory:memory:concise',receiptId: 'receipt-1',resourceId: 'mem-1',- status: MaintenanceActionStatus.Applied,+ status: ActionStatus.Applied,summary: 'Saved concise PR summary preference.',},],@@ -89,7 +83,7 @@ describe('briefMaintenanceService', () => {* Pure noop results do not create Daily Briefs.*/it('does not create briefs for pure noop outcomes', () => {- const service = createBriefMaintenanceService();+ const service = createBriefSelfReviewService();expect(service.projectNightlyReviewBrief({@@ -109,7 +103,7 @@ describe('briefMaintenanceService', () => {* Planned noop actions that execute as proposed remain silent.*/it('does not create proposal briefs for proposed noop actions with receipts', () => {- const service = createBriefMaintenanceService();+ const service = createBriefSelfReviewService();expect(service.projectNightlyReviewBrief({@@ -119,26 +113,26 @@ describe('briefMaintenanceService', () => {actions: [{actionType: 'noop',- applyMode: MaintenanceApplyMode.ProposalOnly,+ applyMode: ApplyMode.ProposalOnly,confidence: 0.9,dedupeKey: 'noop:quiet',evidenceRefs: [{ id: 'topic-1', type: 'topic' }],idempotencyKey: 'source:noop:quiet',- rationale: 'No maintenance change is needed.',- risk: MaintenanceRisk.Low,+ rationale: 'No self-iteration change is needed.',+ risk: Risk.Low,},],plannerVersion: 'test-planner',- reviewScope: MaintenanceReviewScope.Nightly,- summary: 'Review found no actionable maintenance.',+ reviewScope: Scope.Nightly,+ summary: 'Review found no actionable shared.',},result: {actions: [{idempotencyKey: 'source:noop:quiet',receiptId: 'source:noop:quiet:action',- status: MaintenanceActionStatus.Proposed,- summary: 'No maintenance change is needed.',+ status: ActionStatus.Proposed,+ summary: 'No self-iteration change is needed.',},],status: ReviewRunStatus.Completed,@@ -156,7 +150,7 @@ describe('briefMaintenanceService', () => {* Proposal actions produce decision briefs.*/it('projects proposal results to decision briefs', () => {- const service = createBriefMaintenanceService();+ const service = createBriefSelfReviewService();const brief = service.projectNightlyReviewBrief({agentId: 'agent-1',@@ -166,7 +160,7 @@ describe('briefMaintenanceService', () => {{idempotencyKey: 'source:proposal_only:skill:merge',receiptId: 'receipt-2',- status: MaintenanceActionStatus.Proposed,+ status: ActionStatus.Proposed,summary: 'Review skill consolidation proposal.',},],@@ -183,7 +177,7 @@ describe('briefMaintenanceService', () => {type: 'decision',});expect(brief?.priority).toBe('normal');- expect(brief?.summary).toContain('1 maintenance proposal need review.');+ expect(brief?.summary).toContain('1 self-review proposal need review.');expect(brief?.summary).toContain('**Proposal**');expect(brief?.summary).toContain('- Review skill consolidation proposal.');});@@ -193,7 +187,7 @@ describe('briefMaintenanceService', () => {* Proposal briefs retain the frozen action payload needed for later approval.*/it('stores frozen proposal actions on proposal briefs', () => {- const service = createBriefMaintenanceService();+ const service = createBriefSelfReviewService();const projected = service.projectNightlyReviewBrief({agentId: 'agent-1',localDate: '2026-05-09',@@ -201,7 +195,7 @@ describe('briefMaintenanceService', () => {actions: [{actionType: 'refine_skill',- applyMode: MaintenanceApplyMode.ProposalOnly,+ applyMode: ApplyMode.ProposalOnly,baseSnapshot: completeRefineSkillBaseSnapshot('adoc-1'),confidence: 0.91,dedupeKey: 'skill:adoc-1',@@ -217,12 +211,12 @@ describe('briefMaintenanceService', () => {operation: 'refine',},rationale: 'Refine the managed skill instead of creating duplicate skill drafts.',- risk: MaintenanceRisk.Medium,+ risk: Risk.Medium,target: { skillDocumentId: 'adoc-1' },},],plannerVersion: 'test-planner',- reviewScope: MaintenanceReviewScope.Nightly,+ reviewScope: Scope.Nightly,summary: 'Review found a skill refinement proposal.',},result: {@@ -230,7 +224,7 @@ describe('briefMaintenanceService', () => {{idempotencyKey: 'source:refine_skill:skill:adoc-1',receiptId: 'source:refine_skill:skill:adoc-1:action',- status: MaintenanceActionStatus.Proposed,+ status: ActionStatus.Proposed,summary: 'Refine the managed skill instead of creating duplicate skill drafts.',},],@@ -251,13 +245,13 @@ describe('briefMaintenanceService', () => {]);const nightlySelfReview = projected?.metadata.agentSignal?.nightlySelfReview;- expect(nightlySelfReview?.maintenanceProposal).toMatchObject({+ expect(nightlySelfReview?.selfReviewProposal).toMatchObject({proposalKey: 'agent-1:refine_skill:agent_document:adoc-1',status: 'pending',version: 1,});expect(projected?.metadata).not.toHaveProperty('proposal');- expect(nightlySelfReview?.maintenanceProposal?.actions[0]).toMatchObject({+ expect(nightlySelfReview?.selfReviewProposal?.actions[0]).toMatchObject({actionType: 'refine_skill',idempotencyKey: 'source:refine_skill:skill:adoc-1',operation: {@@ -272,7 +266,7 @@ describe('briefMaintenanceService', () => {* Mixed noop and actionable proposed results only freeze the actionable proposal metadata.*/it('stores proposal metadata only for real proposed actions when noop results are mixed in', () => {- const service = createBriefMaintenanceService();+ const service = createBriefSelfReviewService();const projected = service.projectNightlyReviewBrief({agentId: 'agent-1',localDate: '2026-05-09',@@ -280,17 +274,17 @@ describe('briefMaintenanceService', () => {actions: [{actionType: 'noop',- applyMode: MaintenanceApplyMode.ProposalOnly,+ applyMode: ApplyMode.ProposalOnly,confidence: 0.9,dedupeKey: 'noop:quiet',evidenceRefs: [{ id: 'topic-1', type: 'topic' }],idempotencyKey: 'source:noop:quiet',- rationale: 'No maintenance change is needed.',- risk: MaintenanceRisk.Low,+ rationale: 'No self-iteration change is needed.',+ risk: Risk.Low,},{actionType: 'refine_skill',- applyMode: MaintenanceApplyMode.ProposalOnly,+ applyMode: ApplyMode.ProposalOnly,baseSnapshot: completeRefineSkillBaseSnapshot('adoc-1'),confidence: 0.91,dedupeKey: 'skill:adoc-1',@@ -306,12 +300,12 @@ describe('briefMaintenanceService', () => {operation: 'refine',},rationale: 'Refine the managed skill instead of creating duplicate skill drafts.',- risk: MaintenanceRisk.Medium,+ risk: Risk.Medium,target: { skillDocumentId: 'adoc-1' },},],plannerVersion: 'test-planner',- reviewScope: MaintenanceReviewScope.Nightly,+ reviewScope: Scope.Nightly,summary: 'Review found one actionable proposal.',},result: {@@ -319,13 +313,13 @@ describe('briefMaintenanceService', () => {{idempotencyKey: 'source:noop:quiet',receiptId: 'source:noop:quiet:action',- status: MaintenanceActionStatus.Proposed,- summary: 'No maintenance change is needed.',+ status: ActionStatus.Proposed,+ summary: 'No self-iteration change is needed.',},{idempotencyKey: 'source:refine_skill:skill:adoc-1',receiptId: 'source:refine_skill:skill:adoc-1:action',- status: MaintenanceActionStatus.Proposed,+ status: ActionStatus.Proposed,summary: 'Refine the managed skill instead of creating duplicate skill drafts.',},],@@ -339,10 +333,10 @@ describe('briefMaintenanceService', () => {});expect(getNightlySelfReview(projected)?.actionCounts.proposed).toBe(1);- expect(projected?.summary).toContain('1 maintenance proposal need review.');- expect(projected?.summary).not.toContain('No maintenance change is needed.');- expect(getMaintenanceProposal(projected)?.actions).toHaveLength(1);- expect(getMaintenanceProposal(projected)?.actions[0]).toMatchObject({+ expect(projected?.summary).toContain('1 self-review proposal need review.');+ expect(projected?.summary).not.toContain('No self-iteration change is needed.');+ expect(getSelfReviewProposal(projected)?.actions).toHaveLength(1);+ expect(getSelfReviewProposal(projected)?.actions[0]).toMatchObject({actionType: 'refine_skill',idempotencyKey: 'source:refine_skill:skill:adoc-1',});@@ -353,7 +347,7 @@ describe('briefMaintenanceService', () => {* 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 service = createBriefSelfReviewService();const brief = service.projectNightlyReviewBrief({agentId: 'agent-1',@@ -362,7 +356,7 @@ describe('briefMaintenanceService', () => {actions: [{idempotencyKey: 'source:write_memory:memory:concise',- status: MaintenanceActionStatus.Failed,+ status: ActionStatus.Failed,summary: 'Memory service unavailable.',},],@@ -389,13 +383,13 @@ describe('briefMaintenanceService', () => {/*** @example- * Pending maintenance proposals stay visible when self-iteration is disabled.+ * Pending self-review proposals stay visible when shared is disabled.*/- it('keeps pending maintenance proposals visible after self-iteration is disabled', () => {- const service = createBriefMaintenanceService();+ it('keeps pending self-review proposals visible after shared is disabled', () => {+ const service = createBriefSelfReviewService();expect(- service.isMaintenanceProposalVisible({+ service.isSelfReviewProposalVisible({selfIterationEnabled: false,status: 'pending',trigger: 'agent-signal:nightly-review',@@ -405,13 +399,13 @@ describe('briefMaintenanceService', () => {/*** @example- * Applying a maintenance proposal re-checks server, user, and agent gates.+ * Applying a self-review proposal re-checks server, user, and agent gates.*/- it('blocks proposal apply when any current self-iteration gate is disabled', async () => {- const service = createBriefMaintenanceService();+ it('blocks proposal apply when any current shared gate is disabled', async () => {+ const service = createBriefSelfReviewService();await expect(- service.canApplyMaintenanceProposal({+ service.canApplySelfReviewProposal({checkAgentGate: vi.fn(async () => true),checkServerGate: vi.fn(async () => true),checkUserGate: vi.fn(async () => false),@@ -424,13 +418,13 @@ describe('briefMaintenanceService', () => {/*** @example- * Applying a maintenance proposal is allowed only when all gates pass.+ * Applying a self-review proposal is allowed only when all gates pass.*/it('allows proposal apply when all current gates pass', async () => {- const service = createBriefMaintenanceService();+ const service = createBriefSelfReviewService();await expect(- service.canApplyMaintenanceProposal({+ service.canApplySelfReviewProposal({checkAgentGate: vi.fn(async () => true),checkServerGate: vi.fn(async () => true),checkUserGate: vi.fn(async () => true),@@ -449,14 +443,14 @@ describe('briefMaintenanceService', () => {id: 'brief-1',metadata: {},priority: 'info',- summary: '1 maintenance update applied.',+ summary: '1 self-iteration 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 writer = createServerSelfReviewBriefWriter({} as never, 'user-1');+ const service = createBriefSelfReviewService();const brief = service.projectNightlyReviewBrief({agentId: 'agent-1',localDate: '2026-05-04',@@ -465,7 +459,7 @@ describe('briefMaintenanceService', () => {{idempotencyKey: 'source:write_memory:memory:concise',receiptId: 'receipt-1',- status: MaintenanceActionStatus.Applied,+ status: ActionStatus.Applied,summary: 'Saved concise PR summary preference.',},],@@ -488,7 +482,7 @@ describe('briefMaintenanceService', () => {* A compatible pending proposal refreshes the old brief instead of creating a duplicate.*/it('refreshes an existing compatible pending proposal brief', async () => {- const service = createBriefMaintenanceService();+ const service = createBriefSelfReviewService();const incoming = service.projectNightlyReviewBrief({agentId: 'agent-1',localDate: '2026-05-09',@@ -496,7 +490,7 @@ describe('briefMaintenanceService', () => {actions: [{actionType: 'refine_skill',- applyMode: MaintenanceApplyMode.ProposalOnly,+ applyMode: ApplyMode.ProposalOnly,baseSnapshot: completeRefineSkillBaseSnapshot('adoc-1'),confidence: 0.91,dedupeKey: 'skill:adoc-1',@@ -508,12 +502,12 @@ describe('briefMaintenanceService', () => {operation: 'refine',},rationale: 'Refresh the same proposal.',- risk: MaintenanceRisk.Medium,+ risk: Risk.Medium,target: { skillDocumentId: 'adoc-1' },},],plannerVersion: 'test-planner',- reviewScope: MaintenanceReviewScope.Nightly,+ reviewScope: Scope.Nightly,summary: 'Refresh proposal.',},result: {@@ -521,7 +515,7 @@ describe('briefMaintenanceService', () => {{idempotencyKey: 'source:new',receiptId: 'receipt-new',- status: MaintenanceActionStatus.Proposed,+ status: ActionStatus.Proposed,},],status: ReviewRunStatus.Completed,@@ -533,7 +527,7 @@ describe('briefMaintenanceService', () => {});if (!incoming) throw new Error('Expected projected incoming brief');- const incomingProposal = getMaintenanceProposal(incoming);+ const incomingProposal = getSelfReviewProposal(incoming);if (!incomingProposal) throw new Error('Expected projected proposal brief');const existingProposal = {@@ -555,7 +549,7 @@ describe('briefMaintenanceService', () => {metadata: {agentSignal: {nightlySelfReview: {- maintenanceProposal: existingProposal,+ selfReviewProposal: existingProposal,},},},@@ -566,7 +560,7 @@ describe('briefMaintenanceService', () => {metadata: {agentSignal: {nightlySelfReview: {- maintenanceProposal: { ...existingProposal, actions: incomingProposal.actions },+ selfReviewProposal: { ...existingProposal, actions: incomingProposal.actions },},},},@@ -578,7 +572,7 @@ describe('briefMaintenanceService', () => {const updateMetadata = vi.spyOn(BriefModel.prototype, 'updateMetadata').mockResolvedValue(updatedBrief);- const writer = createServerMaintenanceBriefWriter({} as never, 'user-1');+ const writer = createServerSelfReviewBriefWriter({} as never, 'user-1');await expect(writer.writeDailyBrief(incoming)).resolves.toBe(updatedBrief);@@ -593,7 +587,7 @@ describe('briefMaintenanceService', () => {expect.objectContaining({agentSignal: expect.objectContaining({nightlySelfReview: expect.objectContaining({- maintenanceProposal: expect.objectContaining({+ selfReviewProposal: expect.objectContaining({actions: incomingProposal.actions,status: 'pending',}),@@ -608,7 +602,7 @@ describe('briefMaintenanceService', () => {* An incompatible same-key proposal supersedes the old brief and creates a new one.*/it('supersedes an incompatible pending proposal before creating a replacement brief', async () => {- const service = createBriefMaintenanceService();+ const service = createBriefSelfReviewService();const incoming = service.projectNightlyReviewBrief({agentId: 'agent-1',localDate: '2026-05-09',@@ -616,7 +610,7 @@ describe('briefMaintenanceService', () => {actions: [{actionType: 'refine_skill',- applyMode: MaintenanceApplyMode.ProposalOnly,+ applyMode: ApplyMode.ProposalOnly,baseSnapshot: completeRefineSkillBaseSnapshot('adoc-1'),confidence: 0.91,dedupeKey: 'skill:adoc-1',@@ -628,12 +622,12 @@ describe('briefMaintenanceService', () => {operation: 'refine',},rationale: 'Replace the old proposal.',- risk: MaintenanceRisk.Medium,+ risk: Risk.Medium,target: { skillDocumentId: 'adoc-1' },},],plannerVersion: 'test-planner',- reviewScope: MaintenanceReviewScope.Nightly,+ reviewScope: Scope.Nightly,summary: 'Replacement proposal.',},result: {@@ -641,7 +635,7 @@ describe('briefMaintenanceService', () => {{idempotencyKey: 'source:new',receiptId: 'receipt-new',- status: MaintenanceActionStatus.Proposed,+ status: ActionStatus.Proposed,},],status: ReviewRunStatus.Completed,@@ -653,11 +647,11 @@ describe('briefMaintenanceService', () => {});if (!incoming) throw new Error('Expected projected incoming brief');- const incomingProposal = getMaintenanceProposal(incoming);+ const incomingProposal = getSelfReviewProposal(incoming);if (!incomingProposal) throw new Error('Expected projected proposal brief');const existingProposal = incomingProposal;- incoming.metadata.agentSignal.nightlySelfReview.maintenanceProposal = {+ incoming.metadata.agentSignal.nightlySelfReview.selfReviewProposal = {...incomingProposal,actions: [{@@ -676,7 +670,7 @@ describe('briefMaintenanceService', () => {metadata: {agentSignal: {nightlySelfReview: {- maintenanceProposal: existingProposal,+ selfReviewProposal: existingProposal,},},},@@ -690,7 +684,7 @@ describe('briefMaintenanceService', () => {const updateMetadata = vi.spyOn(BriefModel.prototype, 'updateMetadata').mockResolvedValue(existingBrief);- const writer = createServerMaintenanceBriefWriter({} as never, 'user-1');+ const writer = createServerSelfReviewBriefWriter({} as never, 'user-1');await expect(writer.writeDailyBrief(incoming)).resolves.toBe(createdBrief);@@ -699,10 +693,10 @@ describe('briefMaintenanceService', () => {expect.objectContaining({agentSignal: expect.objectContaining({nightlySelfReview: expect.objectContaining({- maintenanceProposal: expect.objectContaining({+ selfReviewProposal: expect.objectContaining({status: 'superseded',supersededBy:- incoming.metadata.agentSignal.nightlySelfReview.maintenanceProposal?.proposalKey,+ incoming.metadata.agentSignal.nightlySelfReview.selfReviewProposal?.proposalKey,}),}),}),@@ -716,7 +710,7 @@ describe('briefMaintenanceService', () => {* An expired pending proposal is marked expired and a fresh proposal brief is created.*/it('marks expired pending proposals before creating a fresh brief', async () => {- const service = createBriefMaintenanceService();+ const service = createBriefSelfReviewService();const incoming = service.projectNightlyReviewBrief({agentId: 'agent-1',localDate: '2026-05-09',@@ -724,7 +718,7 @@ describe('briefMaintenanceService', () => {actions: [{actionType: 'refine_skill',- applyMode: MaintenanceApplyMode.ProposalOnly,+ applyMode: ApplyMode.ProposalOnly,baseSnapshot: completeRefineSkillBaseSnapshot('adoc-1'),confidence: 0.91,dedupeKey: 'skill:adoc-1',@@ -736,12 +730,12 @@ describe('briefMaintenanceService', () => {operation: 'refine',},rationale: 'Create a fresh proposal.',- risk: MaintenanceRisk.Medium,+ risk: Risk.Medium,target: { skillDocumentId: 'adoc-1' },},],plannerVersion: 'test-planner',- reviewScope: MaintenanceReviewScope.Nightly,+ reviewScope: Scope.Nightly,summary: 'Fresh proposal.',},result: {@@ -749,7 +743,7 @@ describe('briefMaintenanceService', () => {{idempotencyKey: 'source:new',receiptId: 'receipt-new',- status: MaintenanceActionStatus.Proposed,+ status: ActionStatus.Proposed,},],status: ReviewRunStatus.Completed,@@ -761,7 +755,7 @@ describe('briefMaintenanceService', () => {});if (!incoming) throw new Error('Expected projected incoming brief');- const incomingProposal = getMaintenanceProposal(incoming);+ const incomingProposal = getSelfReviewProposal(incoming);if (!incomingProposal) throw new Error('Expected projected proposal brief');const existingProposal = {@@ -775,7 +769,7 @@ describe('briefMaintenanceService', () => {metadata: {agentSignal: {nightlySelfReview: {- maintenanceProposal: existingProposal,+ selfReviewProposal: existingProposal,},},},@@ -789,7 +783,7 @@ describe('briefMaintenanceService', () => {const updateMetadata = vi.spyOn(BriefModel.prototype, 'updateMetadata').mockResolvedValue(existingBrief);- const writer = createServerMaintenanceBriefWriter({} as never, 'user-1');+ const writer = createServerSelfReviewBriefWriter({} as never, 'user-1');await expect(writer.writeDailyBrief(incoming)).resolves.toBe(createdBrief);@@ -798,7 +792,7 @@ describe('briefMaintenanceService', () => {expect.objectContaining({agentSignal: expect.objectContaining({nightlySelfReview: expect.objectContaining({- maintenanceProposal: expect.objectContaining({ status: 'expired' }),+ selfReviewProposal: expect.objectContaining({ status: 'expired' }),}),}),}),diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/nightlyCollector.test.ts b/src/server/services/agentSignal/services/selfIteration/review/__test__/collect.test.tssimilarity index 63%rename from src/server/services/agentSignal/services/maintenance/__tests__/nightlyCollector.test.tsrename to src/server/services/agentSignal/services/selfIteration/review/__test__/collect.test.tsindex 8f3bda1d090..368fa6a9594 100644--- a/src/server/services/agentSignal/services/maintenance/__tests__/nightlyCollector.test.ts+++ b/src/server/services/agentSignal/services/selfIteration/review/__test__/collect.test.ts@@ -5,8 +5,8 @@ import type {ListRelevantMemoriesInput,ListTopicActivityInput,NightlyReviewReadAdapters,-} from '../nightlyCollector';-import { createNightlyReviewService } from '../nightlyCollector';+} from '../collect';+import { createSelfReviewContextService, mapNightlyDocumentActivityRows } from '../collect';const REVIEW_INPUT = {agentId: 'agent-1',@@ -53,8 +53,95 @@ const createDeps = (...overrides,});+describe('mapNightlyDocumentActivityRows', () => {+ /**+ * @example+ * hintIsSkill true rows enter the skill bucket and false rows enter the general bucket.+ */+ it('buckets hinted skill and general document activity separately', () => {+ expect(+ mapNightlyDocumentActivityRows([+ {+ agentDocumentId: 'agent-doc-skill',+ documentId: 'doc-skill',+ hintIsSkill: true,+ policyLoadFormat: 'raw',+ templateId: null,+ title: 'YouTube comments skill',+ updatedAt: new Date('2026-05-09T18:10:00.000Z'),+ },+ {+ agentDocumentId: 'agent-doc-general',+ documentId: 'doc-general',+ hintIsSkill: false,+ policyLoadFormat: 'raw',+ templateId: null,+ title: 'Meeting notes',+ updatedAt: new Date('2026-05-09T18:11:00.000Z'),+ },+ ]),+ ).toEqual({+ ambiguousBucket: [],+ excludedSummary: { count: 0, reasons: [] },+ generalDocumentBucket: [+ expect.objectContaining({+ agentDocumentId: 'agent-doc-general',+ reason: 'metadata.agentSignal.hintIsSkill=false',+ }),+ ],+ skillBucket: [+ expect.objectContaining({+ agentDocumentId: 'agent-doc-skill',+ hintIsSkill: true,+ reason: 'metadata.agentSignal.hintIsSkill=true',+ }),+ ],+ });+ });++ /**+ * @example+ * Existing managed skill templates are still skill bucket evidence even without a hint.+ */+ it('buckets known skill template rows as skill activity', () => {+ expect(+ mapNightlyDocumentActivityRows([+ {+ agentDocumentId: 'agent-doc-index',+ documentId: 'doc-index',+ hintIsSkill: null,+ policyLoadFormat: 'raw',+ templateId: 'skills/index',+ title: 'Skill index',+ updatedAt: new Date('2026-05-09T18:10:00.000Z'),+ },+ {+ agentDocumentId: 'agent-doc-managed-skill',+ documentId: 'doc-managed-skill',+ hintIsSkill: null,+ policyLoadFormat: 'raw',+ templateId: 'agent-skill',+ title: 'Managed skill',+ updatedAt: new Date('2026-05-09T18:11:00.000Z'),+ },+ ]).skillBucket,+ ).toEqual([+ expect.objectContaining({+ agentDocumentId: 'agent-doc-index',+ hintIsSkill: false,+ reason: 'templateId=skills/index',+ }),+ expect.objectContaining({+ agentDocumentId: 'agent-doc-managed-skill',+ hintIsSkill: false,+ reason: 'templateId=agent-skill',+ }),+ ]);+ });+});+describe('nightlyReviewService', () => {- describe('collectNightlyReviewContext', () => {+ describe('collect', () => {it('ranks high-signal topics first and excludes raw messages while including skills and memories', async () => {/*** @example@@ -88,9 +175,9 @@ describe('nightlyReviewService', () => {},]),});- const service = createNightlyReviewService(deps);+ const service = createSelfReviewContextService(deps);- const context = await service.collectNightlyReviewContext(REVIEW_INPUT);+ const context = await service.collect(REVIEW_INPUT);expect(context).toMatchObject({agentId: 'agent-1',@@ -123,25 +210,25 @@ describe('nightlyReviewService', () => {correctionCount: 1,correctionIds: [],});- expect(context.maintenanceSignals.map((signal) => signal.kind)).not.toContain(+ expect(context.selfReviewSignals.map((signal) => signal.kind)).not.toContain('durable_user_preference',);expect(context.topics[0]).not.toHaveProperty('rawMessages');expect(context.topics[1]).not.toHaveProperty('rawMessages');});- it('returns empty structured maintenance buckets when optional adapters are absent', async () => {+ it('returns empty structured shared buckets when optional adapters are absent', async () => {/*** @example- * expect(context.maintenanceSignals).toEqual([]).+ * expect(context.selfReviewSignals).toEqual([]).*/- const service = createNightlyReviewService({+ const service = createSelfReviewContextService({listManagedSkills: async () => [],listRelevantMemories: async () => [],listTopicActivity: async () => [],});- await expect(service.collectNightlyReviewContext(REVIEW_INPUT)).resolves.toMatchObject({+ await expect(service.collect(REVIEW_INPUT)).resolves.toMatchObject({documentActivity: {ambiguousBucket: [],excludedSummary: { count: 0, reasons: [] },@@ -149,7 +236,7 @@ describe('nightlyReviewService', () => {skillBucket: [],},feedbackActivity: { neutralCount: 0, notSatisfied: [], satisfied: [] },- maintenanceSignals: [],+ selfReviewSignals: [],proposalActivity: {active: [],dismissedCount: 0,@@ -165,6 +252,7 @@ describe('nightlyReviewService', () => {recentReceipts: [],reviewCount: 0,},+ selfFeedbackCandidates: [],toolActivity: [],});});@@ -174,7 +262,7 @@ describe('nightlyReviewService', () => {* @example* expect(context.proposalActivity.active[0].proposalId).toBe('brf_1').*/- const service = createNightlyReviewService({+ const service = createSelfReviewContextService({listManagedSkills: async () => [],listProposalActivity: async () => ({active: [@@ -201,7 +289,7 @@ describe('nightlyReviewService', () => {listTopicActivity: async () => [],});- await expect(service.collectNightlyReviewContext(REVIEW_INPUT)).resolves.toMatchObject({+ await expect(service.collect(REVIEW_INPUT)).resolves.toMatchObject({proposalActivity: {active: [{ proposalId: 'brf_1', status: 'pending' }],},@@ -221,9 +309,9 @@ describe('nightlyReviewService', () => {})),),});- const service = createNightlyReviewService(deps);+ const service = createSelfReviewContextService(deps);- const context = await service.collectNightlyReviewContext(REVIEW_INPUT);+ const context = await service.collect(REVIEW_INPUT);expect(context.topics).toHaveLength(30);expect(context.topics.at(-1)?.id).toBe('topic-29');@@ -249,9 +337,9 @@ describe('nightlyReviewService', () => {},]),});- const service = createNightlyReviewService(deps);+ const service = createSelfReviewContextService(deps);- const context = await service.collectNightlyReviewContext(REVIEW_INPUT);+ const context = await service.collect(REVIEW_INPUT);expect(context.topics.map((topic) => topic.id)).toEqual(['topic-receipt', 'topic-huge']);expect(context.topics[0].highSignalReasons).toEqual(['receipt']);@@ -278,9 +366,9 @@ describe('nightlyReviewService', () => {},]),});- const service = createNightlyReviewService(deps);+ const service = createSelfReviewContextService(deps);- const context = await service.collectNightlyReviewContext(REVIEW_INPUT);+ const context = await service.collect(REVIEW_INPUT);expect(context.topics[0].evidenceRefs).toEqual([{ id: 'message-1', summary: 'User corrected the answer.', type: 'message' },@@ -311,9 +399,9 @@ describe('nightlyReviewService', () => {},]),});- const service = createNightlyReviewService(deps);+ const service = createSelfReviewContextService(deps);- const context = await service.collectNightlyReviewContext(REVIEW_INPUT);+ const context = await service.collect(REVIEW_INPUT);expect(context.topics[0]).toMatchObject({failedMessages: [{ errorSummary: '{"message":"model failed"}', messageId: 'msg-1' }],@@ -353,9 +441,9 @@ describe('nightlyReviewService', () => {},]),});- const service = createNightlyReviewService(deps);+ const service = createSelfReviewContextService(deps);- const context = await service.collectNightlyReviewContext(REVIEW_INPUT);+ const context = await service.collect(REVIEW_INPUT);expect(context.topics.map((topic) => topic.id)).toEqual(['topic-a', 'topic-b']);});@@ -380,9 +468,9 @@ describe('nightlyReviewService', () => {},]),});- const service = createNightlyReviewService(deps);+ const service = createSelfReviewContextService(deps);- const context = await service.collectNightlyReviewContext(REVIEW_INPUT);+ const context = await service.collect(REVIEW_INPUT);expect(context.topics[0].attributes).toEqual({ safeLabel: 'billing' });});@@ -401,9 +489,9 @@ describe('nightlyReviewService', () => {},]),});- const service = createNightlyReviewService(deps);+ const service = createSelfReviewContextService(deps);- const context = await service.collectNightlyReviewContext(REVIEW_INPUT);+ const context = await service.collect(REVIEW_INPUT);expect(context.topics[0]).toMatchObject({highSignalReasons: [],@@ -411,5 +499,72 @@ describe('nightlyReviewService', () => {reviewScore: 4,});});++ it('maps reflection intent receipt metadata into ranked review candidates', async () => {+ /**+ * @example+ * expect(context.selfFeedbackCandidates[0].reviewBehavior).toBe('proposal_priority');+ */+ const service = createSelfReviewContextService({+ listManagedSkills: async () => [],+ listReceiptActivity: async () => ({+ appliedCount: 0,+ duplicateGroups: [],+ failedCount: 0,+ pendingProposalCount: 0,+ recentReceipts: [+ {+ id: 'receipt-reflection-1',+ kind: 'review',+ metadata: {+ selfIteration: {+ intents: [+ {+ actionType: 'refine_skill',+ confidence: 0.9,+ evidenceRefs: [{ id: 'tool-call-1', type: 'tool_call' }],+ idempotencyKey: 'intent-refine-skill-1',+ intentType: 'skill',+ mode: 'reflection',+ operation: {+ domain: 'skill',+ input: {+ bodyMarkdown: '# Skill',+ skillDocumentId: 'skill-1',+ userId: 'user-1',+ },+ operation: 'refine',+ },+ rationale: 'The agent repeatedly failed the same local checklist.',+ risk: 'medium',+ target: { skillDocumentId: 'skill-1' },+ urgency: 'soon',+ },+ ],+ mode: 'reflection',+ },+ },+ status: 'completed',+ },+ ],+ reviewCount: 1,+ }),+ listRelevantMemories: async () => [],+ listTopicActivity: async () => [],+ });++ const context = await service.collect(REVIEW_INPUT);++ expect(context.selfFeedbackCandidates).toHaveLength(1);+ expect(context.selfFeedbackCandidates[0]).toMatchObject({+ confidence: 0.9,+ evidenceStrength: 'strong',+ reviewBehavior: 'proposal_priority',+ });+ expect(context.selfFeedbackCandidates[0].intent.operation).toMatchObject({+ domain: 'skill',+ operation: 'refine',+ });+ });});});diff --git a/src/server/services/agentSignal/policies/reviewNightly/__tests__/nightlyReview.test.ts b/src/server/services/agentSignal/services/selfIteration/review/__test__/handler.test.tssimilarity index 89%rename from src/server/services/agentSignal/policies/reviewNightly/__tests__/nightlyReview.test.tsrename to src/server/services/agentSignal/services/selfIteration/review/__test__/handler.test.tsindex 7eae91712bb..31c3a43b4bc 100644--- a/src/server/services/agentSignal/policies/reviewNightly/__tests__/nightlyReview.test.ts+++ b/src/server/services/agentSignal/services/selfIteration/review/__test__/handler.test.ts@@ -4,31 +4,22 @@ import type { SourceAgentNightlyReviewRequested } from '@lobechat/agent-signal/simport { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';import { describe, expect, it, vi } from 'vitest';+import { createDefaultAgentSignalPolicies } from '../../../../policies';import type {AgentSignalActionHandlerDefinition,AgentSignalSignalHandlerDefinition,AgentSignalSourceHandlerDefinition,-} from '../../../runtime/middleware';-import type { MaintenanceAgentRunResult } from '../../../services/maintenance/agentRunner';-import type { NightlyReviewContext } from '../../../services/maintenance/nightlyCollector';-import type { MaintenanceProposalPlan } from '../../../services/maintenance/proposal';-import type {- MaintenancePlan,- MaintenanceReviewRunResult,-} from '../../../services/maintenance/types';-import {- MaintenanceActionStatus,- MaintenanceApplyMode,- MaintenanceReviewScope,- MaintenanceRisk,- ReviewRunStatus,-} from '../../../services/maintenance/types';-import { createDefaultAgentSignalPolicies } from '../..';-import type { CreateNightlyReviewSourceHandlerDependencies } from '../nightlyReview';+} from '../../../../runtime/middleware';+import type { AgentRunResult } from '../../execute';+import type { Plan, RunResult } from '../../types';+import { ActionStatus, ApplyMode, ReviewRunStatus, Risk, Scope } from '../../types';+import type { NightlyReviewContext } from '../collect';+import type { CreateNightlyReviewSourceHandlerDependencies } from '../handler';import {createNightlyReviewSourceHandler,createNightlyReviewSourcePolicyHandler,-} from '../nightlyReview';+} from '../handler';+import type { SelfReviewProposalPlan } from '../proposal';const reviewPayload = {agentId: 'agent-1',@@ -66,7 +57,7 @@ const reviewContext = {notSatisfied: [],satisfied: [],},- maintenanceSignals: [],+ selfReviewSignals: [],managedSkills: [],proposalActivity: {active: [],@@ -86,6 +77,7 @@ const reviewContext = {relevantMemories: [],reviewWindowEnd: reviewPayload.reviewWindowEnd,reviewWindowStart: reviewPayload.reviewWindowStart,+ selfFeedbackCandidates: [],toolActivity: [],topics: [],userId: 'user-1',@@ -95,37 +87,37 @@ const reviewPlan = {actions: [{actionType: 'noop',- applyMode: MaintenanceApplyMode.Skip,+ applyMode: ApplyMode.Skip,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.Low,+ rationale: 'No self-iteration needed.',+ risk: Risk.Low,},],localDate: reviewPayload.localDate,plannerVersion: 'test-planner',- reviewScope: MaintenanceReviewScope.Nightly,+ reviewScope: Scope.Nightly,summary: 'Quiet night.',-} satisfies MaintenancePlan;+} satisfies Plan;const executionResult = {actions: [{idempotencyKey: 'nightly-review:user-1:agent-1:2026-05-04:noop:quiet',- status: MaintenanceActionStatus.Skipped,- summary: 'No maintenance needed.',+ status: ActionStatus.Skipped,+ summary: 'No self-iteration needed.',},],status: ReviewRunStatus.Completed,-} satisfies MaintenanceReviewRunResult;+} satisfies RunResult;const reviewAgentResult = {execution: executionResult,projectionPlan: reviewPlan,stepCount: 1,-} satisfies MaintenanceAgentRunResult;+} satisfies AgentRunResult;const createDependencies = (overrides: Partial<CreateNightlyReviewSourceHandlerDependencies> = {},@@ -133,7 +125,7 @@ const createDependencies = (acquireReviewGuard: vi.fn(async () => true),canRunReview: vi.fn(async () => true),collectContext: vi.fn(async () => reviewContext),- runMaintenanceReviewAgent: vi.fn(async () => reviewAgentResult),+ runSelfReviewAgent: vi.fn(async () => reviewAgentResult),...overrides,});@@ -165,7 +157,7 @@ describe('nightly review source handler', () => {reviewWindowStart: reviewPayload.reviewWindowStart,userId: 'user-1',});- expect(deps.runMaintenanceReviewAgent).toHaveBeenCalledWith({+ expect(deps.runSelfReviewAgent).toHaveBeenCalledWith({context: reviewContext,localDate: '2026-05-04',sourceId: 'nightly-review:user-1:agent-1:2026-05-04',@@ -191,12 +183,12 @@ describe('nightly review source handler', () => {it('writes review receipts before creating an eligible nightly brief', async () => {const calls: string[] = [];const deps = createDependencies({- runMaintenanceReviewAgent: vi.fn(async () => ({+ runSelfReviewAgent: vi.fn(async () => ({execution: {actions: [{idempotencyKey: 'nightly-review:user-1:agent-1:2026-05-04:refine_skill:skill-doc-1',- status: MaintenanceActionStatus.Proposed,+ status: ActionStatus.Proposed,summary: 'Review the skill refinement proposal.',},],@@ -208,7 +200,7 @@ describe('nightly review source handler', () => {{...reviewPlan.actions[0],actionType: 'refine_skill',- applyMode: MaintenanceApplyMode.ProposalOnly,+ applyMode: ApplyMode.ProposalOnly,baseSnapshot: {agentDocumentId: 'skill-doc-1',contentHash: 'sha256:workflow-summary',@@ -229,11 +221,11 @@ describe('nightly review source handler', () => {operation: 'refine',},rationale: 'Review the skill refinement proposal.',- risk: MaintenanceRisk.Medium,+ risk: Risk.Medium,target: { skillDocumentId: 'skill-doc-1' },},],- } satisfies MaintenanceProposalPlan,+ } satisfies SelfReviewProposalPlan,})),writeDailyBrief: vi.fn(async () => {calls.push('brief');@@ -262,7 +254,7 @@ describe('nightly review source handler', () => {agentSignal: expect.objectContaining({nightlySelfReview: expect.objectContaining({evidenceRefs: [{ id: 'topic-1', type: 'topic' }],- maintenanceProposal: expect.objectContaining({+ selfReviewProposal: expect.objectContaining({actions: [expect.objectContaining({actionType: 'refine_skill',@@ -298,16 +290,16 @@ describe('nightly review source handler', () => {* @example* expect(deps.writeDailyBrief).toHaveBeenCalledWith(expect.objectContaining({ type: 'insight' }));*/- it('creates an insight brief for auto-applied nightly maintenance', async () => {+ it('creates an insight brief for auto-applied nightly shared', async () => {const deps = createDependencies({- runMaintenanceReviewAgent: vi.fn(async () => ({+ runSelfReviewAgent: vi.fn(async () => ({execution: {actions: [{idempotencyKey:'nightly-review:user-1:agent-1:2026-05-04:write_memory:memory:concise',resourceId: 'mem-1',- status: MaintenanceActionStatus.Applied,+ status: ActionStatus.Applied,summary: 'Saved concise release summary preference.',},],@@ -319,7 +311,7 @@ describe('nightly review source handler', () => {{...reviewPlan.actions[0],actionType: 'write_memory',- applyMode: MaintenanceApplyMode.AutoApply,+ applyMode: ApplyMode.AutoApply,dedupeKey: 'memory:concise',idempotencyKey:'nightly-review:user-1:agent-1:2026-05-04:write_memory:memory:concise',@@ -332,11 +324,11 @@ describe('nightly review source handler', () => {operation: 'write',},rationale: 'The user stated a durable release summary preference.',- risk: MaintenanceRisk.Low,+ risk: Risk.Low,target: { topicIds: ['topic-1'] },},],- } satisfies MaintenancePlan,+ } satisfies Plan,})),writeDailyBrief: vi.fn(async () => ({ id: 'brief-insight-1' })),writeReceipts: vi.fn(async () => {}),@@ -399,7 +391,7 @@ describe('nightly review source handler', () => {/*** @example- * expect(brief.metadata.agentSignal.nightlySelfReview.maintenanceProposal.actions[0].operation).toBeDefined();+ * expect(brief.metadata.agentSignal.nightlySelfReview.selfReviewProposal.actions[0].operation).toBeDefined();*/it('projects frozen proposal action operations from the runner projection plan', async () => {const proposedSkillPlan = {@@ -408,7 +400,7 @@ describe('nightly review source handler', () => {{...reviewPlan.actions[0],actionType: 'refine_skill',- applyMode: MaintenanceApplyMode.ProposalOnly,+ applyMode: ApplyMode.ProposalOnly,baseSnapshot: {agentDocumentId: 'skill-doc-1',contentHash: 'sha256:workflow-summary',@@ -429,18 +421,18 @@ describe('nightly review source handler', () => {operation: 'refine',},rationale: 'Review the workflow summary skill refinement.',- risk: MaintenanceRisk.Medium,+ risk: Risk.Medium,target: { skillDocumentId: 'skill-doc-1' },},],- } satisfies MaintenanceProposalPlan;+ } satisfies SelfReviewProposalPlan;const deps = createDependencies({- runMaintenanceReviewAgent: vi.fn(async () => ({+ runSelfReviewAgent: vi.fn(async () => ({execution: {actions: [{idempotencyKey: 'nightly-review:user-1:agent-1:2026-05-04:refine_skill:skill-doc-1',- status: MaintenanceActionStatus.Proposed,+ status: ActionStatus.Proposed,summary: 'Refine the workflow summary skill.',},],@@ -460,7 +452,7 @@ describe('nightly review source handler', () => {metadata: expect.objectContaining({agentSignal: expect.objectContaining({nightlySelfReview: expect.objectContaining({- maintenanceProposal: expect.objectContaining({+ selfReviewProposal: expect.objectContaining({actions: [expect.objectContaining({actionType: 'refine_skill',@@ -486,12 +478,12 @@ describe('nightly review source handler', () => {const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});const briefError = new Error('brief store unavailable');const deps = createDependencies({- runMaintenanceReviewAgent: vi.fn(async () => ({+ runSelfReviewAgent: vi.fn(async () => ({execution: {actions: [{idempotencyKey: 'nightly-review:user-1:agent-1:2026-05-04:refine_skill:skill-doc-1',- status: MaintenanceActionStatus.Proposed,+ status: ActionStatus.Proposed,summary: 'Review the skill refinement proposal.',},],@@ -503,7 +495,7 @@ describe('nightly review source handler', () => {{...reviewPlan.actions[0],actionType: 'refine_skill',- applyMode: MaintenanceApplyMode.ProposalOnly,+ applyMode: ApplyMode.ProposalOnly,baseSnapshot: {agentDocumentId: 'skill-doc-1',contentHash: 'sha256:workflow-summary',@@ -524,11 +516,11 @@ describe('nightly review source handler', () => {operation: 'refine',},rationale: 'Review the skill refinement proposal.',- risk: MaintenanceRisk.Medium,+ risk: Risk.Medium,target: { skillDocumentId: 'skill-doc-1' },},],- } satisfies MaintenanceProposalPlan,+ } satisfies SelfReviewProposalPlan,})),writeDailyBrief: vi.fn(async () => {throw briefError;@@ -571,7 +563,7 @@ describe('nightly review source handler', () => {}),);expect(deps.collectContext).not.toHaveBeenCalled();- expect(deps.runMaintenanceReviewAgent).not.toHaveBeenCalled();+ expect(deps.runSelfReviewAgent).not.toHaveBeenCalled();});/**@@ -686,7 +678,7 @@ describe('nightly review source handler', () => {expect(nightlyHandler).toEqual(expect.objectContaining({- id: `${AGENT_SIGNAL_SOURCE_TYPES.agentNightlyReviewRequested}:maintenance-review`,+ id: `${AGENT_SIGNAL_SOURCE_TYPES.agentNightlyReviewRequested}:shared-review`,type: 'source',}),);diff --git a/src/server/services/agentSignal/services/selfIteration/review/__test__/intentPolicy.test.ts b/src/server/services/agentSignal/services/selfIteration/review/__test__/intentPolicy.test.tsnew file mode 100644index 00000000000..ba23ee20084--- /dev/null+++ b/src/server/services/agentSignal/services/selfIteration/review/__test__/intentPolicy.test.ts@@ -0,0 +1,201 @@+import { describe, expect, it } from 'vitest';++import {+ getSelfFeedbackIntentTargetSignature,+ groupSelfFeedbackIntents,+ normalizeReflectionIntent,+ rankSelfFeedbackCandidates,+ squashSelfFeedbackIntentGroup,+} from '../intentPolicy';++describe('self-review intent policy', () => {+ /**+ * @example+ * normalizeReflectionIntent({ confidence: undefined }).confidence === 0.5;+ */+ it('defaults missing confidence to 0.5', () => {+ expect(+ normalizeReflectionIntent({+ evidenceRefs: [],+ idempotencyKey: 'intent-1',+ intentType: 'workflow',+ mode: 'reflection',+ rationale: 'Review this later.',+ risk: 'low',+ urgency: 'later',+ }).confidence,+ ).toBe(0.5);+ });++ /**+ * @example+ * skill refine intents targeting the same skill are grouped together.+ */+ it('groups intents by intent type action type and target signature', () => {+ const groups = groupSelfFeedbackIntents([+ normalizeReflectionIntent({+ actionType: 'refine_skill',+ confidence: 0.7,+ evidenceRefs: [{ id: 'msg-1', type: 'message' }],+ idempotencyKey: 'intent-1',+ intentType: 'skill',+ mode: 'reflection',+ rationale: 'Refine release note checklist.',+ risk: 'medium',+ target: { skillDocumentId: 'skill-1' },+ urgency: 'soon',+ }),+ normalizeReflectionIntent({+ actionType: 'refine_skill',+ confidence: 0.8,+ evidenceRefs: [{ id: 'msg-2', type: 'message' }],+ idempotencyKey: 'intent-2',+ intentType: 'skill',+ mode: 'reflection',+ rationale: 'Same target.',+ risk: 'medium',+ target: { skillDocumentId: 'skill-1' },+ urgency: 'later',+ }),+ ]);++ expect(groups).toHaveLength(1);+ expect(groups[0].key).toBe('skill:refine_skill:skill:skill-1');+ });++ /**+ * @example+ * repeated evidence uses max confidence rather than summing confidence.+ */+ it('uses max confidence without inflating repeated evidence', () => {+ const group = groupSelfFeedbackIntents([+ normalizeReflectionIntent({+ actionType: 'write_memory',+ confidence: 0.6,+ evidenceRefs: [{ id: 'msg-1', type: 'message' }],+ idempotencyKey: 'intent-1',+ intentType: 'memory',+ mode: 'reflection',+ rationale: 'Remember preference.',+ risk: 'low',+ target: { memoryId: 'memory-1' },+ urgency: 'later',+ }),+ normalizeReflectionIntent({+ actionType: 'write_memory',+ confidence: 0.7,+ evidenceRefs: [{ id: 'msg-2', type: 'message' }],+ idempotencyKey: 'intent-2',+ intentType: 'memory',+ mode: 'reflection',+ rationale: 'Same preference.',+ risk: 'low',+ target: { memoryId: 'memory-1' },+ urgency: 'soon',+ }),+ ])[0];++ expect(squashSelfFeedbackIntentGroup(group).confidence).toBe(0.7);+ });++ /**+ * @example+ * repeated medium intents become stronger evidence without changing aggregate confidence.+ */+ it('promotes repeated matching intents to stronger evidence strength', () => {+ const group = groupSelfFeedbackIntents([+ normalizeReflectionIntent({+ actionType: 'write_memory',+ confidence: 0.55,+ evidenceRefs: [{ id: 'msg-1', type: 'message' }],+ idempotencyKey: 'intent-1',+ intentType: 'memory',+ mode: 'reflection',+ rationale: 'Remember preference.',+ risk: 'low',+ target: { memoryId: 'memory-1' },+ urgency: 'later',+ }),+ normalizeReflectionIntent({+ actionType: 'write_memory',+ confidence: 0.55,+ evidenceRefs: [{ id: 'msg-2', type: 'message' }],+ idempotencyKey: 'intent-2',+ intentType: 'memory',+ mode: 'reflection',+ rationale: 'Same preference.',+ risk: 'low',+ target: { memoryId: 'memory-1' },+ urgency: 'later',+ }),+ ])[0];++ expect(squashSelfFeedbackIntentGroup(group).evidenceStrength).toBe('strong');+ });++ /**+ * @example+ * immediate candidates sort before soon and later candidates.+ */+ it('ranks immediate urgency before soon and later', () => {+ const ranked = rankSelfFeedbackCandidates(+ groupSelfFeedbackIntents(+ ['later', 'immediate', 'soon'].map((urgency, index) =>+ normalizeReflectionIntent({+ actionType: 'write_memory',+ confidence: 0.8,+ evidenceRefs: [{ id: `msg-${index}`, type: 'message' }],+ idempotencyKey: `intent-${index}`,+ intentType: 'memory',+ mode: 'reflection',+ rationale: 'Remember preference.',+ risk: 'low',+ target: { memoryId: `memory-${index}` },+ urgency: urgency as 'immediate' | 'later' | 'soon',+ }),+ ),+ ),+ );++ expect(ranked.map((candidate) => candidate.intent.urgency)).toEqual([+ 'immediate',+ 'soon',+ 'later',+ ]);+ });++ /**+ * @example+ * strong candidates with operation payloads become proposal-priority evidence.+ */+ it('marks strong candidates with target or operation as proposal-priority evidence', () => {+ const [candidate] = rankSelfFeedbackCandidates(+ groupSelfFeedbackIntents([+ normalizeReflectionIntent({+ actionType: 'refine_skill',+ confidence: 0.9,+ evidenceRefs: [{ id: 'msg-1', type: 'message' }],+ idempotencyKey: 'intent-1',+ intentType: 'skill',+ mode: 'reflection',+ operation: {+ domain: 'skill',+ input: {+ bodyMarkdown: '# Skill',+ skillDocumentId: 'skill-1',+ userId: 'user-1',+ },+ operation: 'refine',+ },+ rationale: 'Refine checklist.',+ risk: 'medium',+ target: { skillDocumentId: 'skill-1' },+ urgency: 'soon',+ }),+ ]),+ );++ expect(candidate.reviewBehavior).toBe('proposal_priority');+ expect(getSelfFeedbackIntentTargetSignature(candidate.intent)).toBe('skill:skill-1');+ });+});diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/proposal.test.ts b/src/server/services/agentSignal/services/selfIteration/review/__test__/proposal.test.tssimilarity index 76%rename from src/server/services/agentSignal/services/maintenance/__tests__/proposal.test.tsrename to src/server/services/agentSignal/services/selfIteration/review/__test__/proposal.test.tsindex 4a79f4ff926..4c309ac13c0 100644--- a/src/server/services/agentSignal/services/maintenance/__tests__/proposal.test.ts+++ b/src/server/services/agentSignal/services/selfIteration/review/__test__/proposal.test.ts@@ -1,33 +1,28 @@import { describe, expect, it } from 'vitest';-import type { MaintenanceProposalMetadata, MaintenanceProposalPlan } from '../proposal';+import { ActionStatus, ApplyMode, Risk, Scope } from '../../types';+import type { SelfReviewProposalMetadata, SelfReviewProposalPlan } from '../proposal';import {- buildMaintenanceProposalFromPlan,- buildMaintenanceProposalKey,+ buildSelfReviewProposalFromPlan,+ buildSelfReviewProposalKey,getNextProposalExpiry,- isMaintenanceProposalMetadata,- refreshMaintenanceProposal,- shouldRefreshMaintenanceProposal,- shouldSupersedeMaintenanceProposal,- supersedeMaintenanceProposal,+ isSelfReviewProposalMetadata,+ refreshSelfReviewProposal,+ shouldRefreshSelfReviewProposal,+ shouldSupersedeSelfReviewProposal,+ supersedeSelfReviewProposal,} from '../proposal';-import {- MaintenanceActionStatus,- MaintenanceApplyMode,- MaintenanceReviewScope,- MaintenanceRisk,-} from '../types';const validProposalMetadata = (- overrides: Partial<MaintenanceProposalMetadata> = {},-): MaintenanceProposalMetadata => ({+ overrides: Partial<SelfReviewProposalMetadata> = {},+): SelfReviewProposalMetadata => ({actions: [{actionType: 'refine_skill',evidenceRefs: [{ id: 'topic_1', type: 'topic' }],idempotencyKey: 'source:refine_skill:skill:adoc_1',rationale: 'Refine the skill.',- risk: MaintenanceRisk.Medium,+ risk: Risk.Medium,target: { skillDocumentId: 'adoc_1' },},],@@ -48,15 +43,15 @@ const malformedProposalMetadata = (overrides: Record<string, unknown>) => ({...overrides,});-describe('maintenance proposal metadata', () => {+describe('self-review proposal metadata', () => {/*** @example- * buildMaintenanceProposalKey({ agentId: 'agt_1', actionType: 'refine_skill' })+ * buildSelfReviewProposalKey({ agentId: 'agt_1', actionType: 'refine_skill' })* returns a deterministic key scoped to target identity.*/it('builds a stable proposal key from target identity', () => {expect(- buildMaintenanceProposalKey({+ buildSelfReviewProposalKey({actionType: 'refine_skill',agentId: 'agt_1',targetId: 'adoc_1',@@ -87,11 +82,11 @@ describe('maintenance proposal metadata', () => {/*** @example- * shouldRefreshMaintenanceProposal({ existing: pendingSameKey }) returns refresh true.+ * shouldRefreshSelfReviewProposal({ existing: pendingSameKey }) returns refresh true.*/it('refreshes only compatible pending proposals before expiry', () => {expect(- shouldRefreshMaintenanceProposal({+ shouldRefreshSelfReviewProposal({existing: {actionType: 'refine_skill',expiresAt: '2026-05-12T00:00:00.000Z',@@ -109,11 +104,11 @@ describe('maintenance proposal metadata', () => {/*** @example- * shouldSupersedeMaintenanceProposal({ existing, incoming }) returns supersede true for incompatible operations.+ * shouldSupersedeSelfReviewProposal({ existing, incoming }) returns supersede true for incompatible operations.*/it('supersedes incompatible pending proposals with the same key', () => {expect(- shouldSupersedeMaintenanceProposal({+ shouldSupersedeSelfReviewProposal({existing: validProposalMetadata({actions: [{@@ -126,7 +121,7 @@ describe('maintenance proposal metadata', () => {operation: 'refine',},rationale: 'old rationale',- risk: MaintenanceRisk.Medium,+ risk: Risk.Medium,target: { skillDocumentId: 'adoc_1' },},],@@ -143,7 +138,7 @@ describe('maintenance proposal metadata', () => {operation: 'create',},rationale: 'new rationale',- risk: MaintenanceRisk.Medium,+ risk: Risk.Medium,target: { skillName: 'new-skill' },},],@@ -155,7 +150,7 @@ describe('maintenance proposal metadata', () => {/*** @example- * shouldSupersedeMaintenanceProposal({ existing, incoming }) ignores rationale-only changes.+ * shouldSupersedeSelfReviewProposal({ existing, incoming }) ignores rationale-only changes.*/it('keeps equivalent operations compatible even when rationale changes', () => {const existing = validProposalMetadata({@@ -170,7 +165,7 @@ describe('maintenance proposal metadata', () => {operation: 'refine',},rationale: 'old rationale',- risk: MaintenanceRisk.Medium,+ risk: Risk.Medium,target: { skillDocumentId: 'adoc_1' },},],@@ -187,14 +182,14 @@ describe('maintenance proposal metadata', () => {operation: 'refine',},rationale: 'new rationale',- risk: MaintenanceRisk.Medium,+ risk: Risk.Medium,target: { skillDocumentId: 'adoc_1' },},],});expect(- shouldSupersedeMaintenanceProposal({+ shouldSupersedeSelfReviewProposal({existing,incoming,now: '2026-05-10T00:00:00.000Z',@@ -204,7 +199,7 @@ describe('maintenance proposal metadata', () => {/*** @example- * refreshMaintenanceProposal({ existing, incoming }) preserves createdAt and refreshes expiry.+ * refreshSelfReviewProposal({ existing, incoming }) preserves createdAt and refreshes expiry.*/it('refreshes proposal actions and expiry while preserving proposal identity', () => {const existing = validProposalMetadata({@@ -218,7 +213,7 @@ describe('maintenance proposal metadata', () => {evidenceRefs: [{ id: 'msg_new', type: 'message' }],idempotencyKey: 'new',rationale: 'new rationale',- risk: MaintenanceRisk.Medium,+ risk: Risk.Medium,target: { skillDocumentId: 'adoc_1' },},],@@ -227,7 +222,7 @@ describe('maintenance proposal metadata', () => {});expect(- refreshMaintenanceProposal({+ refreshSelfReviewProposal({existing,incoming,now: '2026-05-10T00:00:00.000Z',@@ -245,11 +240,11 @@ describe('maintenance proposal metadata', () => {/*** @example- * supersedeMaintenanceProposal({ existing, supersededBy }) marks the old proposal inactive.+ * supersedeSelfReviewProposal({ existing, supersededBy }) marks the old proposal inactive.*/it('marks superseded proposals with replacement identity', () => {expect(- supersedeMaintenanceProposal({+ supersedeSelfReviewProposal({existing: validProposalMetadata(),now: '2026-05-10T00:00:00.000Z',supersededBy: 'brief_new',@@ -263,55 +258,53 @@ describe('maintenance proposal metadata', () => {/*** @example- * isMaintenanceProposalMetadata({ status: 'pending' }) returns false.+ * isSelfReviewProposalMetadata({ status: 'pending' }) returns false.*/it('does not accept arbitrary metadata as proposal metadata', () => {- expect(isMaintenanceProposalMetadata({ status: 'pending' })).toBe(false);- expect(isMaintenanceProposalMetadata(validProposalMetadata({ actions: [] }))).toBe(true);+ expect(isSelfReviewProposalMetadata({ status: 'pending' })).toBe(false);+ expect(isSelfReviewProposalMetadata(validProposalMetadata({ actions: [] }))).toBe(true);expect(- isMaintenanceProposalMetadata(malformedProposalMetadata({ actionType: 'delete_everything' })),+ isSelfReviewProposalMetadata(malformedProposalMetadata({ actionType: 'delete_everything' })),).toBe(false);- expect(isMaintenanceProposalMetadata(malformedProposalMetadata({ status: 'archived' }))).toBe(+ expect(isSelfReviewProposalMetadata(malformedProposalMetadata({ status: 'archived' }))).toBe(false,);});/*** @example- * isMaintenanceProposalMetadata({ actions: [{}] }) returns false.+ * isSelfReviewProposalMetadata({ actions: [{}] }) returns false.*/it('rejects malformed proposal action metadata entries', () => {const validAction = validProposalMetadata().actions[0];const malformedProposalAction = (overrides: Record<string, unknown>) =>malformedProposalMetadata({ actions: [{ ...validAction, ...overrides }] });- expect(isMaintenanceProposalMetadata(malformedProposalMetadata({ actions: [{}] }))).toBe(false);- expect(- isMaintenanceProposalMetadata(malformedProposalAction({ evidenceRefs: undefined })),- ).toBe(false);- expect(- isMaintenanceProposalMetadata(malformedProposalAction({ idempotencyKey: undefined })),- ).toBe(false);- expect(isMaintenanceProposalMetadata(malformedProposalAction({ rationale: undefined }))).toBe(+ expect(isSelfReviewProposalMetadata(malformedProposalMetadata({ actions: [{}] }))).toBe(false);+ expect(isSelfReviewProposalMetadata(malformedProposalAction({ evidenceRefs: undefined }))).toBe(false,);- expect(isMaintenanceProposalMetadata(malformedProposalAction({ risk: undefined }))).toBe(false);expect(- isMaintenanceProposalMetadata(malformedProposalAction({ actionType: 'delete_everything' })),+ isSelfReviewProposalMetadata(malformedProposalAction({ idempotencyKey: undefined })),).toBe(false);- expect(isMaintenanceProposalMetadata(malformedProposalAction({ risk: 'critical' }))).toBe(+ expect(isSelfReviewProposalMetadata(malformedProposalAction({ rationale: undefined }))).toBe(false,);+ expect(isSelfReviewProposalMetadata(malformedProposalAction({ risk: undefined }))).toBe(false);+ expect(+ isSelfReviewProposalMetadata(malformedProposalAction({ actionType: 'delete_everything' })),+ ).toBe(false);+ expect(isSelfReviewProposalMetadata(malformedProposalAction({ risk: 'critical' }))).toBe(false);});/*** @example- * buildMaintenanceProposalFromPlan({ plan }) stores the complete refine base snapshot.+ * buildSelfReviewProposalFromPlan({ plan }) stores the complete refine base snapshot.*/it('stores complete base snapshots on mergeable refine_skill proposals', () => {const action = {actionType: 'refine_skill' as const,- applyMode: MaintenanceApplyMode.ProposalOnly,+ applyMode: ApplyMode.ProposalOnly,baseSnapshot: {agentDocumentId: 'adoc_1',contentHash: 'sha256:base',@@ -334,10 +327,10 @@ describe('maintenance proposal metadata', () => {operation: 'refine' as const,},rationale: 'Refine the reusable review skill.',- risk: MaintenanceRisk.Medium,+ risk: Risk.Medium,target: { skillDocumentId: 'adoc_1' },};- const proposal = buildMaintenanceProposalFromPlan({+ const proposal = buildSelfReviewProposalFromPlan({agentId: 'agt_1',evidenceWindowEnd: '2026-05-09T02:00:00.000Z',evidenceWindowStart: '2026-05-09T00:00:00.000Z',@@ -345,13 +338,13 @@ describe('maintenance proposal metadata', () => {plan: {actions: [action],plannerVersion: 'test-planner',- reviewScope: MaintenanceReviewScope.Nightly,+ reviewScope: Scope.Nightly,summary: 'Review found a skill refinement proposal.',},results: [{idempotencyKey: 'source:refine_skill:skill:adoc_1',- status: MaintenanceActionStatus.Proposed,+ status: ActionStatus.Proposed,},],});@@ -368,7 +361,7 @@ describe('maintenance proposal metadata', () => {/*** @example- * buildMaintenanceProposalFromPlan({ plan: missingSnapshotPlan }) throws before storing.+ * buildSelfReviewProposalFromPlan({ plan: missingSnapshotPlan }) throws before storing.*/it('rejects mergeable refine_skill proposal actions without required base snapshots', () => {const buildProposal = (action: {@@ -386,7 +379,7 @@ describe('maintenance proposal metadata', () => {actions: [{...action,- applyMode: MaintenanceApplyMode.ProposalOnly,+ applyMode: ApplyMode.ProposalOnly,confidence: 0.92,dedupeKey: 'skill:adoc_1',evidenceRefs: [{ id: 'topic_1', type: 'topic' }],@@ -401,16 +394,16 @@ describe('maintenance proposal metadata', () => {operation: 'refine',},rationale: 'Refine the reusable review skill.',- risk: MaintenanceRisk.Medium,+ risk: Risk.Medium,target: { skillDocumentId: 'adoc_1' },},],plannerVersion: 'test-planner',- reviewScope: MaintenanceReviewScope.Nightly,+ reviewScope: Scope.Nightly,summary: 'Review found a skill refinement proposal.',};- return buildMaintenanceProposalFromPlan({+ return buildSelfReviewProposalFromPlan({agentId: 'agt_1',evidenceWindowEnd: '2026-05-09T02:00:00.000Z',evidenceWindowStart: '2026-05-09T00:00:00.000Z',@@ -419,11 +412,11 @@ describe('maintenance proposal metadata', () => {// This intentionally bypasses the compile-time snapshot requirement.// The test exercises runtime validation for malformed persisted/runtime proposal data.// Remove this cast when malformed projection plans can no longer reach this boundary.- plan: malformedPlan as unknown as MaintenanceProposalPlan,+ plan: malformedPlan as unknown as SelfReviewProposalPlan,results: [{idempotencyKey: 'source:refine_skill:skill:adoc_1',- status: MaintenanceActionStatus.Proposed,+ status: ActionStatus.Proposed,},],});@@ -450,12 +443,12 @@ describe('maintenance proposal metadata', () => {/*** @example- * buildMaintenanceProposalFromPlan({ plan }) stores the absent create snapshot.+ * buildSelfReviewProposalFromPlan({ plan }) stores the absent create snapshot.*/it('accepts complete absent snapshots on mergeable create_skill proposals', () => {const action = {actionType: 'create_skill' as const,- applyMode: MaintenanceApplyMode.ProposalOnly,+ applyMode: ApplyMode.ProposalOnly,baseSnapshot: {absent: true,skillName: 'code-review',@@ -476,10 +469,10 @@ describe('maintenance proposal metadata', () => {operation: 'create' as const,},rationale: 'Create a reusable review skill.',- risk: MaintenanceRisk.Medium,+ risk: Risk.Medium,target: { skillName: 'code-review' },};- const proposal = buildMaintenanceProposalFromPlan({+ const proposal = buildSelfReviewProposalFromPlan({agentId: 'agt_1',evidenceWindowEnd: '2026-05-09T02:00:00.000Z',evidenceWindowStart: '2026-05-09T00:00:00.000Z',@@ -487,13 +480,13 @@ describe('maintenance proposal metadata', () => {plan: {actions: [action],plannerVersion: 'test-planner',- reviewScope: MaintenanceReviewScope.Nightly,+ reviewScope: Scope.Nightly,summary: 'Review found a skill creation proposal.',},results: [{idempotencyKey: 'source:create_skill:skill:code-review',- status: MaintenanceActionStatus.Proposed,+ status: ActionStatus.Proposed,},],});@@ -507,7 +500,7 @@ describe('maintenance proposal metadata', () => {/*** @example- * buildMaintenanceProposalFromPlan({ plan: incompleteAbsentSnapshotPlan }) throws.+ * buildSelfReviewProposalFromPlan({ plan: incompleteAbsentSnapshotPlan }) throws.*/it('rejects missing or incomplete absent snapshots on mergeable create_skill proposals', () => {const buildProposal = (action: {@@ -522,7 +515,7 @@ describe('maintenance proposal metadata', () => {actions: [{...action,- applyMode: MaintenanceApplyMode.ProposalOnly,+ applyMode: ApplyMode.ProposalOnly,confidence: 0.92,dedupeKey: 'skill:code-review',evidenceRefs: [{ id: 'topic_1', type: 'topic' }],@@ -537,16 +530,16 @@ describe('maintenance proposal metadata', () => {operation: 'create',},rationale: 'Create a reusable review skill.',- risk: MaintenanceRisk.Medium,+ risk: Risk.Medium,target: { skillName: 'code-review' },},],plannerVersion: 'test-planner',- reviewScope: MaintenanceReviewScope.Nightly,+ reviewScope: Scope.Nightly,summary: 'Review found a skill creation proposal.',};- return buildMaintenanceProposalFromPlan({+ return buildSelfReviewProposalFromPlan({agentId: 'agt_1',evidenceWindowEnd: '2026-05-09T02:00:00.000Z',evidenceWindowStart: '2026-05-09T00:00:00.000Z',@@ -555,11 +548,11 @@ describe('maintenance proposal metadata', () => {// This intentionally bypasses the compile-time snapshot requirement.// The test exercises runtime validation for malformed persisted/runtime proposal data.// Remove this cast when malformed projection plans can no longer reach this boundary.- plan: malformedPlan as unknown as MaintenanceProposalPlan,+ plan: malformedPlan as unknown as SelfReviewProposalPlan,results: [{idempotencyKey: 'source:create_skill:skill:code-review',- status: MaintenanceActionStatus.Proposed,+ status: ActionStatus.Proposed,},],});@@ -583,10 +576,10 @@ describe('maintenance proposal metadata', () => {/*** @example- * buildMaintenanceProposalFromPlan({ plan }) keeps target title fallback for consolidate actions.+ * buildSelfReviewProposalFromPlan({ plan }) keeps target title fallback for consolidate actions.*/it('stores targetTitle fallback on non-mergeable skill proposals', () => {- const proposal = buildMaintenanceProposalFromPlan({+ const proposal = buildSelfReviewProposalFromPlan({agentId: 'agt_1',evidenceWindowEnd: '2026-05-09T02:00:00.000Z',evidenceWindowStart: '2026-05-09T00:00:00.000Z',@@ -595,7 +588,7 @@ describe('maintenance proposal metadata', () => {actions: [{actionType: 'consolidate_skill',- applyMode: MaintenanceApplyMode.ProposalOnly,+ applyMode: ApplyMode.ProposalOnly,confidence: 0.92,dedupeKey: 'skill:review-practices',evidenceRefs: [{ id: 'topic_1', type: 'topic' }],@@ -611,18 +604,18 @@ describe('maintenance proposal metadata', () => {operation: 'consolidate',},rationale: 'Consolidate overlapping review skills.',- risk: MaintenanceRisk.Medium,+ risk: Risk.Medium,target: { skillName: 'Review Practices' },},],plannerVersion: 'test-planner',- reviewScope: MaintenanceReviewScope.Nightly,+ reviewScope: Scope.Nightly,summary: 'Review found a skill consolidation proposal.',},results: [{idempotencyKey: 'source:consolidate_skill:skill:review-practices',- status: MaintenanceActionStatus.Proposed,+ status: ActionStatus.Proposed,},],});@@ -634,11 +627,11 @@ describe('maintenance proposal metadata', () => {/*** @example- * buildMaintenanceProposalFromPlan({ plan: noopPlan }) returns undefined for proposed noop actions.+ * buildSelfReviewProposalFromPlan({ plan: noopPlan }) returns undefined for proposed noop actions.*/it('does not build proposal metadata from proposed noop actions', () => {expect(- buildMaintenanceProposalFromPlan({+ buildSelfReviewProposalFromPlan({agentId: 'agt_1',evidenceWindowEnd: '2026-05-09T02:00:00.000Z',evidenceWindowStart: '2026-05-09T00:00:00.000Z',@@ -647,23 +640,23 @@ describe('maintenance proposal metadata', () => {actions: [{actionType: 'noop',- applyMode: MaintenanceApplyMode.ProposalOnly,+ applyMode: ApplyMode.ProposalOnly,confidence: 0.92,dedupeKey: 'noop:quiet',evidenceRefs: [{ id: 'topic_1', type: 'topic' }],idempotencyKey: 'source:noop:quiet',- rationale: 'No maintenance change is needed.',- risk: MaintenanceRisk.Low,+ rationale: 'No self-iteration change is needed.',+ risk: Risk.Low,},],plannerVersion: 'test-planner',- reviewScope: MaintenanceReviewScope.Nightly,+ reviewScope: Scope.Nightly,summary: 'Review found no actionable proposal.',},results: [{idempotencyKey: 'source:noop:quiet',- status: MaintenanceActionStatus.Proposed,+ status: ActionStatus.Proposed,},],}),diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/proposalApply.test.ts b/src/server/services/agentSignal/services/selfIteration/review/__test__/proposalApply.test.tssimilarity index 93%rename from src/server/services/agentSignal/services/maintenance/__tests__/proposalApply.test.tsrename to src/server/services/agentSignal/services/selfIteration/review/__test__/proposalApply.test.tsindex 1d20527828d..9fd7dc0413b 100644--- a/src/server/services/agentSignal/services/maintenance/__tests__/proposalApply.test.ts+++ b/src/server/services/agentSignal/services/selfIteration/review/__test__/proposalApply.test.ts@@ -1,10 +1,10 @@import { SpanStatusCode } from '@lobechat/observability-otel/api';import { beforeEach, describe, expect, it, vi } from 'vitest';-import type { MaintenanceProposalMetadata } from '../proposal';-import { createMaintenanceProposalApplyService } from '../proposalApply';-import type { RefineMaintenanceSkillInput } from '../skill';-import { MaintenanceRisk } from '../types';+import type { SkillRefineInput } from '../../tools/shared';+import { Risk } from '../../types';+import type { SelfReviewProposalMetadata } from '../proposal';+import { createSelfReviewProposalApplyService } from '../proposalApply';const { spanEnd, spanSetAttribute, spanSetStatus, startActiveSpan } = vi.hoisted(() => {interface MockSpan {@@ -35,8 +35,8 @@ vi.mock('@lobechat/observability-otel/modules/agent-signal', () => ({}));const createProposal = (- overrides: Partial<MaintenanceProposalMetadata> = {},-): MaintenanceProposalMetadata => ({+ overrides: Partial<SelfReviewProposalMetadata> = {},+): SelfReviewProposalMetadata => ({actionType: 'refine_skill',actions: [{@@ -58,11 +58,11 @@ const createProposal = (description: 'Updated review workflow.',skillDocumentId: 'adoc_1',userId: 'user_1',- } as unknown as RefineMaintenanceSkillInput,+ } as unknown as SkillRefineInput,operation: 'refine' as const,},rationale: 'Keep the skill up to date.',- risk: MaintenanceRisk.Medium,+ risk: Risk.Medium,target: { skillDocumentId: 'adoc_1' },},],@@ -77,7 +77,7 @@ const createProposal = (...overrides,});-describe('maintenance proposal apply service', () => {+describe('self-review proposal apply service', () => {beforeEach(() => {vi.clearAllMocks();});@@ -94,7 +94,7 @@ describe('maintenance proposal apply service', () => {});const createSkillIfAbsent = vi.fn();const updateProposal = vi.fn();- const service = createMaintenanceProposalApplyService({+ const service = createSelfReviewProposalApplyService({checkAction: vi.fn().mockResolvedValue({ allowed: true }),checkGates: vi.fn().mockResolvedValue({ allowed: true }),now: () => '2026-05-09T01:00:00.000Z',@@ -140,7 +140,7 @@ describe('maintenance proposal apply service', () => {]);expect(updateProposal).toHaveBeenCalledWith(result.proposal);expect(startActiveSpan).toHaveBeenCalledWith(- 'agent_signal.maintenance_proposal.apply',+ 'agent_signal.self_review_proposal.apply',expect.objectContaining({attributes: expect.objectContaining({'agent.signal.agent_id': 'agt_1',@@ -172,7 +172,7 @@ describe('maintenance proposal apply service', () => {summary: 'Skill already created.',});const replaceSkillContentCAS = vi.fn();- const service = createMaintenanceProposalApplyService({+ const service = createSelfReviewProposalApplyService({checkAction: vi.fn().mockResolvedValue({ allowed: true }),checkGates: vi.fn().mockResolvedValue({ allowed: true }),now: () => '2026-05-09T01:00:00.000Z',@@ -209,7 +209,7 @@ describe('maintenance proposal apply service', () => {operation: 'create',},rationale: 'Create a managed skill.',- risk: MaintenanceRisk.Medium,+ risk: Risk.Medium,target: { skillName: 'code-review' },},],@@ -250,7 +250,7 @@ describe('maintenance proposal apply service', () => {it('skips stale proposal actions without calling safe tools', async () => {const createSkillIfAbsent = vi.fn();const replaceSkillContentCAS = vi.fn();- const service = createMaintenanceProposalApplyService({+ const service = createSelfReviewProposalApplyService({checkAction: vi.fn().mockResolvedValue({ allowed: false, reason: 'document_changed' }),checkGates: vi.fn().mockResolvedValue({ allowed: true }),now: () => '2026-05-09T01:00:00.000Z',@@ -296,7 +296,7 @@ describe('maintenance proposal apply service', () => {status: 'applied',summary: 'Consolidated managed skill.',});- const service = createMaintenanceProposalApplyService({+ const service = createSelfReviewProposalApplyService({checkAction: vi.fn().mockResolvedValue({ allowed: true }),checkGates: vi.fn().mockResolvedValue({ allowed: true }),now: () => '2026-05-09T01:00:00.000Z',@@ -335,7 +335,7 @@ describe('maintenance proposal apply service', () => {operation: 'consolidate',},rationale: 'Merge overlapping skills.',- risk: MaintenanceRisk.High,+ risk: Risk.High,target: { skillDocumentId: 'adoc_1' },},],diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/proposalPreflight.test.ts b/src/server/services/agentSignal/services/selfIteration/review/__test__/proposalPreflight.test.tssimilarity index 87%rename from src/server/services/agentSignal/services/maintenance/__tests__/proposalPreflight.test.tsrename to src/server/services/agentSignal/services/selfIteration/review/__test__/proposalPreflight.test.tsindex 4da4df574bf..246c043896a 100644--- a/src/server/services/agentSignal/services/maintenance/__tests__/proposalPreflight.test.ts+++ b/src/server/services/agentSignal/services/selfIteration/review/__test__/proposalPreflight.test.ts@@ -1,8 +1,8 @@import { describe, expect, it, vi } from 'vitest';-import type { MaintenanceProposalPreflightAdapters } from '../proposalPreflight';-import { createMaintenanceProposalPreflightService } from '../proposalPreflight';-import { MaintenanceRisk } from '../types';+import { Risk } from '../../types';+import type { SelfReviewProposalPreflightAdapters } from '../proposalPreflight';+import { createSelfReviewProposalPreflightService } from '../proposalPreflight';const createRefineAction = (contentHash = 'sha256:base') => ({actionType: 'refine_skill' as const,@@ -23,7 +23,7 @@ const createRefineAction = (contentHash = 'sha256:base') => ({operation: 'refine' as const,},rationale: 'Update skill',- risk: MaintenanceRisk.Medium,+ risk: Risk.Medium,target: { skillDocumentId: 'adoc_1' },});@@ -48,7 +48,7 @@ const createCreateAction = () => ({operation: 'create' as const,},rationale: 'Create skill',- risk: MaintenanceRisk.Medium,+ risk: Risk.Medium,target: { skillName: 'code-review' },});@@ -94,7 +94,7 @@ const createConsolidateAction = () => ({operation: 'consolidate' as const,},rationale: 'Merge overlapping review skills.',- risk: MaintenanceRisk.Medium,+ risk: Risk.Medium,target: { skillDocumentId: 'adoc_1' },});@@ -120,8 +120,8 @@ const createSnapshotReader = () =>);const createAdapters = (- overrides: Partial<MaintenanceProposalPreflightAdapters> = {},-): MaintenanceProposalPreflightAdapters => ({+ overrides: Partial<SelfReviewProposalPreflightAdapters> = {},+): SelfReviewProposalPreflightAdapters => ({isSkillNameAvailable: async () => true,readSkillTargetSnapshot: async () => ({agentDocumentId: 'adoc_1',@@ -134,14 +134,14 @@ const createAdapters = (...overrides,});-describe('maintenance proposal preflight', () => {+describe('self-review proposal preflight', () => {/*** @example* expect(result.allowed).toBe(true);*/it('allows fresh refine_skill proposals with matching snapshot', async () => {const readSkillTargetSnapshot = vi.fn(createAdapters().readSkillTargetSnapshot);- const service = createMaintenanceProposalPreflightService(+ const service = createSelfReviewProposalPreflightService(createAdapters({ readSkillTargetSnapshot }),);@@ -154,7 +154,7 @@ describe('maintenance proposal preflight', () => {* expect(result.reason).toBe('content_changed');*/it('rejects drifted refine_skill when content hash changed', async () => {- const service = createMaintenanceProposalPreflightService({+ const service = createSelfReviewProposalPreflightService({...createAdapters(),readSkillTargetSnapshot: async () => ({agentDocumentId: 'adoc_1',@@ -177,7 +177,7 @@ describe('maintenance proposal preflight', () => {* expect(result.reason).toBe('target_type_changed');*/it('rejects refine_skill when frozen target identity drifts from the base snapshot', async () => {- const service = createMaintenanceProposalPreflightService(createAdapters());+ const service = createSelfReviewProposalPreflightService(createAdapters());const action = createRefineAction();await expect(@@ -196,7 +196,7 @@ describe('maintenance proposal preflight', () => {* expect(result.reason).toBe('target_type_changed');*/it('rejects refine_skill when frozen operation identity drifts from the base snapshot', async () => {- const service = createMaintenanceProposalPreflightService(createAdapters());+ const service = createSelfReviewProposalPreflightService(createAdapters());const action = createRefineAction();await expect(@@ -218,7 +218,7 @@ describe('maintenance proposal preflight', () => {* expect(result.reason).toBe('target_unmanaged');*/it('rejects unmanaged targets', async () => {- const service = createMaintenanceProposalPreflightService({+ const service = createSelfReviewProposalPreflightService({...createAdapters(),readSkillTargetSnapshot: async () => ({agentDocumentId: 'adoc_1',@@ -240,7 +240,7 @@ describe('maintenance proposal preflight', () => {* expect(result.reason).toBe('target_not_writable');*/it('rejects readonly targets', async () => {- const service = createMaintenanceProposalPreflightService({+ const service = createSelfReviewProposalPreflightService({...createAdapters(),readSkillTargetSnapshot: async () => ({agentDocumentId: 'adoc_1',@@ -262,7 +262,7 @@ describe('maintenance proposal preflight', () => {* expect(result.reason).toBe('snapshot_missing');*/it('does not report missing base snapshots as target_deleted', async () => {- const service = createMaintenanceProposalPreflightService(createAdapters());+ const service = createSelfReviewProposalPreflightService(createAdapters());const action = createRefineAction();const { baseSnapshot: _baseSnapshot, ...actionWithoutSnapshot } = action;@@ -277,7 +277,7 @@ describe('maintenance proposal preflight', () => {* expect(result.reason).toBe('snapshot_incomplete');*/it('rejects incomplete refine_skill base snapshots', async () => {- const service = createMaintenanceProposalPreflightService(createAdapters());+ const service = createSelfReviewProposalPreflightService(createAdapters());const action = createRefineAction();const { contentHash: _contentHash, ...incompleteSnapshot } = action.baseSnapshot;@@ -297,7 +297,7 @@ describe('maintenance proposal preflight', () => {* expect(result.reason).toBe('target_deleted');*/it('rejects missing targets', async () => {- const service = createMaintenanceProposalPreflightService({+ const service = createSelfReviewProposalPreflightService({...createAdapters(),readSkillTargetSnapshot: async () => undefined,});@@ -314,7 +314,7 @@ describe('maintenance proposal preflight', () => {*/it('allows create_skill proposals when stable name is still absent', async () => {const isSkillNameAvailable = vi.fn(async () => true);- const service = createMaintenanceProposalPreflightService(+ const service = createSelfReviewProposalPreflightService(createAdapters({ isSkillNameAvailable }),);@@ -330,7 +330,7 @@ describe('maintenance proposal preflight', () => {* expect(result.reason).toBe('target_conflict');*/it('rejects create_skill proposals when stable name is now taken', async () => {- const service = createMaintenanceProposalPreflightService(+ const service = createSelfReviewProposalPreflightService(createAdapters({ isSkillNameAvailable: async () => false }),);@@ -345,7 +345,7 @@ describe('maintenance proposal preflight', () => {* expect(result.reason).toBe('target_type_changed');*/it('rejects create_skill when frozen target name drifts from the base snapshot', async () => {- const service = createMaintenanceProposalPreflightService(createAdapters());+ const service = createSelfReviewProposalPreflightService(createAdapters());const action = createCreateAction();await expect(@@ -364,7 +364,7 @@ describe('maintenance proposal preflight', () => {* expect(result.reason).toBe('target_type_changed');*/it('rejects create_skill when frozen operation name drifts from the base snapshot', async () => {- const service = createMaintenanceProposalPreflightService(createAdapters());+ const service = createSelfReviewProposalPreflightService(createAdapters());const action = createCreateAction();await expect(@@ -387,7 +387,7 @@ describe('maintenance proposal preflight', () => {*/it('allows consolidate_skill proposals when canonical and source snapshots are fresh', async () => {const readSkillTargetSnapshot = createSnapshotReader();- const service = createMaintenanceProposalPreflightService(+ const service = createSelfReviewProposalPreflightService(createAdapters({ readSkillTargetSnapshot }),);@@ -403,7 +403,7 @@ describe('maintenance proposal preflight', () => {* expect(result.reason).toBe('content_changed');*/it('rejects consolidate_skill proposals when a source snapshot changed', async () => {- const service = createMaintenanceProposalPreflightService(+ const service = createSelfReviewProposalPreflightService(createAdapters({readSkillTargetSnapshot: async (skillDocumentId) =>skillDocumentId === 'adoc_2'@@ -435,7 +435,7 @@ describe('maintenance proposal preflight', () => {* expect(result.reason).toBe('unsupported');*/it('keeps unsupported actions unsupported', async () => {- const service = createMaintenanceProposalPreflightService(createAdapters());+ const service = createSelfReviewProposalPreflightService(createAdapters());const action = createRefineAction();await expect(service.checkAction({ ...action, actionType: 'proposal_only' })).resolves.toEqual({diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/proposalSnapshot.test.ts b/src/server/services/agentSignal/services/selfIteration/review/__test__/proposalSnapshot.test.tssimilarity index 88%rename from src/server/services/agentSignal/services/maintenance/__tests__/proposalSnapshot.test.tsrename to src/server/services/agentSignal/services/selfIteration/review/__test__/proposalSnapshot.test.tsindex bfd866daeeb..e79b0623e70 100644--- a/src/server/services/agentSignal/services/maintenance/__tests__/proposalSnapshot.test.ts+++ b/src/server/services/agentSignal/services/selfIteration/review/__test__/proposalSnapshot.test.ts@@ -1,8 +1,8 @@import { describe, expect, it, vi } from 'vitest';-import { createMaintenanceProposalSnapshotService } from '../proposalSnapshot';+import { createSelfReviewProposalSnapshotService } from '../proposalSnapshot';-describe('maintenance proposal snapshot service', () => {+describe('self-review proposal snapshot service', () => {/*** @example* expect(snapshot).toEqual({ targetType: 'skill', contentHash: 'sha256:base' });@@ -17,7 +17,7 @@ describe('maintenance proposal snapshot service', () => {targetTitle: 'Code Review',writable: true,}));- const service = createMaintenanceProposalSnapshotService({+ const service = createSelfReviewProposalSnapshotService({isSkillNameAvailable: async () => true,readSkillTargetSnapshot,});@@ -48,7 +48,7 @@ describe('maintenance proposal snapshot service', () => {*/it('captures absent-target snapshots for create_skill', async () => {const isSkillNameAvailable = vi.fn(async () => true);- const service = createMaintenanceProposalSnapshotService({+ const service = createSelfReviewProposalSnapshotService({isSkillNameAvailable,readSkillTargetSnapshot: async () => undefined,});@@ -78,7 +78,7 @@ describe('maintenance proposal snapshot service', () => {* expect(capture).rejects.toThrow('Skill name is already taken');*/it('rejects create_skill snapshots when the stable skill name is already taken', async () => {- const service = createMaintenanceProposalSnapshotService({+ const service = createSelfReviewProposalSnapshotService({isSkillNameAvailable: async () => false,readSkillTargetSnapshot: async () => undefined,});diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/nightlySchedule.test.ts b/src/server/services/agentSignal/services/selfIteration/review/__test__/schedule.test.tssimilarity index 96%rename from src/server/services/agentSignal/services/maintenance/__tests__/nightlySchedule.test.tsrename to src/server/services/agentSignal/services/selfIteration/review/__test__/schedule.test.tsindex 84b06a434cd..275e535d84a 100644--- a/src/server/services/agentSignal/services/maintenance/__tests__/nightlySchedule.test.ts+++ b/src/server/services/agentSignal/services/selfIteration/review/__test__/schedule.test.ts@@ -8,12 +8,12 @@ import type {ListNightlyReviewEligibleUsersInput,NightlyReviewAgentTarget,NightlyReviewEligibleUser,-} from '../nightlySchedule';+} from '../schedule';import {buildNightlyReviewSourceId,- createNightlyReviewScheduleService,+ createSelfReviewScheduleService,createServerNightlyReviewScheduleService,-} from '../nightlySchedule';+} from '../schedule';const mocks = vi.hoisted(() => ({enqueueAgentSignalSourceEvent: vi.fn(),@@ -66,7 +66,7 @@ describe('nightlyReviewScheduleService', () => {describe('dispatchNightlyReviewRequests', () => {it('enqueues Shanghai user nightly review sources with previous full local day window', async () => {const deps = createDeps(new Date('2026-05-03T18:30:00.000Z'));- const service = createNightlyReviewScheduleService(deps);+ const service = createSelfReviewScheduleService(deps);const summary = await service.dispatchNightlyReviewRequests();@@ -95,7 +95,7 @@ describe('nightlyReviewScheduleService', () => {it('skips users outside the local night window without enqueueing', async () => {const deps = createDeps(new Date('2026-05-03T20:30:00.000Z'));- const service = createNightlyReviewScheduleService(deps);+ const service = createSelfReviewScheduleService(deps);const summary = await service.dispatchNightlyReviewRequests();@@ -113,7 +113,7 @@ describe('nightlyReviewScheduleService', () => {timezone: 'Invalid/Zone',},]);- const service = createNightlyReviewScheduleService(deps);+ const service = createSelfReviewScheduleService(deps);await expect(service.dispatchNightlyReviewRequests()).resolves.toEqual({enqueued: 1,diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/serverRuntime.test.ts b/src/server/services/agentSignal/services/selfIteration/review/__test__/server.test.tssimilarity index 73%rename from src/server/services/agentSignal/services/maintenance/__tests__/serverRuntime.test.tsrename to src/server/services/agentSignal/services/selfIteration/review/__test__/server.test.tsindex 20465295efb..bf71b540c32 100644--- a/src/server/services/agentSignal/services/maintenance/__tests__/serverRuntime.test.ts+++ b/src/server/services/agentSignal/services/selfIteration/review/__test__/server.test.ts@@ -5,30 +5,18 @@ import type { BriefItem } from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';import type * as SkillManagementModule from '@/server/services/skillManagement';-import type * as ToolFirstRuntimeModule from '../agent';-import type { NightlyReviewContext } from '../nightlyCollector';-import {- createServerNightlyReviewPolicyOptions,- listServerProposalActivity,-} from '../serverRuntime';-import { MaintenanceActionStatus, ReviewRunStatus } from '../types';+import type * as ToolFirstRuntimeModule from '../../execute';+import { listServerSelfReviewProposalActivity } from '../../server';+import { ActionStatus, ReviewRunStatus } from '../../types';+import type { NightlyReviewContext } from '../collect';+import { createServerSelfReviewPolicyOptions } from '../server';const mocks = vi.hoisted(() => ({- createMaintenanceExecutorService: vi.fn(() => ({- execute: vi.fn(async () => {- throw new Error('legacy executor must not execute nightly mutations');- }),- })),- createMaintenancePlannerService: vi.fn(() => ({- plan: vi.fn(() => {- throw new Error('legacy planner must not plan nightly mutations');- }),- })),briefCreate: vi.fn(),briefListUnresolvedByAgentAndTrigger: vi.fn(async () => []),briefUpdateMetadata: vi.fn(),initModelRuntimeFromDB: vi.fn(async () => ({ chat: vi.fn() })),- runMaintenanceToolFirstRuntime: vi.fn(),+ executeSelfIteration: vi.fn(),skillReadTargetSnapshot: vi.fn(),skillReplaceSkillIndex: vi.fn(),}));@@ -37,17 +25,9 @@ vi.mock('@/server/modules/ModelRuntime', () => ({initModelRuntimeFromDB: mocks.initModelRuntimeFromDB,}));-vi.mock('../executor', () => ({- createMaintenanceExecutorService: mocks.createMaintenanceExecutorService,-}));--vi.mock('../planner', () => ({- createMaintenancePlannerService: mocks.createMaintenancePlannerService,-}));--vi.mock('../agent', async (importOriginal) => ({+vi.mock('../../execute', async (importOriginal) => ({...(await importOriginal<typeof ToolFirstRuntimeModule>()),- runMaintenanceToolFirstRuntime: mocks.runMaintenanceToolFirstRuntime,+ executeSelfIteration: mocks.executeSelfIteration,}));vi.mock('@/database/models/agentSignal/nightlyReview', () => ({@@ -115,32 +95,36 @@ const baseBrief = (overrides: Partial<BriefItem>): BriefItem => ({const proposalMetadata = (overrides: Record<string, unknown> = {},): NonNullable<BriefItem['metadata']> => ({- proposal: {- actionType: 'refine_skill',- actions: [- {+ agentSignal: {+ nightlySelfReview: {+ selfReviewProposal: {actionType: 'refine_skill',- baseSnapshot: { targetTitle: 'Skill Index' },- evidenceRefs: [- { id: 'topic-1', type: 'topic' },- { id: 'message-1', type: 'message' },+ actions: [+ {+ actionType: 'refine_skill',+ baseSnapshot: { targetTitle: 'Skill Index' },+ evidenceRefs: [+ { id: 'topic-1', type: 'topic' },+ { id: 'message-1', type: 'message' },+ ],+ idempotencyKey: 'source:refine_skill:skill:adoc-1',+ rationale: 'Refine the skill.',+ risk: 'medium',+ target: { skillDocumentId: 'adoc-1' },+ },],- idempotencyKey: 'source:refine_skill:skill:adoc-1',- rationale: 'Refine the skill.',- risk: 'medium',- target: { skillDocumentId: 'adoc-1' },+ createdAt: '2026-05-09T00:00:00.000Z',+ evidenceRefs: [{ id: 'topic-1', type: 'topic' }],+ evidenceWindowEnd: '2026-05-09T02:00:00.000Z',+ evidenceWindowStart: '2026-05-09T00:00:00.000Z',+ expiresAt: '2026-05-12T00:00:00.000Z',+ proposalKey: 'agent-1:refine_skill:agent_document:adoc-1',+ status: 'pending',+ updatedAt: '2026-05-09T01:00:00.000Z',+ version: 1,+ ...overrides,},- ],- createdAt: '2026-05-09T00:00:00.000Z',- evidenceRefs: [{ id: 'topic-1', type: 'topic' }],- evidenceWindowEnd: '2026-05-09T02:00:00.000Z',- evidenceWindowStart: '2026-05-09T00:00:00.000Z',- expiresAt: '2026-05-12T00:00:00.000Z',- proposalKey: 'agent-1:refine_skill:agent_document:adoc-1',- status: 'pending',- updatedAt: '2026-05-09T01:00:00.000Z',- version: 1,- ...overrides,+ },},});@@ -157,7 +141,7 @@ const createNightlyContext = (): NightlyReviewContext => ({notSatisfied: [],satisfied: [],},- maintenanceSignals: [],+ selfReviewSignals: [],managedSkills: [],proposalActivity: {active: [],@@ -177,6 +161,7 @@ const createNightlyContext = (): NightlyReviewContext => ({relevantMemories: [],reviewWindowEnd: '2026-05-09T02:00:00.000Z',reviewWindowStart: '2026-05-09T00:00:00.000Z',+ selfFeedbackCandidates: [],toolActivity: [],topics: [],userId: 'user-1',@@ -190,7 +175,7 @@ beforeEach(() => {mocks.initModelRuntimeFromDB.mockResolvedValue({ chat: vi.fn() });mocks.skillReadTargetSnapshot.mockResolvedValue(undefined);mocks.skillReplaceSkillIndex.mockResolvedValue(undefined);- mocks.runMaintenanceToolFirstRuntime.mockResolvedValue({+ mocks.executeSelfIteration.mockResolvedValue({content: 'Created a skill.',stepCount: 3,toolCalls: [@@ -203,7 +188,7 @@ beforeEach(() => {title: 'Concise answers',}),id: 'tool-call-1',- identifier: 'agent-signal-maintenance',+ identifier: 'agent-signal-self-iteration',type: 'builtin',},],@@ -260,13 +245,13 @@ const createSkillProposalToolArguments = () => ({summary: 'Review concise answers skill.',});-describe('listServerProposalActivity', () => {+describe('listServerSelfReviewProposalActivity', () => {/*** @example- * listServerProposalActivity skips malformed metadata and maps active proposal targets.+ * listServerSelfReviewProposalActivity skips malformed metadata and maps active proposal targets.*/it('filters invalid metadata and maps active proposal target digests', async () => {- const digest = await listServerProposalActivity({+ const digest = await listServerSelfReviewProposalActivity({agentId: 'agent-1',briefModel: {listUnresolvedByAgentAndTrigger: async () => [@@ -313,12 +298,12 @@ describe('listServerProposalActivity', () => {/*** @example- * listServerProposalActivity passes trigger and agent filters to the brief reader.+ * listServerSelfReviewProposalActivity passes trigger and agent filters to the brief reader.*/it('queries unresolved proposal briefs by trigger and agent before the read cap', async () => {const calls: Array<{ agentId: string; limit?: number; trigger: string }> = [];- await listServerProposalActivity({+ await listServerSelfReviewProposalActivity({agentId: 'agent-1',briefModel: {listUnresolvedByAgentAndTrigger: async (options) => {@@ -341,10 +326,10 @@ describe('listServerProposalActivity', () => {/*** @example- * listServerProposalActivity excludes expired pending proposals from active activity.+ * listServerSelfReviewProposalActivity excludes expired pending proposals from active activity.*/it('counts expired pending proposals as expired instead of active', async () => {- const digest = await listServerProposalActivity({+ const digest = await listServerSelfReviewProposalActivity({agentId: 'agent-1',briefModel: {listUnresolvedByAgentAndTrigger: async () => [@@ -364,10 +349,10 @@ describe('listServerProposalActivity', () => {/*** @example- * listServerProposalActivity ignores legacy noop proposal metadata.+ * listServerSelfReviewProposalActivity ignores legacy noop proposal metadata.*/it('skips noop proposal metadata from active activity', async () => {- const digest = await listServerProposalActivity({+ const digest = await listServerSelfReviewProposalActivity({agentId: 'agent-1',briefModel: {listUnresolvedByAgentAndTrigger: async () => [@@ -380,7 +365,7 @@ describe('listServerProposalActivity', () => {actionType: 'noop',evidenceRefs: [{ id: 'topic-1', type: 'topic' }],idempotencyKey: 'source:noop:quiet',- rationale: 'No maintenance needed.',+ rationale: 'No self-iteration needed.',risk: 'low',},],@@ -397,10 +382,10 @@ describe('listServerProposalActivity', () => {/*** @example- * listServerProposalActivity keeps unexpired pending proposals in active activity.+ * listServerSelfReviewProposalActivity keeps unexpired pending proposals in active activity.*/it('keeps future pending proposals active', async () => {- const digest = await listServerProposalActivity({+ const digest = await listServerSelfReviewProposalActivity({agentId: 'agent-1',briefModel: {listUnresolvedByAgentAndTrigger: async () => [@@ -420,10 +405,10 @@ describe('listServerProposalActivity', () => {/*** @example- * listServerProposalActivity prefers skillDocumentId when a proposal target has multiple ids.+ * listServerSelfReviewProposalActivity prefers skillDocumentId when a proposal target has multiple ids.*/it('uses proposal key target priority when mapping active proposal target ids', async () => {- const digest = await listServerProposalActivity({+ const digest = await listServerSelfReviewProposalActivity({agentId: 'agent-1',briefModel: {listUnresolvedByAgentAndTrigger: async () => [@@ -457,10 +442,10 @@ describe('listServerProposalActivity', () => {/*** @example- * listServerProposalActivity counts inactive unresolved proposal statuses without listing them as active.+ * listServerSelfReviewProposalActivity counts inactive unresolved proposal statuses without listing them as active.*/it('separates active proposals from inactive unresolved proposal status counts', async () => {- const digest = await listServerProposalActivity({+ const digest = await listServerSelfReviewProposalActivity({agentId: 'agent-1',briefModel: {listUnresolvedByAgentAndTrigger: async () => [@@ -482,23 +467,23 @@ describe('listServerProposalActivity', () => {});});-describe('createServerNightlyReviewPolicyOptions', () => {+describe('createServerSelfReviewPolicyOptions', () => {/*** @example- * createServerNightlyReviewPolicyOptions delegates nightly mutation authority to the+ * createServerSelfReviewPolicyOptions delegates nightly mutation authority to the* tool-first runtime instead of the legacy reviewer -> planner -> executor chain.*/- it('runs nightly maintenance through the tool-first runtime with DB model runtime and real tools', async () => {+ it('runs nightly shared through the tool-first runtime with DB model runtime and real tools', async () => {const modelRuntime = { chat: vi.fn() };mocks.initModelRuntimeFromDB.mockResolvedValue(modelRuntime);- const options = createServerNightlyReviewPolicyOptions({+ const options = createServerSelfReviewPolicyOptions({agentId: 'agent-1',db: {} as unknown as LobeChatDatabase,selfIterationEnabled: true,userId: 'user-1',});- const result = await options.runMaintenanceReviewAgent({+ const result = await options.runSelfReviewAgent({context: createNightlyContext(),localDate: '2026-05-09',sourceId: 'nightly-review:user-1:agent-1:2026-05-09',@@ -506,7 +491,7 @@ describe('createServerNightlyReviewPolicyOptions', () => {});expect(mocks.initModelRuntimeFromDB).toHaveBeenCalledTimes(1);- expect(mocks.runMaintenanceToolFirstRuntime).toHaveBeenCalledWith(+ expect(mocks.executeSelfIteration).toHaveBeenCalledWith(expect.objectContaining({agentId: 'agent-1',maxSteps: 10,@@ -515,15 +500,13 @@ describe('createServerNightlyReviewPolicyOptions', () => {userId: 'user-1',}),);- expect(mocks.createMaintenancePlannerService).not.toHaveBeenCalled();- expect(mocks.createMaintenanceExecutorService).not.toHaveBeenCalled();expect(result.stepCount).toBe(3);expect(result.execution).toMatchObject({actions: [{idempotencyKey: 'op-create-skill',resourceId: 'skill-1',- status: MaintenanceActionStatus.Applied,+ status: ActionStatus.Applied,},],sourceId: 'nightly-review:user-1:agent-1:2026-05-09',@@ -538,7 +521,7 @@ describe('createServerNightlyReviewPolicyOptions', () => {/*** @example- * createServerNightlyReviewPolicyOptions exposes createMaintenanceProposal with real brief+ * createServerSelfReviewPolicyOptions exposes createSelfReviewProposal with real brief* persistence instead of returning an unsupported tool result.*/it('persists proposal lifecycle tool writes through Daily Brief proposal metadata', async () => {@@ -552,8 +535,8 @@ describe('createServerNightlyReviewPolicyOptions', () => {zadd: vi.fn(async () => 1),};mocks.initModelRuntimeFromDB.mockResolvedValue(modelRuntime);- mocks.runMaintenanceToolFirstRuntime.mockImplementation(async (input) => {- const result = await input.tools.createMaintenanceProposal({+ mocks.executeSelfIteration.mockImplementation(async (input) => {+ const result = await input.tools.createSelfReviewProposal({actions: toolArguments.actions,idempotencyKey: toolArguments.idempotencyKey,metadata: {},@@ -567,25 +550,25 @@ describe('createServerNightlyReviewPolicyOptions', () => {stepCount: 2,toolCalls: [{- apiName: 'createMaintenanceProposal',+ apiName: 'createSelfReviewProposal',arguments: JSON.stringify(toolArguments),id: 'call-proposal-1',- identifier: 'agent-signal-maintenance',+ identifier: 'agent-signal-self-iteration',type: 'builtin',},],usage: [],- writeOutcomes: [{ result, toolName: 'createMaintenanceProposal' }],+ writeOutcomes: [{ result, toolName: 'createSelfReviewProposal' }],};});- const options = createServerNightlyReviewPolicyOptions({+ const options = createServerSelfReviewPolicyOptions({agentId: 'agent-1',db: {} as unknown as LobeChatDatabase,selfIterationEnabled: true,userId: 'user-1',});- const result = await options.runMaintenanceReviewAgent({+ const result = await options.runSelfReviewAgent({context: createNightlyContext(),localDate: '2026-05-09',sourceId: 'source-1',@@ -597,7 +580,7 @@ describe('createServerNightlyReviewPolicyOptions', () => {metadata: {agentSignal: {nightlySelfReview: {- maintenanceProposal: {+ selfReviewProposal: {actions: [{actionType: 'create_skill',@@ -621,7 +604,112 @@ describe('createServerNightlyReviewPolicyOptions', () => {/*** @example- * createMaintenanceProposal({ actions: [{ actionType: 'refine_skill' }] })+ * const digest = await tools.getEvidenceDigest({ evidenceIds: ['message-1', 'agent-doc-1'] });+ * expect(digest.topics[0].topicId).toBe('topic-1');+ */+ it('keeps topic and signal context when evidence digest is requested with message or agent document ids', async () => {+ const modelRuntime = { chat: vi.fn() };+ const context: NightlyReviewContext = {+ ...createNightlyContext(),+ documentActivity: {+ ...createNightlyContext().documentActivity,+ skillBucket: [+ {+ agentDocumentId: 'agent-doc-1',+ documentId: 'doc-1',+ hintIsSkill: false,+ reason: 'templateId=agent-skill',+ updatedAt: '2026-05-09T01:00:00.000Z',+ },+ ],+ },+ selfReviewSignals: [+ {+ evidenceRefs: [+ { id: 'message-1', type: 'message' },+ { id: 'agent-doc-1', type: 'agent_document' },+ ],+ features: [],+ kind: 'skill_document_with_tool_failure',+ strength: 'medium',+ },+ ],+ managedSkills: [{ documentId: 'agent-doc-1', name: 'release-note-checklist' }],+ topics: [+ {+ evidenceRefs: [{ id: 'topic-1', type: 'topic' }],+ failedToolCalls: [+ {+ apiName: 'replaceSkillContentCAS',+ messageId: 'message-1',+ toolCallId: 'tool-call-1',+ },+ ],+ failedToolCount: 1,+ highSignalReasons: ['failed_tool'],+ messageCount: 1,+ reviewScore: 4001,+ summary: 'The skill refinement failed.',+ topicId: 'topic-1',+ },+ ],+ };+ mocks.initModelRuntimeFromDB.mockResolvedValue(modelRuntime);+ mocks.executeSelfIteration.mockImplementation(async (input) => {+ const digest = await input.tools.getEvidenceDigest({+ agentId: 'agent-1',+ evidenceIds: ['message-1', 'agent-doc-1'],+ reviewWindowEnd: context.reviewWindowEnd,+ reviewWindowStart: context.reviewWindowStart,+ userId: 'user-1',+ });++ expect(digest).toMatchObject({+ selfReviewSignals: [+ {+ kind: 'skill_document_with_tool_failure',+ },+ ],+ managedSkills: [+ {+ documentId: 'agent-doc-1',+ name: 'release-note-checklist',+ },+ ],+ topics: [+ {+ topicId: 'topic-1',+ },+ ],+ });++ return {+ content: 'Inspected evidence.',+ stepCount: 1,+ toolCalls: [],+ usage: [],+ writeOutcomes: [],+ };+ });++ const options = createServerSelfReviewPolicyOptions({+ agentId: 'agent-1',+ db: {} as unknown as LobeChatDatabase,+ selfIterationEnabled: true,+ userId: 'user-1',+ });++ await options.runSelfReviewAgent({+ context,+ localDate: '2026-05-09',+ sourceId: 'source-1',+ userId: 'user-1',+ });+ });++ /**+ * @example+ * createSelfReviewProposal({ actions: [{ actionType: 'refine_skill' }] })* snapshots the target skill on the server before creating the approval brief.*/it('enriches refine skill proposals with server-side base snapshots', async () => {@@ -669,8 +757,8 @@ describe('createServerNightlyReviewPolicyOptions', () => {targetTitle: 'Existing skill',writable: true,});- mocks.runMaintenanceToolFirstRuntime.mockImplementation(async (input) => {- const result = await input.tools.createMaintenanceProposal({+ mocks.executeSelfIteration.mockImplementation(async (input) => {+ const result = await input.tools.createSelfReviewProposal({actions: toolArguments.actions,idempotencyKey: toolArguments.idempotencyKey,metadata: {},@@ -684,25 +772,25 @@ describe('createServerNightlyReviewPolicyOptions', () => {stepCount: 2,toolCalls: [{- apiName: 'createMaintenanceProposal',+ apiName: 'createSelfReviewProposal',arguments: JSON.stringify(toolArguments),id: 'call-proposal-refine-1',- identifier: 'agent-signal-maintenance',+ identifier: 'agent-signal-self-iteration',type: 'builtin',},],usage: [],- writeOutcomes: [{ result, toolName: 'createMaintenanceProposal' }],+ writeOutcomes: [{ result, toolName: 'createSelfReviewProposal' }],};});- const options = createServerNightlyReviewPolicyOptions({+ const options = createServerSelfReviewPolicyOptions({agentId: 'agent-1',db: {} as unknown as LobeChatDatabase,selfIterationEnabled: true,userId: 'user-1',});- const result = await options.runMaintenanceReviewAgent({+ const result = await options.runSelfReviewAgent({context: createNightlyContext(),localDate: '2026-05-09',sourceId: 'source-1',@@ -714,7 +802,7 @@ describe('createServerNightlyReviewPolicyOptions', () => {metadata: {agentSignal: {nightlySelfReview: {- maintenanceProposal: {+ selfReviewProposal: {actions: [{actionType: 'refine_skill',@@ -771,7 +859,7 @@ describe('createServerNightlyReviewPolicyOptions', () => {bundle: { agentDocumentId: 'skill-bundle-1' },name: 'existing-skill',});- mocks.runMaintenanceToolFirstRuntime.mockImplementation(async (input) => {+ mocks.executeSelfIteration.mockImplementation(async (input) => {const result = await input.tools.replaceSkillContentCAS({bodyMarkdown: 'Updated skill body.',idempotencyKey: 'source-1:replaceSkillContentCAS:skill-index-1',@@ -791,7 +879,7 @@ describe('createServerNightlyReviewPolicyOptions', () => {skillDocumentId: 'skill-index-1',}),id: 'call-refine-1',- identifier: 'agent-signal-maintenance',+ identifier: 'agent-signal-self-iteration',type: 'builtin',},],@@ -800,13 +888,13 @@ describe('createServerNightlyReviewPolicyOptions', () => {};});- const options = createServerNightlyReviewPolicyOptions({+ const options = createServerSelfReviewPolicyOptions({agentId: 'agent-1',db: {} as unknown as LobeChatDatabase,selfIterationEnabled: true,userId: 'user-1',});- const result = await options.runMaintenanceReviewAgent({+ const result = await options.runSelfReviewAgent({context: createNightlyContext(),localDate: '2026-05-09',sourceId: 'source-1',@@ -823,7 +911,7 @@ describe('createServerNightlyReviewPolicyOptions', () => {expect(result.execution.actions[0]).toMatchObject({idempotencyKey: 'source-1:replaceSkillContentCAS:skill-index-1',resourceId: 'skill-bundle-1',- status: MaintenanceActionStatus.Applied,+ status: ActionStatus.Applied,});});});diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/nightlySignals.test.ts b/src/server/services/agentSignal/services/selfIteration/review/__test__/signals.test.tssimilarity index 94%rename from src/server/services/agentSignal/services/maintenance/__tests__/nightlySignals.test.tsrename to src/server/services/agentSignal/services/selfIteration/review/__test__/signals.test.tsindex fd2cf25cec2..21a7adf5e69 100644--- a/src/server/services/agentSignal/services/maintenance/__tests__/nightlySignals.test.ts+++ b/src/server/services/agentSignal/services/selfIteration/review/__test__/signals.test.ts@@ -4,8 +4,8 @@ import type {DocumentActivityDigest,FeedbackActivityDigest,ReceiptActivityDigest,-} from '../nightlyCollector';-import { deriveNightlyMaintenanceSignals } from '../nightlySignals';+} from '../collect';+import { deriveSelfReviewSignals } from '../signals';const createEmptyDocumentActivityForTest = (): DocumentActivityDigest => ({ambiguousBucket: [],@@ -29,14 +29,14 @@ const createEmptyReceiptActivityForTest = (): ReceiptActivityDigest => ({reviewCount: 0,});-describe('deriveNightlyMaintenanceSignals', () => {+describe('deriveSelfReviewSignals', () => {/*** @example* Tool activity by itself is telemetry only and should stay weak.*/it('keeps frequent tool usage weak when there is no document feedback or receipt support', () => {expect(- deriveNightlyMaintenanceSignals({+ deriveSelfReviewSignals({documentActivity: createEmptyDocumentActivityForTest(),feedbackActivity: createEmptyFeedbackActivityForTest(),receiptActivity: createEmptyReceiptActivityForTest(),@@ -66,7 +66,7 @@ describe('deriveNightlyMaintenanceSignals', () => {* Tool-only activity never becomes skill overlap evidence.*/it('does not create skill overlap signals from tool usage alone', () => {- const signals = deriveNightlyMaintenanceSignals({+ const signals = deriveSelfReviewSignals({documentActivity: createEmptyDocumentActivityForTest(),feedbackActivity: createEmptyFeedbackActivityForTest(),receiptActivity: createEmptyReceiptActivityForTest(),@@ -89,11 +89,11 @@ describe('deriveNightlyMaintenanceSignals', () => {/*** @example- * Explicit hinted skill document activity should be a medium maintenance signal.+ * Explicit hinted skill document activity should be a medium self-review signal.*/it('creates hinted skill document signals from hintIsSkill document activity', () => {expect(- deriveNightlyMaintenanceSignals({+ deriveSelfReviewSignals({documentActivity: {ambiguousBucket: [],excludedSummary: { count: 0, reasons: [] },@@ -128,7 +128,7 @@ describe('deriveNightlyMaintenanceSignals', () => {*/it('creates repeated tool failure signals when failure count crosses the threshold', () => {expect(- deriveNightlyMaintenanceSignals({+ deriveSelfReviewSignals({documentActivity: createEmptyDocumentActivityForTest(),feedbackActivity: createEmptyFeedbackActivityForTest(),receiptActivity: createEmptyReceiptActivityForTest(),@@ -158,7 +158,7 @@ describe('deriveNightlyMaintenanceSignals', () => {* Ordinary message wording and correction metadata are not durable preference evidence.*/it('does not create durable user preference signals from correction-bearing topics', () => {- const signals = deriveNightlyMaintenanceSignals({+ const signals = deriveSelfReviewSignals({documentActivity: createEmptyDocumentActivityForTest(),feedbackActivity: createEmptyFeedbackActivityForTest(),receiptActivity: createEmptyReceiptActivityForTest(),@@ -185,7 +185,7 @@ describe('deriveNightlyMaintenanceSignals', () => {* Two skill bucket documents produce an overlap review signal.*/it('creates possible skill overlap signals from multiple skill document events', () => {- const signals = deriveNightlyMaintenanceSignals({+ const signals = deriveSelfReviewSignals({documentActivity: {ambiguousBucket: [],excludedSummary: { count: 0, reasons: [] },@@ -226,7 +226,7 @@ describe('deriveNightlyMaintenanceSignals', () => {*/it('creates pending proposal signals from receipt activity', () => {expect(- deriveNightlyMaintenanceSignals({+ deriveSelfReviewSignals({documentActivity: createEmptyDocumentActivityForTest(),feedbackActivity: createEmptyFeedbackActivityForTest(),receiptActivity: {@@ -277,7 +277,7 @@ describe('deriveNightlyMaintenanceSignals', () => {};expect(- deriveNightlyMaintenanceSignals({+ deriveSelfReviewSignals({documentActivity: createEmptyDocumentActivityForTest(),feedbackActivity,receiptActivity: createEmptyReceiptActivityForTest(),@@ -286,7 +286,7 @@ describe('deriveNightlyMaintenanceSignals', () => {).toEqual([]);expect(- deriveNightlyMaintenanceSignals({+ deriveSelfReviewSignals({documentActivity: createEmptyDocumentActivityForTest(),feedbackActivity,receiptActivity: createEmptyReceiptActivityForTest(),diff --git a/src/server/services/agentSignal/services/maintenance/brief.ts b/src/server/services/agentSignal/services/selfIteration/review/brief.tssimilarity index 73%rename from src/server/services/agentSignal/services/maintenance/brief.tsrename to src/server/services/agentSignal/services/selfIteration/review/brief.tsindex 4dd8e5b4bda..6a94c80895f 100644--- a/src/server/services/agentSignal/services/maintenance/brief.ts+++ b/src/server/services/agentSignal/services/selfIteration/review/brief.ts@@ -6,26 +6,26 @@ import { BriefModel } from '@/database/models/brief';import type { BriefItem, NewBrief } from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';+import type { EvidenceRef, RunResult } from '../types';+import { ActionStatus, ReviewRunStatus } from '../types';import type {- MaintenanceProposalMetadata,- MaintenanceProposalPlan,- MaintenanceReviewIdea,+ SelfReviewIdea,+ SelfReviewProposalMetadata,+ SelfReviewProposalPlan,} from './proposal';import {AGENT_SIGNAL_PROPOSAL_BRIEF_ACTIONS,- buildMaintenanceProposalFromPlan,- getMaintenanceProposalFromBriefMetadata,- refreshMaintenanceProposal,- shouldRefreshMaintenanceProposal,- shouldSupersedeMaintenanceProposal,- supersedeMaintenanceProposal,+ buildSelfReviewProposalFromPlan,+ getSelfReviewProposalFromBriefMetadata,+ refreshSelfReviewProposal,+ shouldRefreshSelfReviewProposal,+ shouldSupersedeSelfReviewProposal,+ supersedeSelfReviewProposal,} from './proposal';-import type { EvidenceRef, MaintenanceReviewRunResult } from './types';-import { MaintenanceActionStatus, ReviewRunStatus } from './types';export const NIGHTLY_REVIEW_BRIEF_TRIGGER = 'agent-signal:nightly-review';-interface MaintenanceBriefActionCounts {+interface SelfReviewBriefActionCounts {/** Number of actions applied to durable resources. */applied: number;/** Number of actions that failed after planning or execution. */@@ -36,22 +36,22 @@ interface MaintenanceBriefActionCounts {skipped: number;}-/** Metadata stored with Agent Signal maintenance Daily Briefs. */-export interface MaintenanceBriefMetadata {+/** Metadata stored with Agent Signal self-review Daily Briefs. */+export interface SelfReviewBriefMetadata {/** Per-action status counts used by UI filters and eval assertions. */- actionCounts: MaintenanceBriefActionCounts;+ actionCounts: SelfReviewBriefActionCounts;/** Evidence refs retained from reviewer/planner context for audit drilldown. */evidenceRefs: EvidenceRef[];/** Non-actionable self-review ideas retained without entering approve-time apply. */- ideas?: MaintenanceReviewIdea[];+ ideas?: SelfReviewIdea[];/** User-local review date in YYYY-MM-DD form. */localDate: string;- /** Frozen maintenance proposal state for approve/dismiss flows. */- maintenanceProposal?: MaintenanceProposalMetadata;/** Coarse user-visible outcome selected by the projection service. */outcome: 'applied' | 'error' | 'ideas' | 'proposal';/** Durable receipt ids linked to this brief. */receiptIds: string[];+ /** Frozen self-review proposal state for approve/dismiss flows. */+ selfReviewProposal?: SelfReviewProposalMetadata;/** Review source id that produced this brief. */sourceId?: string;/** IANA timezone used for the nightly review window. */@@ -67,24 +67,24 @@ export interface AgentSignalNightlySelfReviewBriefMetadata extends BriefMetadata/** Agent Signal-owned metadata namespace. */agentSignal: {/** Nightly self-review status, receipts, and optional frozen proposal. */- nightlySelfReview: MaintenanceBriefMetadata;+ nightlySelfReview: SelfReviewBriefMetadata;/** Future Agent Signal domains can live beside nightly self-review. */[key: string]: unknown;};}-/** Create payload for a maintenance Daily Brief. */-export type MaintenanceBriefProjection = Omit<NewBrief, 'id' | 'userId'> & {+/** Create payload for a self-review Daily Brief. */+export type SelfReviewBriefProjection = Omit<NewBrief, 'id' | 'userId'> & {metadata: AgentSignalNightlySelfReviewBriefMetadata;trigger: typeof NIGHTLY_REVIEW_BRIEF_TRIGGER;};-const isProposalExpired = (proposal: Pick<MaintenanceProposalMetadata, 'expiresAt'>, now: string) =>+const isProposalExpired = (proposal: Pick<SelfReviewProposalMetadata, 'expiresAt'>, now: string) =>new Date(proposal.expiresAt).getTime() <= new Date(now).getTime();const updateBriefProposalMetadata = (brief: BriefItem,- proposal: MaintenanceProposalMetadata,+ proposal: SelfReviewProposalMetadata,): BriefItem['metadata'] => ({...asMetadataRecord(brief.metadata),agentSignal: {@@ -93,7 +93,7 @@ const updateBriefProposalMetadata = (...asMetadataRecord(asMetadataRecord(asMetadataRecord(brief.metadata).agentSignal).nightlySelfReview,),- maintenanceProposal: proposal,+ selfReviewProposal: proposal,},},});@@ -106,14 +106,14 @@ const asMetadataRecord = (metadata: unknown): Record<string, unknown> =>/** Reads Agent Signal nightly self-review metadata from a namespaced Brief payload. */export const getNightlySelfReviewBriefMetadata = (metadata: unknown,-): MaintenanceBriefMetadata | undefined => {+): SelfReviewBriefMetadata | undefined => {const agentSignal = asMetadataRecord(asMetadataRecord(metadata).agentSignal);const nightlySelfReview = agentSignal.nightlySelfReview;return nightlySelfReview &&typeof nightlySelfReview === 'object' &&!Array.isArray(nightlySelfReview)- ? (nightlySelfReview as MaintenanceBriefMetadata)+ ? (nightlySelfReview as SelfReviewBriefMetadata): undefined;};@@ -124,11 +124,11 @@ const createNightlySelfReviewBriefMetadata = ({outcome,proposal,}: {- actionCounts: MaintenanceBriefActionCounts;+ actionCounts: SelfReviewBriefActionCounts;evidenceRefs: EvidenceRef[];input: ProjectNightlyReviewBriefInput;- outcome: MaintenanceBriefMetadata['outcome'];- proposal?: MaintenanceProposalMetadata;+ outcome: SelfReviewBriefMetadata['outcome'];+ proposal?: SelfReviewProposalMetadata;}): AgentSignalNightlySelfReviewBriefMetadata => ({agentSignal: {nightlySelfReview: {@@ -137,7 +137,7 @@ const createNightlySelfReviewBriefMetadata = ({...(input.ideas?.length ? { ideas: input.ideas } : {}),localDate: input.localDate,outcome,- ...(proposal ? { maintenanceProposal: proposal } : {}),+ ...(proposal ? { selfReviewProposal: proposal } : {}),receiptIds: getReceiptIds(input.result),...(input.result.sourceId ? { sourceId: input.result.sourceId } : {}),timezone: input.timezone,@@ -147,7 +147,7 @@ const createNightlySelfReviewBriefMetadata = ({},});-const ACTIVE_PROPOSAL_REFRESH_STATUSES = new Set<MaintenanceProposalMetadata['status']>([+const ACTIVE_PROPOSAL_REFRESH_STATUSES = new Set<SelfReviewProposalMetadata['status']>(['expired','pending','stale',@@ -160,7 +160,7 @@ const findExistingProposalBrief = async ({trigger,}: {agentId: string;- incomingProposal: MaintenanceProposalMetadata;+ incomingProposal: SelfReviewProposalMetadata;model: BriefModel;trigger: typeof NIGHTLY_REVIEW_BRIEF_TRIGGER;}) => {@@ -171,7 +171,7 @@ const findExistingProposalBrief = async ({});return rows.find((row) => {- const proposal = getMaintenanceProposalFromBriefMetadata(row.metadata);+ const proposal = getSelfReviewProposalFromBriefMetadata(row.metadata);return (proposal?.proposalKey === incomingProposal.proposalKey &&@@ -183,7 +183,7 @@ const findExistingProposalBrief = async ({const updateProposalMetadata = async (model: BriefModel,brief: BriefItem,- proposal: MaintenanceProposalMetadata,+ proposal: SelfReviewProposalMetadata,) => model.updateMetadata(brief.id, updateBriefProposalMetadata(brief, proposal));const refreshProposalBrief = ({@@ -192,13 +192,13 @@ const refreshProposalBrief = ({proposal,targetBrief,}: {- fallbackBrief: MaintenanceBriefProjection;+ fallbackBrief: SelfReviewBriefProjection;model: BriefModel;- proposal: MaintenanceProposalMetadata;+ proposal: SelfReviewProposalMetadata;targetBrief: BriefItem;}) =>tracer.startActiveSpan(- 'agent_signal.maintenance_proposal.refresh',+ 'agent_signal.self_review_proposal.refresh',{attributes: {'agent.signal.proposal.key': proposal.proposalKey,@@ -222,11 +222,11 @@ const supersedeProposalBrief = ({targetBrief,}: {model: BriefModel;- proposal: MaintenanceProposalMetadata;+ proposal: SelfReviewProposalMetadata;targetBrief: BriefItem;}) =>tracer.startActiveSpan(- 'agent_signal.maintenance_proposal.supersede',+ 'agent_signal.self_review_proposal.supersede',{attributes: {'agent.signal.proposal.key': proposal.proposalKey,@@ -242,20 +242,20 @@ const supersedeProposalBrief = ({},);-/** Input used to project one nightly maintenance result to a Daily Brief payload. */+/** Input used to project one nightly shared result to a Daily Brief payload. */export interface ProjectNightlyReviewBriefInput {- /** Agent reviewed by the nightly maintenance run. */+ /** Agent reviewed by the nightly shared run. */agentId: string;/** Evidence refs retained from the review or source handler. */evidenceRefs?: EvidenceRef[];/** Non-actionable self-review ideas collected during the run. */- ideas?: MaintenanceReviewIdea[];+ ideas?: SelfReviewIdea[];/** User-local date reviewed by the nightly run. */localDate: string;- /** Frozen maintenance plan used to preserve proposal actions. */- plan?: MaintenanceProposalPlan;- /** Executor result for the nightly maintenance run. */- result: MaintenanceReviewRunResult;+ /** Frozen self-iteration plan used to preserve proposal actions. */+ plan?: SelfReviewProposalPlan;+ /** Executor result for the nightly shared run. */+ result: RunResult;/** Review window end ISO timestamp. */reviewWindowEnd: string;/** Review window start ISO timestamp. */@@ -266,27 +266,27 @@ export interface ProjectNightlyReviewBriefInput {userId: string;}-/** Gate checks required before applying a pending maintenance proposal. */-export interface CanApplyMaintenanceProposalInput {+/** Gate checks required before applying a pending self-review proposal. */+export interface CanApplySelfReviewProposalInput {/** 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. */+ /** Checks whether the current user still enables shared. */checkUserGate: () => boolean | Promise<boolean>;}/** Result of proposal apply gate re-checks. */-export interface MaintenanceProposalApplyGateResult {+export interface SelfReviewProposalApplyGateResult {/** 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. */+/** Input used to decide whether an existing self-review proposal stays visible. */+export interface SelfReviewProposalVisibilityInput {+ /** Current shared setting. Does not hide already-created proposals. */selfIterationEnabled: boolean;/** Proposal resolution state. */status: 'dismissed' | 'pending' | 'resolved';@@ -294,17 +294,17 @@ export interface MaintenanceProposalVisibilityInput {trigger?: string | null;}-const getPlanActionByIdempotencyKey = (plan?: MaintenanceProposalPlan) =>+const getPlanActionByIdempotencyKey = (plan?: SelfReviewProposalPlan) =>new Map(plan?.actions.map((action) => [action.idempotencyKey, action]));const isVisibleProposalResult = (- action: MaintenanceReviewRunResult['actions'][number],+ action: RunResult['actions'][number],planActionByIdempotencyKey: Map<string,- MaintenanceProposalPlan['actions'][number]+ SelfReviewProposalPlan['actions'][number]> = getPlanActionByIdempotencyKey(),) => {- if (action.status !== MaintenanceActionStatus.Proposed || !action.receiptId) return false;+ if (action.status !== ActionStatus.Proposed || !action.receiptId) return false;const plannedAction = planActionByIdempotencyKey.get(action.idempotencyKey);@@ -312,10 +312,10 @@ const isVisibleProposalResult = (};const countActions = (- result: MaintenanceReviewRunResult,- plan?: MaintenanceProposalPlan,-): MaintenanceBriefActionCounts => {- const counts: MaintenanceBriefActionCounts = {+ result: RunResult,+ plan?: SelfReviewProposalPlan,+): SelfReviewBriefActionCounts => {+ const counts: SelfReviewBriefActionCounts = {applied: 0,failed: 0,proposed: 0,@@ -324,13 +324,10 @@ const countActions = (const planActionByIdempotencyKey = getPlanActionByIdempotencyKey(plan);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 === ActionStatus.Applied) counts.applied += 1;+ if (action.status === ActionStatus.Failed) counts.failed += 1;if (isVisibleProposalResult(action, planActionByIdempotencyKey)) counts.proposed += 1;- if (- action.status === MaintenanceActionStatus.Skipped ||- action.status === MaintenanceActionStatus.Deduped- ) {+ if (action.status === ActionStatus.Skipped || action.status === ActionStatus.Deduped) {counts.skipped += 1;}}@@ -338,16 +335,16 @@ const countActions = (return counts;};-const getReceiptIds = (result: MaintenanceReviewRunResult) => [+const getReceiptIds = (result: RunResult) => [...(result.summaryReceiptId ? [result.summaryReceiptId] : []),...result.actions.flatMap((action) => (action.receiptId ? [action.receiptId] : [])),];const getOutcome = (- result: MaintenanceReviewRunResult,- counts: MaintenanceBriefActionCounts,- ideas: MaintenanceReviewIdea[] = [],-): MaintenanceBriefMetadata['outcome'] | undefined => {+ result: RunResult,+ counts: SelfReviewBriefActionCounts,+ ideas: SelfReviewIdea[] = [],+): SelfReviewBriefMetadata['outcome'] | undefined => {if (counts.proposed > 0) return 'proposal';if (counts.applied > 0) return 'applied';if (counts.failed > 0 || result.status === ReviewRunStatus.Failed) return 'error';@@ -357,15 +354,15 @@ const getOutcome = (};const formatActionSummaries = (- result: MaintenanceReviewRunResult,- status: MaintenanceActionStatus,+ result: RunResult,+ status: ActionStatus,heading: string,- plan?: MaintenanceProposalPlan,+ plan?: SelfReviewProposalPlan,) => {const planActionByIdempotencyKey = getPlanActionByIdempotencyKey(plan);const summaries = result.actions.filter((action) => {- if (status !== MaintenanceActionStatus.Proposed) return action.status === status;+ if (status !== ActionStatus.Proposed) return action.status === status;return isVisibleProposalResult(action, planActionByIdempotencyKey);})@@ -379,10 +376,10 @@ const formatActionSummaries = (const createDetailedSummary = (summary: string,- result: MaintenanceReviewRunResult,- status: MaintenanceActionStatus,+ result: RunResult,+ status: ActionStatus,heading: string,- plan?: MaintenanceProposalPlan,+ plan?: SelfReviewProposalPlan,) => {const details = formatActionSummaries(result, status, heading, plan);@@ -393,8 +390,8 @@ const collectBriefArtifactDocuments = ({ideas = [],proposal,}: {- ideas?: MaintenanceReviewIdea[];- proposal?: MaintenanceProposalMetadata;+ ideas?: SelfReviewIdea[];+ proposal?: SelfReviewProposalMetadata;}): BriefArtifactDocument[] => {const documents = new Map<string, BriefArtifactDocument>();@@ -424,8 +421,8 @@ const collectBriefArtifactDocuments = ({};const createBriefArtifacts = (input: {- ideas?: MaintenanceReviewIdea[];- proposal?: MaintenanceProposalMetadata;+ ideas?: SelfReviewIdea[];+ proposal?: SelfReviewProposalMetadata;}) => {const documents = collectBriefArtifactDocuments(input);@@ -433,34 +430,28 @@ const createBriefArtifacts = (input: {};const createBriefCopy = (- outcome: MaintenanceBriefMetadata['outcome'],- counts: MaintenanceBriefActionCounts,- result: MaintenanceReviewRunResult,- plan?: MaintenanceProposalPlan,+ outcome: SelfReviewBriefMetadata['outcome'],+ counts: SelfReviewBriefActionCounts,+ result: RunResult,+ plan?: SelfReviewProposalPlan,) => {if (outcome === 'proposal') {- const summary = `${counts.proposed} maintenance proposal${counts.proposed === 1 ? '' : 's'} need review.`;+ const summary = `${counts.proposed} self-review proposal${counts.proposed === 1 ? '' : 's'} need review.`;return {priority: 'normal' as const,- summary: createDetailedSummary(- summary,- result,- MaintenanceActionStatus.Proposed,- 'Proposal',- plan,- ),+ summary: createDetailedSummary(summary, result, ActionStatus.Proposed, 'Proposal', plan),title: 'Agent self-review proposal',type: 'decision' as const,};}if (outcome === 'error') {- const summary = 'Agent self-review could not finish all maintenance actions.';+ const summary = 'Agent self-review could not finish all self-review actions.';return {priority: 'normal' as const,- summary: createDetailedSummary(summary, result, MaintenanceActionStatus.Failed, 'Failure'),+ summary: createDetailedSummary(summary, result, ActionStatus.Failed, 'Failure'),title: 'Agent self-review needs attention',type: 'error' as const,};@@ -469,42 +460,42 @@ const createBriefCopy = (if (outcome === 'ideas') {return {priority: 'info' as const,- summary: 'Agent self-review saved maintenance ideas for future review.',+ summary: 'Agent self-review saved shared ideas for future review.',title: 'Agent self-review ideas',type: 'insight' as const,};}- const summary = `${counts.applied} maintenance update${counts.applied === 1 ? '' : 's'} applied.`;+ const summary = `${counts.applied} self-iteration update${counts.applied === 1 ? '' : 's'} applied.`;return {priority: 'info' as const,- summary: createDetailedSummary(summary, result, MaintenanceActionStatus.Applied, 'Updated'),+ summary: createDetailedSummary(summary, result, ActionStatus.Applied, 'Updated'),title: 'Agent self-review updated resources',type: 'insight' as const,};};/**- * Creates projection helpers for Agent Signal maintenance Daily Briefs.+ * Creates projection helpers for Agent Signal self-review 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+ * - SelfIteration 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 = () => ({+export const createBriefSelfReviewService = () => ({/**- * Checks whether a pending maintenance proposal can be applied right now.+ * Checks whether a pending self-review proposal can be applied right now.** Use when:- * - A user approves a previously-created maintenance proposal+ * - A user approves a previously-created self-review proposal* - Current feature/user/agent gates must be honored at apply time** Expects:@@ -513,9 +504,9 @@ export const createBriefMaintenanceService = () => ({* Returns:* - `allowed: true` only when every gate passes*/- canApplyMaintenanceProposal: async (- input: CanApplyMaintenanceProposalInput,- ): Promise<MaintenanceProposalApplyGateResult> => {+ canApplySelfReviewProposal: async (+ input: CanApplySelfReviewProposalInput,+ ): Promise<SelfReviewProposalApplyGateResult> => {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' };@@ -531,19 +522,19 @@ export const createBriefMaintenanceService = () => ({* - Self-iteration has been disabled after proposal creation** Expects:- * - The caller separately blocks proposal application with `canApplyMaintenanceProposal`+ * - The caller separately blocks proposal application with `canApplySelfReviewProposal`** Returns:* - `true` for pending Agent Signal nightly proposals*/- isMaintenanceProposalVisible: (input: MaintenanceProposalVisibilityInput) =>+ isSelfReviewProposalVisible: (input: SelfReviewProposalVisibilityInput) =>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+ * - Nightly review handlers have already executed self-review actions* - Noop reviews should remain silent while applied/proposal/error outcomes surface** Expects:@@ -555,7 +546,7 @@ export const createBriefMaintenanceService = () => ({*/projectNightlyReviewBrief: (input: ProjectNightlyReviewBriefInput,- ): MaintenanceBriefProjection | undefined => {+ ): SelfReviewBriefProjection | undefined => {const actionCounts = countActions(input.result, input.plan);const outcome = getOutcome(input.result, actionCounts, input.ideas);@@ -564,7 +555,7 @@ export const createBriefMaintenanceService = () => ({const copy = createBriefCopy(outcome, actionCounts, input.result, input.plan);const proposal =outcome === 'proposal' && input.plan- ? buildMaintenanceProposalFromPlan({+ ? buildSelfReviewProposalFromPlan({agentId: input.agentId,evidenceWindowEnd: input.reviewWindowEnd,evidenceWindowStart: input.reviewWindowStart,@@ -608,15 +599,15 @@ export const createBriefMaintenanceService = () => ({* Returns:* - A writer whose `writeDailyBrief` method creates or refreshes proposal briefs*/-export const createServerMaintenanceBriefWriter = (db: LobeChatDatabase, userId: string) => {+export const createServerSelfReviewBriefWriter = (db: LobeChatDatabase, userId: string) => {const model = new BriefModel(db, userId);return {- writeDailyBrief: (brief: MaintenanceBriefProjection) => {- const incomingProposal = brief.metadata.agentSignal.nightlySelfReview.maintenanceProposal;+ writeDailyBrief: (brief: SelfReviewBriefProjection) => {+ const incomingProposal = brief.metadata.agentSignal.nightlySelfReview.selfReviewProposal;return tracer.startActiveSpan(- 'agent_signal.maintenance_brief.write',+ 'agent_signal.self_iteration_brief.write',{attributes: {'agent.signal.agent_id': brief.agentId ?? '',@@ -644,13 +635,11 @@ export const createServerMaintenanceBriefWriter = (db: LobeChatDatabase, userId:if (!existingBrief) return model.create(brief);- const existingProposal = getMaintenanceProposalFromBriefMetadata(- existingBrief.metadata,- );+ const existingProposal = getSelfReviewProposalFromBriefMetadata(existingBrief.metadata);if (!existingProposal) return model.create(brief);if (existingProposal.status === 'pending' && isProposalExpired(existingProposal, now)) {- const expiredProposal: MaintenanceProposalMetadata = {+ const expiredProposal: SelfReviewProposalMetadata = {...existingProposal,status: 'expired',updatedAt: now,@@ -661,20 +650,20 @@ export const createServerMaintenanceBriefWriter = (db: LobeChatDatabase, userId:return model.create(brief);}- const refresh = shouldRefreshMaintenanceProposal({+ const refresh = shouldRefreshSelfReviewProposal({existing: existingProposal,incoming: incomingProposal,now,});if (refresh.refresh &&- shouldSupersedeMaintenanceProposal({+ shouldSupersedeSelfReviewProposal({existing: existingProposal,incoming: incomingProposal,now,}).supersede === false) {- const refreshedProposal = refreshMaintenanceProposal({+ const refreshedProposal = refreshSelfReviewProposal({existing: existingProposal,incoming: incomingProposal,now,@@ -689,13 +678,13 @@ export const createServerMaintenanceBriefWriter = (db: LobeChatDatabase, userId:});}- const supersede = shouldSupersedeMaintenanceProposal({+ const supersede = shouldSupersedeSelfReviewProposal({existing: existingProposal,incoming: incomingProposal,now,});if (supersede.supersede) {- const supersededProposal = supersedeMaintenanceProposal({+ const supersededProposal = supersedeSelfReviewProposal({existing: existingProposal,now,supersededBy: incomingProposal.proposalKey,diff --git a/src/server/services/agentSignal/services/maintenance/nightlyCollector.ts b/src/server/services/agentSignal/services/selfIteration/review/collect.tssimilarity index 63%rename from src/server/services/agentSignal/services/maintenance/nightlyCollector.tsrename to src/server/services/agentSignal/services/selfIteration/review/collect.tsindex 2c649baa11e..a0346a76d1e 100644--- a/src/server/services/agentSignal/services/maintenance/nightlyCollector.ts+++ b/src/server/services/agentSignal/services/selfIteration/review/collect.ts@@ -1,9 +1,17 @@import { SpanStatusCode } from '@lobechat/observability-otel/api';import { tracer } from '@lobechat/observability-otel/modules/agent-signal';-import { deriveNightlyMaintenanceSignals } from './nightlySignals';-import type { MaintenanceProposalStatus } from './proposal';-import type { EvidenceRef, MaintenanceActionType } from './types';+import type { AgentSignalDocumentActivityRow } from '@/database/models/agentSignal/reviewContext';++import type { ActionType, EvidenceRef, SelfFeedbackIntent } from '../types';+import type { RankedSelfFeedbackCandidate } from './intentPolicy';+import {+ groupSelfFeedbackIntents,+ normalizeReflectionIntent,+ rankSelfFeedbackCandidates,+} from './intentPolicy';+import type { SelfReviewProposalStatus } from './proposal';+import { deriveSelfReviewSignals } from './signals';const DEFAULT_MAX_TOPICS = 30;const DEFAULT_MAX_MANAGED_SKILLS = 20;@@ -166,7 +174,7 @@ export interface NightlyReviewManagedSkillSummary {documentId?: string;/** Stable skill name. */name: string;- /** Whether this skill is writable by maintenance flows. */+ /** Whether this skill is writable by shared flows. */readonly?: boolean;/** Last skill update as an ISO string. */updatedAt?: string;@@ -224,7 +232,7 @@ export interface DocumentEventDigest {updatedAt: string;}-/** Document event with explicit skill-maintenance evidence. */+/** Document event with explicit skill-shared evidence. */export interface SkillDocumentEventDigest extends DocumentEventDigest {/** Whether metadata explicitly says this document was hinted as a skill. */hintIsSkill: boolean;@@ -232,13 +240,13 @@ export interface SkillDocumentEventDigest extends DocumentEventDigest {skillFileType?: string | null;}-/** Review-window document activity grouped by maintenance relevance. */+/** Review-window document activity grouped by shared relevance. */export interface DocumentActivityDigest {/** Weak or unclear document events. */ambiguousBucket: DocumentEventDigest[];/** Count and reasons for events omitted from reviewer context. */excludedSummary: { count: number; reasons: string[] };- /** Ordinary document activity that cannot independently trigger skill maintenance. */+ /** Ordinary document activity that cannot independently trigger skill self-review. */generalDocumentBucket: DocumentEventDigest[];/** Skill-like document events, primarily `hintIsSkill:true`. */skillBucket: SkillDocumentEventDigest[];@@ -262,7 +270,7 @@ export interface FeedbackSatisfactionDigest {topicId?: string;}-/** Existing satisfaction judgements grouped for maintenance review. */+/** Existing satisfaction judgements grouped for self-review. */export interface FeedbackActivityDigest {/** Number of neutral judgements suppressed from detailed context. */neutralCount: number;@@ -277,7 +285,9 @@ export interface ReceiptActivityItemDigest {/** Receipt id. */id: string;/** Receipt kind. */- kind: 'maintenance' | 'memory' | 'review' | 'skill';+ kind: 'review' | 'memory' | 'review' | 'skill';+ /** Optional structured receipt metadata used to surface reflection intents in review. */+ metadata?: Record<string, unknown>;/** Receipt status. */status: 'applied' | 'completed' | 'failed' | 'proposed' | 'skipped' | 'updated';/** Short receipt summary. */@@ -296,7 +306,7 @@ export interface ReceiptDuplicateGroupDigest {receiptIds: string[];}-/** Recent receipt history used to suppress repeated maintenance proposals. */+/** Recent receipt history used to suppress repeated self-review proposals. */export interface ReceiptActivityDigest {/** Count of applied or updated receipts. */appliedCount: number;@@ -313,9 +323,9 @@ export interface ReceiptActivityDigest {}/** Bounded unresolved proposal visible to nightly review. */-export interface MaintenanceProposalDigest {+export interface SelfReviewProposalDigest {/** Dominant action type represented by this proposal. */- actionType: MaintenanceActionType;+ actionType: ActionType;/** Last known conflict reason when the proposal became stale or blocked. */conflictReason?: string;/** Proposal creation ISO timestamp. */@@ -329,7 +339,7 @@ export interface MaintenanceProposalDigest {/** Stable one-pending-proposal key for this action target. */proposalKey: string;/** Current lifecycle status. */- status: MaintenanceProposalStatus;+ status: SelfReviewProposalStatus;/** Short proposal summary safe to inject into reviewer context. */summary: string;/** Target id when available. */@@ -343,7 +353,7 @@ export interface MaintenanceProposalDigest {/** Existing unresolved proposal row activity summarized for nightly review. */export interface ProposalActivityDigest {/** Active proposals that may be refreshed, superseded, or kept pending. */- active: MaintenanceProposalDigest[];+ active: SelfReviewProposalDigest[];/** Count of unresolved proposal rows whose metadata is already dismissed. */dismissedCount: number;/** Count of unresolved proposal rows whose metadata is expired or whose pending expiry passed. */@@ -354,20 +364,20 @@ export interface ProposalActivityDigest {supersededCount: number;}-/** Nightly maintenance signal shown to the reviewer before raw buckets. */-export interface MaintenanceSignal {+/** Nightly self-review signal shown to the reviewer before raw buckets. */+export interface SelfReviewSignal {/** Evidence refs that justify the signal. */evidenceRefs: EvidenceRef[];/** Extensible signal features. */- features: MaintenanceSignalFeature[];+ features: SelfReviewSignalFeature[];/** Signal category. */- kind: MaintenanceSignalKind;+ kind: SelfReviewSignalKind;/** Conservative signal strength. */strength: 'weak' | 'medium' | 'strong';}-/** Initial nightly maintenance signal categories. */-export type MaintenanceSignalKind =+/** Initial nightly self-review signal categories. */+export type SelfReviewSignalKind =| 'durable_user_preference'| 'frequent_tool_workflow'| 'hinted_skill_document_changed'@@ -376,8 +386,8 @@ export type MaintenanceSignalKind =| 'skill_document_with_tool_failure'| 'skill_documents_maybe_overlap';-/** Extensible feature bag attached to maintenance signals. */-export type MaintenanceSignalFeature =+/** Extensible feature bag attached to self-review signals. */+export type SelfReviewSignalFeature =| {confidence: number;reason: string;@@ -434,7 +444,7 @@ export interface NightlyReviewReadAdapters {listFeedbackActivity?: (input: NightlyReviewReadInput) => Promise<FeedbackActivityDigest>;/** Lists managed skill summaries for this agent and review window. */listManagedSkills: (input: ListManagedSkillsInput) => Promise<NightlyReviewManagedSkillSummary[]>;- /** Lists existing maintenance proposal activity for this agent. */+ /** Lists existing self-review proposal activity for this agent. */listProposalActivity?: (input: NightlyReviewReadInput) => Promise<ProposalActivityDigest>;/** Lists recent receipt activity relevant to this review window. */listReceiptActivity?: (input: NightlyReviewReadInput) => Promise<ReceiptActivityDigest>;@@ -488,15 +498,13 @@ export interface CollectNightlyReviewContextInput {export interface NightlyReviewContext {/** Stable agent id being reviewed. */agentId: string;- /** Review-window document activity grouped by maintenance relevance. */+ /** Review-window document activity grouped by shared relevance. */documentActivity: DocumentActivityDigest;/** Existing satisfaction judgements grouped for reviewer context. */feedbackActivity: FeedbackActivityDigest;- /** Conservative maintenance signals used as reviewer entry points. */- maintenanceSignals: MaintenanceSignal[];/** Managed skills relevant to the agent. */managedSkills: NightlyReviewManagedSkillSummary[];- /** Existing maintenance proposals used to refresh or supersede pending decisions. */+ /** Existing self-review proposals used to refresh or supersede pending decisions. */proposalActivity: ProposalActivityDigest;/** Recent receipt history used to avoid duplicate proposals. */receiptActivity: ReceiptActivityDigest;@@ -506,6 +514,10 @@ export interface NightlyReviewContext {reviewWindowEnd: string;/** Review window start as an ISO string. */reviewWindowStart: string;+ /** Reflection-mode self-feedback candidates available to nightly self-review. */+ selfFeedbackCandidates: RankedSelfFeedbackCandidate[];+ /** Conservative self-review signals used as reviewer entry points. */+ selfReviewSignals: SelfReviewSignal[];/** Ranked topic digests with evidence refs and no raw messages. */toolActivity: ToolActivityDigest[];/** Ranked topic digests with evidence refs and no raw messages. */@@ -514,14 +526,14 @@ export interface NightlyReviewContext {userId: string;}-/** Nightly review collector service API. */-export interface NightlyReviewService {+/** Self-review context collector service API. */+export interface SelfReviewContextService {/*** 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+ * - The caller must avoid mutating memory, skills, shared state, or queues** Expects:* - Dependencies return digest summaries instead of raw unbounded transcripts@@ -530,9 +542,7 @@ export interface NightlyReviewService {* Returns:* - A deterministic, bounded context containing topics, managed skills, and relevant memories*/- collectNightlyReviewContext: (- input: CollectNightlyReviewContextInput,- ) => Promise<NightlyReviewContext>;+ collect: (input: CollectNightlyReviewContextInput) => Promise<NightlyReviewContext>;}const hasSignal = (count: number | undefined, flag: boolean | undefined) =>@@ -691,6 +701,73 @@ const createEmptyDocumentActivity = (): DocumentActivityDigest => ({skillBucket: [],});+/**+ * Maps database document activity rows into self-review buckets.+ *+ * Use when:+ * - Server runtime adapters need to keep DB row shape separate from reviewer context shape+ * - Tests need deterministic document bucket behavior without opening database connections+ *+ * Expects:+ * - Rows are already scoped to one user, one agent, and one review window+ *+ * Returns:+ * - Document activity buckets where only skill bucket rows can support skill self-review+ */+export const mapNightlyDocumentActivityRows = (+ rows: AgentSignalDocumentActivityRow[],+): DocumentActivityDigest => {+ const digest = createEmptyDocumentActivity();++ for (const row of rows) {+ const base = {+ agentDocumentId: row.agentDocumentId,+ documentId: row.documentId,+ title: row.title,+ updatedAt: row.updatedAt.toISOString(),+ };++ if (row.hintIsSkill === true) {+ digest.skillBucket.push({+ ...base,+ hintIsSkill: true,+ reason: 'metadata.agentSignal.hintIsSkill=true',+ skillFileType: row.policyLoadFormat,+ });+ continue;+ }++ if (+ row.templateId === 'agent-skill' ||+ row.templateId === 'skills/index' ||+ row.templateId === 'skills/bundle'+ ) {+ digest.skillBucket.push({+ ...base,+ hintIsSkill: false,+ reason: `templateId=${row.templateId}`,+ skillFileType: row.templateId,+ });+ continue;+ }++ if (row.hintIsSkill === false) {+ digest.generalDocumentBucket.push({+ ...base,+ reason: 'metadata.agentSignal.hintIsSkill=false',+ });+ continue;+ }++ digest.ambiguousBucket.push({+ ...base,+ reason: 'missing agentSignal hint metadata',+ });+ }++ return digest;+};+const createEmptyFeedbackActivity = (): FeedbackActivityDigest => ({neutralCount: 0,notSatisfied: [],@@ -714,6 +791,125 @@ const createEmptyProposalActivity = (): ProposalActivityDigest => ({supersededCount: 0,});+const toRecord = (value: unknown): Record<string, unknown> | undefined =>+ value && typeof value === 'object' && !Array.isArray(value)+ ? (value as Record<string, unknown>)+ : undefined;++const toString = (value: unknown) => (typeof value === 'string' ? value : undefined);++const toStringArray = (value: unknown) =>+ Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : [];++const toEvidenceRefs = (value: unknown, fallbackReceiptId: string): EvidenceRef[] => {+ if (!Array.isArray(value)) return [{ id: fallbackReceiptId, type: 'receipt' }];++ const refs = value.flatMap((item): EvidenceRef[] => {+ const record = toRecord(item);+ const id = toString(record?.id);+ const type = toString(record?.type);++ if (!id) return [];++ if (+ type === 'topic' ||+ type === 'message' ||+ type === 'operation' ||+ type === 'source' ||+ type === 'receipt' ||+ type === 'tool_call' ||+ type === 'task' ||+ type === 'agent_document' ||+ type === 'memory'+ ) {+ return [{ id, type }];+ }++ return [];+ });++ return refs.length > 0 ? refs : [{ id: fallbackReceiptId, type: 'receipt' }];+};++const toIntentTarget = (value: unknown): SelfFeedbackIntent['target'] | undefined => {+ const record = toRecord(value);+ if (!record) return;++ return {+ memoryId: toString(record.memoryId),+ readonly: typeof record.readonly === 'boolean' ? record.readonly : undefined,+ skillDocumentId: toString(record.skillDocumentId),+ skillName: toString(record.skillName),+ taskIds: toStringArray(record.taskIds),+ topicIds: toStringArray(record.topicIds),+ };+};++const isIntentType = (value: unknown): value is SelfFeedbackIntent['intentType'] =>+ value === 'memory' || value === 'skill' || value === 'tooling' || value === 'workflow';++const isRisk = (value: unknown): value is SelfFeedbackIntent['risk'] =>+ value === 'high' || value === 'low' || value === 'medium';++const isUrgency = (value: unknown): value is SelfFeedbackIntent['urgency'] =>+ value === 'immediate' || value === 'later' || value === 'soon';++const toReflectionIntent = (+ value: unknown,+ receipt: ReceiptActivityItemDigest,+): SelfFeedbackIntent | undefined => {+ const record = toRecord(value);+ if (!record || record.mode !== 'reflection') return;++ const intentType = isIntentType(record.intentType) ? record.intentType : undefined;+ const rationale = toString(record.rationale);+ if (!intentType || !rationale) return;++ return normalizeReflectionIntent({+ actionType: toString(record.actionType),+ confidence: typeof record.confidence === 'number' ? record.confidence : undefined,+ downgradeReason:+ record.downgradeReason === 'approval_required' ||+ record.downgradeReason === 'low_confidence' ||+ record.downgradeReason === 'unsupported_in_reflection'+ ? record.downgradeReason+ : undefined,+ evidenceRefs: toEvidenceRefs(record.evidenceRefs, receipt.id),+ idempotencyKey: toString(record.idempotencyKey) ?? receipt.id,+ intentType,+ mode: 'reflection',+ operation: toRecord(record.operation) as SelfFeedbackIntent['operation'],+ rationale,+ risk: isRisk(record.risk) ? record.risk : 'medium',+ target: toIntentTarget(record.target),+ title: toString(record.title),+ urgency: isUrgency(record.urgency) ? record.urgency : 'later',+ });+};++const getReflectionIntentPayloads = (receipt: ReceiptActivityItemDigest): unknown[] => {+ const selfIteration = toRecord(receipt.metadata?.selfIteration);+ if (!selfIteration || selfIteration.mode !== 'reflection') return [];++ if (Array.isArray(selfIteration.intents)) return selfIteration.intents;+ if (selfIteration.intent) return [selfIteration.intent];+ if (selfIteration.intentType) return [selfIteration];++ return [];+};++const getSelfFeedbackReviewCandidates = (receiptActivity: ReceiptActivityDigest) => {+ const intents = receiptActivity.recentReceipts.flatMap((receipt) =>+ getReflectionIntentPayloads(receipt).flatMap((payload) => {+ const intent = toReflectionIntent(payload, receipt);++ return intent ? [intent] : [];+ }),+ );++ return rankSelfFeedbackCandidates(groupSelfFeedbackIntents(intents));+};+/*** Creates a pure nightly review collector service from digest read adapters.*@@ -728,166 +924,172 @@ const createEmptyProposalActivity = (): ProposalActivityDigest => ({* Returns:* - A collector service with one context assembly method*/-export const createNightlyReviewService = (+export const createSelfReviewContextService = (readAdapters: NightlyReviewReadAdapters,-): NightlyReviewService => {- return {- collectNightlyReviewContext: async (input) => {- return tracer.startActiveSpan(- 'agent_signal.nightly_review.collector.collect',- {- attributes: {- 'agent.signal.agent_id': input.agentId,- 'agent.signal.nightly.max_managed_skills':- input.maxManagedSkills ?? DEFAULT_MAX_MANAGED_SKILLS,- 'agent.signal.nightly.max_memories':- input.maxRelevantMemories ?? DEFAULT_MAX_RELEVANT_MEMORIES,- 'agent.signal.nightly.max_topics': input.maxTopics ?? DEFAULT_MAX_TOPICS,- 'agent.signal.user_id': input.userId,- },+): SelfReviewContextService => {+ const collect = async (+ input: CollectNightlyReviewContextInput,+ ): Promise<NightlyReviewContext> => {+ return tracer.startActiveSpan(+ 'agent_signal.nightly_review.collector.collect',+ {+ attributes: {+ 'agent.signal.agent_id': input.agentId,+ 'agent.signal.nightly.max_managed_skills':+ input.maxManagedSkills ?? DEFAULT_MAX_MANAGED_SKILLS,+ 'agent.signal.nightly.max_memories':+ input.maxRelevantMemories ?? DEFAULT_MAX_RELEVANT_MEMORIES,+ 'agent.signal.nightly.max_topics': input.maxTopics ?? DEFAULT_MAX_TOPICS,+ 'agent.signal.user_id': input.userId,},- async (span) => {- try {- 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,- toolActivity,- documentActivity,- feedbackActivity,- receiptActivity,- proposalActivity,- ] = await Promise.all([- readAdapters.listTopicActivity({- ...readInput,- limit: input.topicFetchLimit ?? maxTopics * 3,- }),- readAdapters.listManagedSkills({- ...readInput,- limit: maxManagedSkills,- }),- readAdapters.listRelevantMemories({- ...readInput,- limit: maxRelevantMemories,- }),- readAdapters.listToolActivity?.(readInput) ?? Promise.resolve([]),- readAdapters.listDocumentActivity?.(readInput) ??- Promise.resolve(createEmptyDocumentActivity()),- readAdapters.listFeedbackActivity?.(readInput) ??- Promise.resolve(createEmptyFeedbackActivity()),- readAdapters.listReceiptActivity?.(readInput) ??- Promise.resolve(createEmptyReceiptActivity()),- readAdapters.listProposalActivity?.(readInput) ??- Promise.resolve(createEmptyProposalActivity()),- ]);- const topics = topicRows.map(normalizeTopic).sort(compareTopics).slice(0, maxTopics);- const maintenanceSignals = deriveNightlyMaintenanceSignals({- documentActivity,- feedbackActivity,- receiptActivity,- toolActivity,- topics,- });-- span.setAttribute('agent.signal.nightly.raw_topic_count', topicRows.length);- span.setAttribute('agent.signal.nightly.topic_count', topics.length);- span.setAttribute(- 'agent.signal.nightly.high_signal_topic_count',- topics.filter((topic) => topic.highSignalReasons.length > 0).length,- );- span.setAttribute('agent.signal.nightly.managed_skill_count', managedSkills.length);- span.setAttribute('agent.signal.nightly.memory_count', relevantMemories.length);- span.setAttribute('agent.signal.nightly.tool_activity_count', toolActivity.length);- span.setAttribute(- 'agent.signal.nightly.document_skill_event_count',- documentActivity.skillBucket.length,- );- span.setAttribute(- 'agent.signal.nightly.document_general_event_count',- documentActivity.generalDocumentBucket.length,- );- span.setAttribute(- 'agent.signal.nightly.feedback_satisfied_count',- feedbackActivity.satisfied.length,- );- span.setAttribute(- 'agent.signal.nightly.feedback_not_satisfied_count',- feedbackActivity.notSatisfied.length,- );- span.setAttribute(- 'agent.signal.nightly.receipt_pending_proposal_count',- receiptActivity.pendingProposalCount,- );- span.setAttribute(- 'agent.signal.nightly.proposal_active_count',- proposalActivity.active.length,- );- span.setAttribute(- 'agent.signal.nightly.proposal_expired_count',- proposalActivity.expiredCount,- );- span.setAttribute(- 'agent.signal.nightly.proposal_dismissed_count',- proposalActivity.dismissedCount,- );- span.setAttribute(- 'agent.signal.nightly.proposal_stale_count',- proposalActivity.staleCount,- );- span.setAttribute(- 'agent.signal.nightly.proposal_superseded_count',- proposalActivity.supersededCount,- );- span.setAttribute(- 'agent.signal.nightly.maintenance_signal_count',- maintenanceSignals.length,- );- span.addEvent('agent_signal.nightly_review.maintenance_signals_derived', {- 'agent.signal.nightly.maintenance_signal_count': maintenanceSignals.length,- 'agent.signal.nightly.maintenance_signal_kinds': maintenanceSignals- .map((signal) => signal.kind)- .join(','),- });- span.setStatus({ code: SpanStatusCode.OK });-- return {+ },+ async (span) => {+ try {+ 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,+ toolActivity,+ documentActivity,+ feedbackActivity,+ receiptActivity,+ proposalActivity,+ ] = await Promise.all([+ readAdapters.listTopicActivity({...readInput,- documentActivity,- feedbackActivity,- maintenanceSignals,- managedSkills: managedSkills.slice(0, maxManagedSkills),- proposalActivity,- receiptActivity,- relevantMemories: relevantMemories.slice(0, maxRelevantMemories),- toolActivity,- topics,- };- } catch (error) {- span.setStatus({- code: SpanStatusCode.ERROR,- message:- error instanceof Error- ? error.message- : 'AgentSignal nightly review context collection failed',- });- span.recordException(error as Error);-- throw error;- } finally {- span.end();- }- },- );- },+ limit: input.topicFetchLimit ?? maxTopics * 3,+ }),+ readAdapters.listManagedSkills({+ ...readInput,+ limit: maxManagedSkills,+ }),+ readAdapters.listRelevantMemories({+ ...readInput,+ limit: maxRelevantMemories,+ }),+ readAdapters.listToolActivity?.(readInput) ?? Promise.resolve([]),+ readAdapters.listDocumentActivity?.(readInput) ??+ Promise.resolve(createEmptyDocumentActivity()),+ readAdapters.listFeedbackActivity?.(readInput) ??+ Promise.resolve(createEmptyFeedbackActivity()),+ readAdapters.listReceiptActivity?.(readInput) ??+ Promise.resolve(createEmptyReceiptActivity()),+ readAdapters.listProposalActivity?.(readInput) ??+ Promise.resolve(createEmptyProposalActivity()),+ ]);+ const topics = topicRows.map(normalizeTopic).sort(compareTopics).slice(0, maxTopics);+ const selfReviewSignals = deriveSelfReviewSignals({+ documentActivity,+ feedbackActivity,+ receiptActivity,+ toolActivity,+ topics,+ });+ const selfFeedbackCandidates = getSelfFeedbackReviewCandidates(receiptActivity);++ span.setAttribute('agent.signal.nightly.raw_topic_count', topicRows.length);+ span.setAttribute('agent.signal.nightly.topic_count', topics.length);+ span.setAttribute(+ 'agent.signal.nightly.high_signal_topic_count',+ topics.filter((topic) => topic.highSignalReasons.length > 0).length,+ );+ span.setAttribute('agent.signal.nightly.managed_skill_count', managedSkills.length);+ span.setAttribute('agent.signal.nightly.memory_count', relevantMemories.length);+ span.setAttribute('agent.signal.nightly.tool_activity_count', toolActivity.length);+ span.setAttribute(+ 'agent.signal.nightly.document_skill_event_count',+ documentActivity.skillBucket.length,+ );+ span.setAttribute(+ 'agent.signal.nightly.document_general_event_count',+ documentActivity.generalDocumentBucket.length,+ );+ span.setAttribute(+ 'agent.signal.nightly.feedback_satisfied_count',+ feedbackActivity.satisfied.length,+ );+ span.setAttribute(+ 'agent.signal.nightly.feedback_not_satisfied_count',+ feedbackActivity.notSatisfied.length,+ );+ span.setAttribute(+ 'agent.signal.nightly.receipt_pending_proposal_count',+ receiptActivity.pendingProposalCount,+ );+ span.setAttribute(+ 'agent.signal.nightly.proposal_active_count',+ proposalActivity.active.length,+ );+ span.setAttribute(+ 'agent.signal.nightly.proposal_expired_count',+ proposalActivity.expiredCount,+ );+ span.setAttribute(+ 'agent.signal.nightly.proposal_dismissed_count',+ proposalActivity.dismissedCount,+ );+ span.setAttribute(+ 'agent.signal.nightly.proposal_stale_count',+ proposalActivity.staleCount,+ );+ span.setAttribute(+ 'agent.signal.nightly.proposal_superseded_count',+ proposalActivity.supersededCount,+ );+ span.setAttribute(+ 'agent.signal.nightly.self_review_signal_count',+ selfReviewSignals.length,+ );+ span.addEvent('agent_signal.nightly_review.self_review_signals_derived', {+ 'agent.signal.nightly.self_review_signal_count': selfReviewSignals.length,+ 'agent.signal.nightly.self_review_signal_kinds': selfReviewSignals+ .map((signal) => signal.kind)+ .join(','),+ });+ span.setStatus({ code: SpanStatusCode.OK });++ return {+ ...readInput,+ documentActivity,+ feedbackActivity,+ selfReviewSignals,+ managedSkills: managedSkills.slice(0, maxManagedSkills),+ proposalActivity,+ receiptActivity,+ relevantMemories: relevantMemories.slice(0, maxRelevantMemories),+ toolActivity,+ topics,+ selfFeedbackCandidates,+ };+ } catch (error) {+ span.setStatus({+ code: SpanStatusCode.ERROR,+ message:+ error instanceof Error+ ? error.message+ : 'AgentSignal nightly review context collection failed',+ });+ span.recordException(error as Error);++ throw error;+ } finally {+ span.end();+ }+ },+ );+ };++ return {+ collect,};};diff --git a/src/server/services/agentSignal/policies/reviewNightly/nightlyReview.ts b/src/server/services/agentSignal/services/selfIteration/review/handler.tssimilarity index 87%rename from src/server/services/agentSignal/policies/reviewNightly/nightlyReview.tsrename to src/server/services/agentSignal/services/selfIteration/review/handler.tsindex 7954132da1b..b22f6c6d74a 100644--- a/src/server/services/agentSignal/policies/reviewNightly/nightlyReview.ts+++ b/src/server/services/agentSignal/services/selfIteration/review/handler.ts@@ -3,26 +3,16 @@ import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';import { SpanStatusCode } from '@lobechat/observability-otel/api';import { tracer } from '@lobechat/observability-otel/modules/agent-signal';-import { defineSourceHandler } from '../../runtime/middleware';-import type { MaintenanceAgentRunResult } from '../../services/maintenance/agentRunner';-import type { MaintenanceBriefProjection } from '../../services/maintenance/brief';-import {- createBriefMaintenanceService,- getNightlySelfReviewBriefMetadata,-} from '../../services/maintenance/brief';-import type {- CollectNightlyReviewContextInput,- NightlyReviewContext,-} from '../../services/maintenance/nightlyCollector';-import type { MaintenanceProposalPlan } from '../../services/maintenance/proposal';-import type {- EvidenceRef,- MaintenancePlan,- MaintenanceReviewRunResult,-} from '../../services/maintenance/types';-import { buildNightlyReviewSourceId, ReviewRunStatus } from '../../services/maintenance/types';-import type { AgentSignalReceipt } from '../../services/receiptService';-import { createMaintenanceReviewReceipts } from '../../services/receiptService';+import { defineSourceHandler } from '../../../runtime/middleware';+import type { AgentSignalReceipt } from '../../receiptService';+import { createSelfReviewReceipts } from '../../receiptService';+import type { AgentRunResult } from '../execute';+import type { EvidenceRef, Plan, RunResult } from '../types';+import { buildNightlyReviewSourceId, ReviewRunStatus } from '../types';+import type { SelfReviewBriefProjection } from './brief';+import { createBriefSelfReviewService, getNightlySelfReviewBriefMetadata } from './brief';+import type { CollectNightlyReviewContextInput, NightlyReviewContext } from './collect';+import type { SelfReviewProposalPlan } from './proposal';/*** Validated nightly review request payload consumed by the handler.@@ -60,15 +50,15 @@ export interface NightlyReviewSourceGuardInput extends NightlyReviewSourcePayloaexport 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. */+ /** Whether Daily Brief creation failed after shared execution. */briefWriteFailed?: boolean;/** Executor result for completed runs. */- execution?: MaintenanceReviewRunResult;+ execution?: RunResult;/** 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. */+ /** Number of planned self-review actions before execution. */plannedActionCount?: number;/** Planner summary for future brief construction. */planSummary?: string;@@ -94,17 +84,17 @@ export interface CreateNightlyReviewSourceHandlerDependencies {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. */+ /** Collects bounded digest context without mutating shared resources. */collectContext: (input: CollectNightlyReviewContextInput) => Promise<NightlyReviewContext>;- /** Runs the bounded maintenance agent and returns execution plus the frozen projection plan. */- runMaintenanceReviewAgent: (input: {+ /** Runs the bounded self-iteration agent and returns execution plus the frozen projection plan. */+ runSelfReviewAgent: (input: {context: NightlyReviewContext;localDate: string;sourceId: string;userId: string;- }) => Promise<MaintenanceAgentRunResult>;+ }) => Promise<AgentRunResult>;/** Writes a Daily Brief payload for user-visible nightly outcomes. */- writeDailyBrief?: (brief: MaintenanceBriefProjection) => Promise<{ id?: string } | void>;+ writeDailyBrief?: (brief: SelfReviewBriefProjection) => Promise<{ id?: string } | void>;/** Writes durable receipts for the review summary and action outcomes. */writeReceipts?: (receipts: AgentSignalReceipt[]) => Promise<void>;}@@ -201,9 +191,9 @@ const toBaseResult = (});const applyReceiptIdsToExecution = (- execution: MaintenanceReviewRunResult,+ execution: RunResult,receipts: AgentSignalReceipt[],-): MaintenanceReviewRunResult => {+): RunResult => {const receiptByActionKey = new Map(receipts.filter((receipt) => receipt.id.endsWith(':action'))@@ -222,7 +212,7 @@ const applyReceiptIdsToExecution = (};};-const collectPlanEvidenceRefs = (plan: MaintenancePlan): EvidenceRef[] => {+const collectPlanEvidenceRefs = (plan: Plan): EvidenceRef[] => {const evidenceRefs = new Map<string, EvidenceRef>();for (const action of plan.actions) {@@ -237,17 +227,17 @@ const collectPlanEvidenceRefs = (plan: MaintenancePlan): EvidenceRef[] => {const isMergeableProposalAction = (actionType: string) =>actionType === 'create_skill' || actionType === 'refine_skill';-const hasProjectionBaseSnapshot = (action: MaintenancePlan['actions'][number]) => {+const hasProjectionBaseSnapshot = (action: Plan['actions'][number]) => {if (!isMergeableProposalAction(action.actionType)) return true;- const actionWithSnapshot = action as MaintenancePlan['actions'][number] & {+ const actionWithSnapshot = action as Plan['actions'][number] & {baseSnapshot?: unknown;};return actionWithSnapshot.baseSnapshot !== undefined;};-const isSnapshotAwareProposalPlan = (plan: MaintenancePlan): plan is MaintenanceProposalPlan =>+const isSnapshotAwareProposalPlan = (plan: Plan): plan is SelfReviewProposalPlan =>plan.actions.every(hasProjectionBaseSnapshot);const writeNightlyReceipts = async (@@ -285,7 +275,7 @@ const writeNightlyReceipts = async (const writeNightlyBrief = async (deps: CreateNightlyReviewSourceHandlerDependencies,- brief: MaintenanceBriefProjection | undefined,+ brief: SelfReviewBriefProjection | undefined,) => {if (!deps.writeDailyBrief || !brief) return {};@@ -340,11 +330,11 @@ const writeNightlyBrief = async (* - `agent.nightly_review.requested`** Downstream:- * - injected bounded maintenance agent runner+ * - injected bounded self-iteration agent runner** 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+ * - Runtime policy composition needs a side-effect boundary before executing self-iteration plans** Expects:* - `source` is an `agent.nightly_review.requested` source with scheduler-produced payload@@ -438,8 +428,8 @@ export const createNightlyReviewSourceHandler = (}),(span, collectedContext) => {span.setAttribute(- 'agent.signal.nightly.context_maintenance_signal_count',- collectedContext.maintenanceSignals?.length ?? 0,+ 'agent.signal.nightly.context_self_review_signal_count',+ collectedContext.selfReviewSignals?.length ?? 0,);span.setAttribute('agent.signal.nightly.context_tool_activity_count',@@ -458,8 +448,7 @@ export const createNightlyReviewSourceHandler = ('agent.signal.nightly.document_skill_event_count':context.documentActivity?.skillBucket?.length ?? 0,'agent.signal.nightly.managed_skill_count': context.managedSkills.length,- 'agent.signal.nightly.maintenance_signal_count':- context.maintenanceSignals?.length ?? 0,+ 'agent.signal.nightly.self_review_signal_count': context.selfReviewSignals?.length ?? 0,'agent.signal.nightly.memory_count': context.relevantMemories.length,'agent.signal.nightly.topic_count': context.topics.length,'agent.signal.nightly.tool_activity_count': context.toolActivity?.length ?? 0,@@ -467,7 +456,7 @@ export const createNightlyReviewSourceHandler = ('agent.signal.user_id': payload.userId,},() =>- deps.runMaintenanceReviewAgent({+ deps.runSelfReviewAgent({context,localDate: payload.localDate,sourceId: source.sourceId,@@ -490,7 +479,7 @@ export const createNightlyReviewSourceHandler = (const plan = agentResult.projectionPlan;const proposalPlan = isSnapshotAwareProposalPlan(plan) ? plan : undefined;const execution = agentResult.execution;- const receipts = createMaintenanceReviewReceipts({+ const receipts = createSelfReviewReceipts({agentId: payload.agentId,createdAt: source.timestamp,localDate: payload.localDate,@@ -514,7 +503,7 @@ export const createNightlyReviewSourceHandler = (await writeNightlyReceipts(deps, receipts);- const brief = createBriefMaintenanceService().projectNightlyReviewBrief({+ const brief = createBriefSelfReviewService().projectNightlyReviewBrief({agentId: payload.agentId,evidenceRefs: collectPlanEvidenceRefs(plan),ideas: agentResult.ideas,@@ -576,7 +565,7 @@ export const createNightlyReviewSourcePolicyHandler = (return defineSourceHandler(AGENT_SIGNAL_SOURCE_TYPES.agentNightlyReviewRequested,- `${AGENT_SIGNAL_SOURCE_TYPES.agentNightlyReviewRequested}:maintenance-review`,+ `${AGENT_SIGNAL_SOURCE_TYPES.agentNightlyReviewRequested}:shared-review`,async (source: SourceAgentNightlyReviewRequested) => {const result = await handler.handle(source);diff --git a/src/server/services/agentSignal/services/selfIteration/review/intentPolicy.ts b/src/server/services/agentSignal/services/selfIteration/review/intentPolicy.tsnew file mode 100644index 00000000000..83c5c332641--- /dev/null+++ b/src/server/services/agentSignal/services/selfIteration/review/intentPolicy.ts@@ -0,0 +1,274 @@+import type { SelfFeedbackIntent } from '../types';++/** Evidence strength assigned to a squashed self-feedback intent group. */+export type ReviewEvidenceStrength = 'medium' | 'strong' | 'weak';++/** Review behavior selected for one ranked shared candidate. */+export type ReviewCandidateBehavior = 'idea_or_wait' | 'proposal_priority' | 'weak_evidence';++/** Reflection intent shape accepted by the review policy before normalization. */+export interface ReflectionIntentPolicyInput extends Omit<SelfFeedbackIntent, 'confidence'> {+ /** Optional confidence; missing values default to `0.5`. */+ confidence?: number;+}++/** Group of normalized reflection intents that target the same review decision. */+export interface SelfFeedbackIntentGroup {+ /** Intents in this group. */+ intents: SelfFeedbackIntent[];+ /** Stable grouping key: `intentType + actionType + target signature`. */+ key: string;+}++/** Squashed candidate produced from one intent group. */+export interface SquashedSelfFeedbackIntentGroup {+ /** Aggregate confidence calculated with max(confidence). */+ confidence: number;+ /** Evidence ids after de-duplicating group evidence refs. */+ evidenceRefs: SelfFeedbackIntent['evidenceRefs'];+ /** Evidence strength derived from confidence and repetition. */+ evidenceStrength: ReviewEvidenceStrength;+ /** Representative intent selected by confidence and urgency. */+ intent: SelfFeedbackIntent;+ /** Stable group key. */+ key: string;+ /** Number of intents in the group. */+ repeatCount: number;+}++/** Ranked review candidate with behavior guidance for the review agent prompt. */+export interface RankedSelfFeedbackCandidate extends SquashedSelfFeedbackIntentGroup {+ /** How review should treat this candidate. */+ reviewBehavior: ReviewCandidateBehavior;+}++const urgencyRank = {+ immediate: 0,+ soon: 1,+ later: 2,+} satisfies Record<SelfFeedbackIntent['urgency'], number>;++const clampConfidence = (value: number | undefined) => {+ if (typeof value !== 'number' || Number.isNaN(value)) return 0.5;++ return Math.min(1, Math.max(0, value));+};++const getEvidenceKey = (evidence: SelfFeedbackIntent['evidenceRefs'][number]) =>+ `${evidence.type}:${evidence.id}`;++const hasTargetOrOperation = (intent: SelfFeedbackIntent) =>+ Boolean(+ intent.operation ||+ intent.target?.memoryId ||+ intent.target?.skillDocumentId ||+ intent.target?.skillName ||+ intent.target?.topicIds?.length ||+ intent.target?.taskIds?.length,+ );++/**+ * Normalizes reflection intent payloads before review grouping.+ *+ * | Input | Output |+ * | --- | --- |+ * | missing confidence | `0.5` |+ * | confidence `< 0` | `0` |+ * | confidence `> 1` | `1` |+ *+ * Use when:+ * - Receipt metadata may omit confidence+ * - Review needs stable math before ranking candidates+ *+ * Expects:+ * - Input already represents reflection-mode agent feedback+ *+ * Returns:+ * - A normalized intent with confidence clamped to 0..1+ */+export const normalizeReflectionIntent = (+ intent: ReflectionIntentPolicyInput,+): SelfFeedbackIntent => ({+ ...intent,+ confidence: clampConfidence(intent.confidence),+});++/**+ * Builds a deterministic target signature for grouping reflection intents.+ *+ * | Target data | Signature |+ * | --- | --- |+ * | `skillDocumentId` | `skill:<id>` |+ * | `skillName` | `skill-name:<name>` |+ * | `memoryId` | `memory:<id>` |+ * | topic ids | `topics:<sorted ids>` |+ * | task ids | `tasks:<sorted ids>` |+ * | no target | `target:none` |+ *+ * Use when:+ * - Review needs repeated reflection intents to squash into one candidate+ * - Target order should not affect grouping+ *+ * Expects:+ * - Intent target ids are stable within the review window+ *+ * Returns:+ * - A compact string suitable for a group key+ */+export const getSelfFeedbackIntentTargetSignature = (intent: SelfFeedbackIntent) => {+ if (intent.target?.skillDocumentId) return `skill:${intent.target.skillDocumentId}`;+ if (intent.target?.skillName) return `skill-name:${intent.target.skillName}`;+ if (intent.target?.memoryId) return `memory:${intent.target.memoryId}`;+ if (intent.target?.topicIds?.length) {+ return `topics:${[...intent.target.topicIds].sort().join(',')}`;+ }+ if (intent.target?.taskIds?.length) {+ return `tasks:${[...intent.target.taskIds].sort().join(',')}`;+ }++ return 'target:none';+};++/**+ * Groups normalized reflection intents by type, action, and target.+ *+ * | Rule | Calculation |+ * | --- | --- |+ * | Group key | `intentType + actionType + target signature` |+ * | Missing action type | `unknown` |+ * | Target signature | {@link getSelfFeedbackIntentTargetSignature} |+ *+ * Use when:+ * - Review context needs repeated reflection feedback squashed before prompting+ *+ * Expects:+ * - Callers normalize confidence with {@link normalizeReflectionIntent}+ *+ * Returns:+ * - Groups in first-seen order+ */+export const groupSelfFeedbackIntents = (+ intents: SelfFeedbackIntent[],+): SelfFeedbackIntentGroup[] => {+ const groups = new Map<string, SelfFeedbackIntent[]>();++ for (const intent of intents) {+ const key = `${intent.intentType}:${intent.actionType ?? 'unknown'}:${getSelfFeedbackIntentTargetSignature(intent)}`;+ const group = groups.get(key);++ if (group) {+ group.push(intent);+ } else {+ groups.set(key, [intent]);+ }+ }++ return [...groups.entries()].map(([key, groupIntents]) => ({ intents: groupIntents, key }));+};++const getEvidenceStrength = (confidence: number, repeatCount: number): ReviewEvidenceStrength => {+ if (confidence < 0.5) return 'weak';+ if (confidence >= 0.8 || repeatCount >= 2) return 'strong';++ return 'medium';+};++/**+ * Squashes one intent group into a review candidate.+ *+ * | Rule | Calculation |+ * | --- | --- |+ * | Aggregate confidence | `max(confidence)` |+ * | Repeated evidence | increases evidence strength, not confidence |+ * | Weak threshold | `< 0.5` |+ * | Medium threshold | `>= 0.5` and `< 0.8` |+ * | Strong threshold | `>= 0.8` or repeated matching intents |+ *+ * Use when:+ * - Review needs one candidate per target/action group+ *+ * Expects:+ * - The group contains at least one normalized intent+ *+ * Returns:+ * - Confidence, evidence strength, representative intent, and de-duplicated evidence refs+ */+export const squashSelfFeedbackIntentGroup = (+ group: SelfFeedbackIntentGroup,+): SquashedSelfFeedbackIntentGroup => {+ const sorted = [...group.intents].sort((a, b) => {+ const confidenceDelta = b.confidence - a.confidence;+ if (confidenceDelta !== 0) return confidenceDelta;++ return urgencyRank[a.urgency] - urgencyRank[b.urgency];+ });+ const intent = sorted[0];+ const confidence = Math.max(...group.intents.map((item) => item.confidence));+ const evidenceMap = new Map<string, SelfFeedbackIntent['evidenceRefs'][number]>();++ for (const item of group.intents) {+ for (const evidence of item.evidenceRefs) {+ evidenceMap.set(getEvidenceKey(evidence), evidence);+ }+ }++ return {+ confidence,+ evidenceRefs: [...evidenceMap.values()],+ evidenceStrength: getEvidenceStrength(confidence, group.intents.length),+ intent,+ key: group.key,+ repeatCount: group.intents.length,+ };+};++const getReviewBehavior = (candidate: SquashedSelfFeedbackIntentGroup): ReviewCandidateBehavior => {+ if (candidate.confidence < 0.5) return 'weak_evidence';+ if (+ candidate.confidence >= 0.8 &&+ hasTargetOrOperation(candidate.intent) &&+ candidate.intent.target?.readonly !== true+ ) {+ return 'proposal_priority';+ }++ return 'idea_or_wait';+};++/**+ * Ranks squashed reflection intent groups for nightly self-review.+ *+ * | Rule | Calculation |+ * | --- | --- |+ * | Immediate priority | `immediate` before `soon` before `later` |+ * | Proposal priority | confidence `>= 0.8` with target or operation |+ * | Duplicate groups | squash before ranking |+ *+ * Use when:+ * - Collector exposes reflection intents as review evidence+ * - Prompt builders need deterministic ordering before LLM review+ *+ * Expects:+ * - Groups come from {@link groupSelfFeedbackIntents}+ *+ * Returns:+ * - Ranked candidates with review behavior hints+ */+export const rankSelfFeedbackCandidates = (+ groups: SelfFeedbackIntentGroup[],+): RankedSelfFeedbackCandidate[] =>+ groups+ .map((group) => {+ const candidate = squashSelfFeedbackIntentGroup(group);++ return {+ ...candidate,+ reviewBehavior: getReviewBehavior(candidate),+ };+ })+ .sort((a, b) => {+ const urgencyDelta = urgencyRank[a.intent.urgency] - urgencyRank[b.intent.urgency];+ if (urgencyDelta !== 0) return urgencyDelta;++ return b.confidence - a.confidence;+ });diff --git a/src/server/services/agentSignal/services/maintenance/proposal.ts b/src/server/services/agentSignal/services/selfIteration/review/proposal.tssimilarity index 74%rename from src/server/services/agentSignal/services/maintenance/proposal.tsrename to src/server/services/agentSignal/services/selfIteration/review/proposal.tsindex 42116673cdd..b2e3e79593e 100644--- a/src/server/services/agentSignal/services/maintenance/proposal.ts+++ b/src/server/services/agentSignal/services/selfIteration/review/proposal.ts@@ -2,18 +2,18 @@ import type { BriefAction } from '@lobechat/types';import { z } from 'zod';import type {+ ActionPlan,+ ActionResult,+ ActionTarget,+ ActionType,EvidenceRef,- MaintenanceActionPlan,- MaintenanceActionResult,- MaintenanceActionTarget,- MaintenanceActionType,- MaintenancePlan,-} from './types';-import { MaintenanceActionStatus, MaintenanceRisk } from './types';+ Plan,+} from '../types';+import { ActionStatus, Risk } from '../types';-export const MAINTENANCE_PROPOSAL_VERSION = 1;+export const SELF_REVIEW_PROPOSAL_VERSION = 1;-export type MaintenanceProposalStatus =+export type SelfReviewProposalStatus =| 'pending'| 'accepted'| 'applying'@@ -25,16 +25,16 @@ export type MaintenanceProposalStatus =| 'stale'| 'superseded';-const MAINTENANCE_ACTION_TYPES = [+const SELF_ITERATION_ACTION_TYPES = ['write_memory','create_skill','refine_skill','consolidate_skill','noop','proposal_only',-] as const satisfies MaintenanceActionType[];+] as const satisfies ActionType[];-const MAINTENANCE_PROPOSAL_STATUSES = [+const SELF_REVIEW_PROPOSAL_STATUSES = ['pending','accepted','applying',@@ -45,15 +45,11 @@ const MAINTENANCE_PROPOSAL_STATUSES = ['expired','stale','superseded',-] as const satisfies MaintenanceProposalStatus[];+] as const satisfies SelfReviewProposalStatus[];-const MAINTENANCE_RISKS = [- MaintenanceRisk.High,- MaintenanceRisk.Low,- MaintenanceRisk.Medium,-] as const satisfies MaintenanceRisk[];+const SELF_ITERATION_RISKS = [Risk.High, Risk.Low, Risk.Medium] as const satisfies Risk[];-export type MaintenanceProposalConflictReason =+export type SelfReviewProposalConflictReason =| 'agent_gate_disabled'| 'content_changed'| 'document_changed'@@ -67,9 +63,9 @@ export type MaintenanceProposalConflictReason =| 'user_gate_disabled'| 'server_gate_disabled';-export interface BuildMaintenanceProposalKeyInput {+export interface BuildSelfReviewProposalKeyInput {/** Action category represented by the proposal. */- actionType: MaintenanceActionType;+ actionType: ActionType;/** Agent whose self-review produced the proposal. */agentId: string;/** Stable target id inside the selected target type. */@@ -78,7 +74,7 @@ export interface BuildMaintenanceProposalKeyInput {targetType: 'agent_document' | 'memory' | 'skill' | 'unknown';}-export interface MaintenanceProposalBaseSnapshot {+export interface SelfReviewProposalBaseSnapshot {/** Whether the target was absent when the proposal was approved for creation. */absent?: boolean;/** Agent document id when the proposal targets managed skill/document state. */@@ -101,37 +97,37 @@ export interface MaintenanceProposalBaseSnapshot {writable?: boolean;}-export interface MaintenanceProposalAction {+export interface SelfReviewProposalAction {/** Planned action type frozen into the proposal. */- actionType: MaintenanceActionType;+ actionType: ActionType;/** Optional target freshness snapshot used by approve-time preflight. */- baseSnapshot?: MaintenanceProposalBaseSnapshot;+ baseSnapshot?: SelfReviewProposalBaseSnapshot;/** Bounded evidence references retained for audit and prompt context. */evidenceRefs: EvidenceRef[];- /** Stable operation idempotency key from the original maintenance plan. */+ /** Stable operation idempotency key from the original self-iteration plan. */idempotencyKey: string;/** Frozen domain operation to apply after user approval when still fresh. */- operation?: MaintenanceActionPlan['operation'];- /** Reviewer rationale shown to users and future maintenance runs. */+ operation?: ActionPlan['operation'];+ /** Reviewer rationale shown to users and future shared runs. */rationale: string;- /** Risk assigned by the maintenance planner. */- risk: MaintenanceRisk;+ /** Risk assigned by the self-iteration planner. */+ risk: Risk;/** Bounded target identity from the original plan. */- target?: MaintenanceActionTarget;+ target?: ActionTarget;}/** Non-actionable self-review thought retained for future review without approve-time mutation. */-export interface MaintenanceReviewIdea {+export interface SelfReviewIdea {/** Bounded evidence references retained for audit and future review context. */evidenceRefs: EvidenceRef[];/** Stable idempotency key from the proposal-only action. */idempotencyKey: string;/** Reviewer rationale explaining why this is an idea instead of an executable action. */rationale: string;- /** Risk assigned by the maintenance reviewer. */- risk: MaintenanceRisk;+ /** Risk assigned by the self-reviewer. */+ risk: Risk;/** Optional target identity the idea is about. */- target?: MaintenanceActionTarget;+ target?: ActionTarget;/** Optional short title for UI or digest presentation. */title?: string;}@@ -141,41 +137,41 @@ export interface MaintenanceReviewIdea {** @param TActionType - Mergeable action type that must carry a complete base snapshot.*/-export type MergeableMaintenanceProposalActionPlan<+export type MergeableSelfReviewProposalActionPlan<TActionType extends 'create_skill' | 'refine_skill' = 'create_skill' | 'refine_skill',-> = MaintenanceActionPlan & {+> = ActionPlan & {/** Mergeable action type that will be applied from a frozen proposal. */actionType: TActionType;/** Complete merge base captured before proposal projection. */- baseSnapshot: MaintenanceProposalBaseSnapshot;+ baseSnapshot: SelfReviewProposalBaseSnapshot;};/**- * Proposal projection action for non-mergeable maintenance mutations.+ * Proposal projection action for non-mergeable self-iteration mutations.*/-export type NonMergeableMaintenanceProposalActionPlan = MaintenanceActionPlan & {+export type NonMergeableSelfReviewProposalActionPlan = ActionPlan & {/** Non-mergeable action type that can use legacy title-only fallback snapshots. */- actionType: Exclude<MaintenanceActionType, 'create_skill' | 'refine_skill'>;+ actionType: Exclude<ActionType, 'create_skill' | 'refine_skill'>;/** Optional proposal snapshot supplied by callers before projection. */- baseSnapshot?: MaintenanceProposalBaseSnapshot;+ baseSnapshot?: SelfReviewProposalBaseSnapshot;};/*** Snapshot-aware action accepted by proposal metadata projection.*/-export type MaintenanceProposalActionPlan =- | MergeableMaintenanceProposalActionPlan- | NonMergeableMaintenanceProposalActionPlan;+export type SelfReviewProposalActionPlan =+ | MergeableSelfReviewProposalActionPlan+ | NonMergeableSelfReviewProposalActionPlan;/**- * Snapshot-aware maintenance plan accepted by proposal metadata projection.+ * Snapshot-aware self-iteration plan accepted by proposal metadata projection.*/-export type MaintenanceProposalPlan = Omit<MaintenancePlan, 'actions'> & {+export type SelfReviewProposalPlan = Omit<Plan, 'actions'> & {/** Planned actions with required base snapshots for mergeable proposal mutations. */- actions: MaintenanceProposalActionPlan[];+ actions: SelfReviewProposalActionPlan[];};-export interface MaintenanceProposalActionApplyResult {+export interface SelfReviewProposalActionApplyResult {/** Frozen action idempotency key this apply result belongs to. */idempotencyKey: string;/** Resource id touched by the action when one exists. */@@ -186,24 +182,24 @@ export interface MaintenanceProposalActionApplyResult {summary?: string;}-export interface MaintenanceProposalApplyAttempt {+export interface SelfReviewProposalApplyAttempt {/** Per-action results in proposal action order. */- actionResults: MaintenanceProposalActionApplyResult[];+ actionResults: SelfReviewProposalActionApplyResult[];/** ISO timestamp for this apply attempt. */appliedAt: string;/** Aggregate apply attempt status. */status: 'applied' | 'failed' | 'partially_failed' | 'stale';}-export interface MaintenanceProposalMetadata {+export interface SelfReviewProposalMetadata {/** Frozen proposal actions. */- actions: MaintenanceProposalAction[];+ actions: SelfReviewProposalAction[];/** Dominant action type used for digest grouping and refresh checks. */- actionType: MaintenanceActionType;+ actionType: ActionType;/** Historical approve/apply attempts for this proposal. */- applyAttempts?: MaintenanceProposalApplyAttempt[];+ applyAttempts?: SelfReviewProposalApplyAttempt[];/** Conflict reason when the proposal cannot be applied as-is. */- conflictReason?: MaintenanceProposalConflictReason;+ conflictReason?: SelfReviewProposalConflictReason;/** ISO timestamp when the proposal was first created. */createdAt: string;/** Bounded evidence retained at proposal level. */@@ -217,28 +213,24 @@ export interface MaintenanceProposalMetadata {/** Stable one-pending-proposal key for this target/action pair. */proposalKey: string;/** Current proposal lifecycle state. */- status: MaintenanceProposalStatus;+ status: SelfReviewProposalStatus;/** Proposal key or brief id that superseded this proposal. */supersededBy?: string;/** ISO timestamp for the last proposal lifecycle update. */updatedAt: string;/** Metadata schema version. */- version: typeof MAINTENANCE_PROPOSAL_VERSION;+ version: typeof SELF_REVIEW_PROPOSAL_VERSION;}-export interface MaintenanceProposalBriefMetadata {+export interface SelfReviewProposalBriefMetadata {/** Namespaced Agent Signal metadata stored inside Daily Brief metadata. */agentSignal?: {- /** Nightly self-review metadata owned by Agent Signal maintenance. */+ /** Nightly self-review metadata owned by Agent Signal. */nightlySelfReview?: {- /** Frozen maintenance proposal state for approve/dismiss flows. */- maintenanceProposal?: MaintenanceProposalMetadata;- /** Legacy transition field accepted while local data is migrated. */- proposal?: MaintenanceProposalMetadata;+ /** Frozen self-review proposal state for approve/dismiss flows. */+ selfReviewProposal?: SelfReviewProposalMetadata;};};- /** Agent Signal maintenance proposal metadata stored inside Daily Brief metadata. */- proposal?: MaintenanceProposalMetadata;}export const AGENT_SIGNAL_PROPOSAL_BRIEF_ACTIONS = [@@ -247,6 +239,9 @@ export const AGENT_SIGNAL_PROPOSAL_BRIEF_ACTIONS = [{ key: 'feedback', label: 'Request changes', type: 'comment' },] satisfies BriefAction[];+/** Daily Brief actions for nightly self-review proposal cards. */+export const AGENT_SIGNAL_SELF_REVIEW_PROPOSAL_BRIEF_ACTIONS = AGENT_SIGNAL_PROPOSAL_BRIEF_ACTIONS;+const EvidenceRefSchema = z.object({id: z.string(),@@ -265,7 +260,7 @@ const EvidenceRefSchema = z}).passthrough();-const MaintenanceProposalBaseSnapshotSchema = z+const SelfReviewProposalBaseSnapshotSchema = z.object({absent: z.boolean().optional(),agentDocumentId: z.string().optional(),@@ -280,23 +275,23 @@ const MaintenanceProposalBaseSnapshotSchema = z}).passthrough();-const MaintenanceProposalActionSchema = z+const SelfReviewProposalActionSchema = z.object({- actionType: z.enum(MAINTENANCE_ACTION_TYPES),- baseSnapshot: MaintenanceProposalBaseSnapshotSchema.optional(),+ actionType: z.enum(SELF_ITERATION_ACTION_TYPES),+ baseSnapshot: SelfReviewProposalBaseSnapshotSchema.optional(),evidenceRefs: z.array(EvidenceRefSchema),idempotencyKey: z.string(),operation: z.unknown().optional(),rationale: z.string(),- risk: z.enum(MAINTENANCE_RISKS),+ risk: z.enum(SELF_ITERATION_RISKS),target: z.unknown().optional(),}).passthrough();-const MaintenanceProposalMetadataSchema = z+const SelfReviewProposalMetadataSchema = z.object({- actions: z.array(MaintenanceProposalActionSchema),- actionType: z.enum(MAINTENANCE_ACTION_TYPES),+ actions: z.array(SelfReviewProposalActionSchema),+ actionType: z.enum(SELF_ITERATION_ACTION_TYPES),applyAttempts: z.unknown().optional(),conflictReason: z.unknown().optional(),createdAt: z.string(),@@ -305,14 +300,14 @@ const MaintenanceProposalMetadataSchema = zevidenceWindowStart: z.string(),expiresAt: z.string(),proposalKey: z.string(),- status: z.enum(MAINTENANCE_PROPOSAL_STATUSES),+ status: z.enum(SELF_REVIEW_PROPOSAL_STATUSES),supersededBy: z.string().optional(),updatedAt: z.string(),- version: z.literal(MAINTENANCE_PROPOSAL_VERSION),+ version: z.literal(SELF_REVIEW_PROPOSAL_VERSION),}).passthrough();-const getMergeableProposalSnapshotError = (action: MaintenanceProposalActionPlan) =>+const getMergeableProposalSnapshotError = (action: SelfReviewProposalActionPlan) =>`Mergeable proposal action requires a complete base snapshot. actionType=${action.actionType}`;const isMergeableProposalAction = (actionType: string) =>@@ -322,7 +317,7 @@ const hasRequiredString = (value: unknown) => typeof value === 'string' && valueconst hasCompleteMergeableSnapshot = (actionType: string,- snapshot: MaintenanceProposalBaseSnapshot | undefined,+ snapshot: SelfReviewProposalBaseSnapshot | undefined,) => {if (!snapshot || snapshot.targetType !== 'skill') return false;@@ -357,12 +352,12 @@ const hasCompleteMergeableSnapshot = (* Returns:* - A colon-delimited key stable across retries for the same proposal target*/-export const buildMaintenanceProposalKey = ({+export const buildSelfReviewProposalKey = ({actionType,agentId,targetId,targetType,-}: BuildMaintenanceProposalKeyInput) => [agentId, actionType, targetType, targetId].join(':');+}: BuildSelfReviewProposalKeyInput) => [agentId, actionType, targetType, targetId].join(':');/*** Calculates the next expiry for a pending proposal.@@ -399,16 +394,14 @@ export const getNextProposalExpiry = ({ createdAt, now }: { createdAt: string; n* Returns:* - `true` only when required proposal metadata fields are present*/-export const isMaintenanceProposalMetadata = (- value: unknown,-): value is MaintenanceProposalMetadata =>- MaintenanceProposalMetadataSchema.safeParse(value).success;+export const isSelfReviewProposalMetadata = (value: unknown): value is SelfReviewProposalMetadata =>+ SelfReviewProposalMetadataSchema.safeParse(value).success;/*** Reads proposal metadata from a Daily Brief metadata object.** Use when:- * - Brief approve/dismiss paths need the stored maintenance proposal+ * - Brief approve/dismiss paths need the stored self-review proposal* - Proposal digest collectors inspect unresolved Agent Signal briefs** Expects:@@ -417,23 +410,20 @@ export const isMaintenanceProposalMetadata = (* Returns:* - Parsed proposal metadata when present, otherwise `undefined`*/-export const getMaintenanceProposalFromBriefMetadata = (+export const getSelfReviewProposalFromBriefMetadata = (metadata: unknown,-): MaintenanceProposalMetadata | undefined => {+): SelfReviewProposalMetadata | undefined => {if (!metadata || typeof metadata !== 'object') return;- const payload = metadata as MaintenanceProposalBriefMetadata;- const proposal =- payload.agentSignal?.nightlySelfReview?.maintenanceProposal ??- payload.agentSignal?.nightlySelfReview?.proposal ??- payload.proposal;+ const payload = metadata as SelfReviewProposalBriefMetadata;+ const proposal = payload.agentSignal?.nightlySelfReview?.selfReviewProposal;- return isMaintenanceProposalMetadata(proposal) ? proposal : undefined;+ return isSelfReviewProposalMetadata(proposal) ? proposal : undefined;};const getProposalTarget = (- action: MaintenanceActionPlan,-): Pick<BuildMaintenanceProposalKeyInput, 'targetId' | 'targetType'> => {+ action: ActionPlan,+): Pick<BuildSelfReviewProposalKeyInput, 'targetId' | 'targetType'> => {if (action.target?.skillDocumentId) {return { targetId: action.target.skillDocumentId, targetType: 'agent_document' };}@@ -443,7 +433,7 @@ const getProposalTarget = (return { targetId: action.dedupeKey, targetType: 'unknown' };};-const getOperationTargetTitle = (action: MaintenanceActionPlan) => {+const getOperationTargetTitle = (action: ActionPlan) => {if (action.operation?.domain !== 'skill') return;const { input } = action.operation;@@ -453,8 +443,8 @@ const getOperationTargetTitle = (action: MaintenanceActionPlan) => {};const getProposalBaseSnapshot = (- action: MaintenanceProposalActionPlan,-): MaintenanceProposalBaseSnapshot | undefined => {+ action: SelfReviewProposalActionPlan,+): SelfReviewProposalBaseSnapshot | undefined => {if (isMergeableProposalAction(action.actionType)) {if (!hasCompleteMergeableSnapshot(action.actionType, action.baseSnapshot)) {throw new Error(getMergeableProposalSnapshotError(action));@@ -468,7 +458,7 @@ const getProposalBaseSnapshot = (return action.baseSnapshot ?? (targetTitle ? { targetTitle } : undefined);};-export interface BuildMaintenanceProposalFromPlanInput {+export interface BuildSelfReviewProposalFromPlanInput {/** Agent whose nightly review produced the proposal. */agentId: string;/** Evidence window end ISO timestamp. */@@ -477,14 +467,14 @@ export interface BuildMaintenanceProposalFromPlanInput {evidenceWindowStart: string;/** Stable timestamp to use for created/updated proposal metadata. */now: string;- /** Snapshot-aware maintenance plan generated before proposal projection. */- plan: MaintenanceProposalPlan;+ /** Snapshot-aware self-iteration plan generated before proposal projection. */+ plan: SelfReviewProposalPlan;/** Execution results that identify which actions stayed proposed. */- results: MaintenanceActionResult[];+ results: ActionResult[];}/**- * Builds proposal metadata from a maintenance plan and execution results.+ * Builds proposal metadata from a self-iteration plan and execution results.** Use when:* - A nightly review projected a user-visible proposal Daily Brief@@ -497,17 +487,17 @@ export interface BuildMaintenanceProposalFromPlanInput {* Returns:* - Proposal metadata for the first proposed target/action group, or `undefined`*/-export const buildMaintenanceProposalFromPlan = ({+export const buildSelfReviewProposalFromPlan = ({agentId,evidenceWindowEnd,evidenceWindowStart,now,plan,results,-}: BuildMaintenanceProposalFromPlanInput): MaintenanceProposalMetadata | undefined => {+}: BuildSelfReviewProposalFromPlanInput): SelfReviewProposalMetadata | undefined => {const proposedResultKeys = new Set(results- .filter((result) => result.status === MaintenanceActionStatus.Proposed)+ .filter((result) => result.status === ActionStatus.Proposed).map((result) => result.idempotencyKey),);const proposedActions = plan.actions.filter(@@ -521,7 +511,7 @@ export const buildMaintenanceProposalFromPlan = ({const [firstAction] = proposedActions;const target = getProposalTarget(firstAction);- const proposalKey = buildMaintenanceProposalKey({+ const proposalKey = buildSelfReviewProposalKey({actionType: firstAction.actionType,agentId,targetId: target.targetId,@@ -559,7 +549,7 @@ export const buildMaintenanceProposalFromPlan = ({proposalKey,status: 'pending',updatedAt: now,- version: MAINTENANCE_PROPOSAL_VERSION,+ version: SELF_REVIEW_PROPOSAL_VERSION,};};@@ -576,17 +566,17 @@ export const buildMaintenanceProposalFromPlan = ({* Returns:* - `{ refresh: true }` only for same-key, same-action, unexpired pending proposals*/-export const shouldRefreshMaintenanceProposal = ({+export const shouldRefreshSelfReviewProposal = ({existing,incoming,now,}: {existing: Pick<- MaintenanceProposalMetadata,+ SelfReviewProposalMetadata,'actionType' | 'expiresAt' | 'proposalKey' | 'status'> &- Partial<MaintenanceProposalMetadata>;- incoming: { actionType: MaintenanceActionType; proposalKey: string };+ Partial<SelfReviewProposalMetadata>;+ incoming: { actionType: ActionType; proposalKey: string };now: string;}) => {if (existing.status !== 'pending') return { refresh: false, reason: 'not_pending' as const };@@ -604,7 +594,7 @@ export const shouldRefreshMaintenanceProposal = ({};const getActionTargetSignature = (- action: Pick<MaintenanceProposalAction, 'operation' | 'target'>,+ action: Pick<SelfReviewProposalAction, 'operation' | 'target'>,) => {if (action.target?.skillDocumentId) return `skillDocumentId:${action.target.skillDocumentId}`;if (action.target?.memoryId) return `memoryId:${action.target.memoryId}`;@@ -619,7 +609,7 @@ const getActionTargetSignature = (return 'unknown';};-const getActionOperationSignature = (action: MaintenanceProposalAction) =>+const getActionOperationSignature = (action: SelfReviewProposalAction) =>[action.actionType,action.operation?.domain ?? 'none',@@ -641,8 +631,8 @@ const getActionOperationSignature = (action: MaintenanceProposalAction) =>* - `true` when action type, operation domain/name, and target identity are equivalent*/export const areProposalActionsCompatible = (- existing: MaintenanceProposalAction[],- incoming: MaintenanceProposalAction[],+ existing: SelfReviewProposalAction[],+ incoming: SelfReviewProposalAction[],) => {if (existing.length !== incoming.length) return false;@@ -665,14 +655,14 @@ export const areProposalActionsCompatible = (* Returns:* - `{ supersede: true }` only for same-key, unexpired pending proposals with incompatible actions*/-export const shouldSupersedeMaintenanceProposal = ({+export const shouldSupersedeSelfReviewProposal = ({existing,incoming,now,}: {- existing: Pick<MaintenanceProposalMetadata, 'actions' | 'expiresAt' | 'proposalKey' | 'status'> &- Partial<MaintenanceProposalMetadata>;- incoming: Pick<MaintenanceProposalMetadata, 'actions' | 'proposalKey'>;+ existing: Pick<SelfReviewProposalMetadata, 'actions' | 'expiresAt' | 'proposalKey' | 'status'> &+ Partial<SelfReviewProposalMetadata>;+ incoming: Pick<SelfReviewProposalMetadata, 'actions' | 'proposalKey'>;now: string;}) => {if (existing.status !== 'pending') return { supersede: false, reason: 'not_pending' as const };@@ -702,15 +692,15 @@ export const shouldSupersedeMaintenanceProposal = ({* Returns:* - Proposal metadata with refreshed actions, evidence window, and sliding expiry*/-export const refreshMaintenanceProposal = ({+export const refreshSelfReviewProposal = ({existing,incoming,now,}: {- existing: MaintenanceProposalMetadata;- incoming: MaintenanceProposalMetadata;+ existing: SelfReviewProposalMetadata;+ incoming: SelfReviewProposalMetadata;now: string;-}): MaintenanceProposalMetadata => ({+}): SelfReviewProposalMetadata => ({...existing,actions: incoming.actions,actionType: incoming.actionType,@@ -735,15 +725,15 @@ export const refreshMaintenanceProposal = ({* Returns:* - Proposal metadata with terminal `superseded` state*/-export const supersedeMaintenanceProposal = ({+export const supersedeSelfReviewProposal = ({existing,now,supersededBy,}: {- existing: MaintenanceProposalMetadata;+ existing: SelfReviewProposalMetadata;now: string;supersededBy: string;-}): MaintenanceProposalMetadata => ({+}): SelfReviewProposalMetadata => ({...existing,status: 'superseded',supersededBy,diff --git a/src/server/services/agentSignal/services/maintenance/proposalApply.ts b/src/server/services/agentSignal/services/selfIteration/review/proposalApply.tssimilarity index 79%rename from src/server/services/agentSignal/services/maintenance/proposalApply.tsrename to src/server/services/agentSignal/services/selfIteration/review/proposalApply.tsindex 08cda1f2b2f..2f9358d6640 100644--- a/src/server/services/agentSignal/services/maintenance/proposalApply.ts+++ b/src/server/services/agentSignal/services/selfIteration/review/proposalApply.ts@@ -1,26 +1,26 @@import { SpanStatusCode } from '@lobechat/observability-otel/api';import { tracer } from '@lobechat/observability-otel/modules/agent-signal';-import type { MaintenanceProposalApplyGateResult } from './brief';+import type { ToolSet, ToolWriteResult } from '../tools/shared';+import type { RunResult } from '../types';+import { ActionStatus, ReviewRunStatus } from '../types';+import type { SelfReviewProposalApplyGateResult } from './brief';import type {- MaintenanceProposalAction,- MaintenanceProposalActionApplyResult,- MaintenanceProposalApplyAttempt,- MaintenanceProposalConflictReason,- MaintenanceProposalMetadata,+ SelfReviewProposalAction,+ SelfReviewProposalActionApplyResult,+ SelfReviewProposalApplyAttempt,+ SelfReviewProposalConflictReason,+ SelfReviewProposalMetadata,} from './proposal';-import type { MaintenanceProposalPreflightResult } from './proposalPreflight';-import type { MaintenanceTools, MaintenanceToolWriteResult } from './tools';-import type { MaintenanceReviewRunResult } from './types';-import { MaintenanceActionStatus, ReviewRunStatus } from './types';+import type { SelfReviewProposalPreflightResult } from './proposalPreflight';-export interface ApplyMaintenanceProposalInput {+export interface ApplySelfReviewProposalInput {/** Agent that owns the proposal target. */agentId: string;/** User-local date when the proposal is tied to a nightly run. */localDate?: string;/** Frozen proposal metadata read from Daily Brief metadata. */- proposal: MaintenanceProposalMetadata;+ proposal: SelfReviewProposalMetadata;/** Source id used for approve-time receipts and idempotency context. */sourceId: string;/** Source type used for approve-time receipts. */@@ -31,36 +31,36 @@ export interface ApplyMaintenanceProposalInput {userId: string;}-export interface ApplyMaintenanceProposalResult {+export interface ApplySelfReviewProposalResult {/** Proposal metadata after the apply attempt has been recorded. */- proposal: MaintenanceProposalMetadata;+ proposal: SelfReviewProposalMetadata;/** Synthetic review result projected from approve-time tool outcomes. */- result: MaintenanceReviewRunResult;+ result: RunResult;}-export interface MaintenanceProposalApplyAdapters {+export interface SelfReviewProposalApplyAdapters {/** Re-checks one frozen action against current target state. */- checkAction: (action: MaintenanceProposalAction) => Promise<MaintenanceProposalPreflightResult>;+ checkAction: (action: SelfReviewProposalAction) => Promise<SelfReviewProposalPreflightResult>;/** Re-checks feature/user/agent gates immediately before mutation. */- checkGates: () => Promise<MaintenanceProposalApplyGateResult>;+ checkGates: () => Promise<SelfReviewProposalApplyGateResult>;/** Clock injected for deterministic apply-attempt metadata. */now?: () => string;- /** Safe maintenance write tools used for approve-time proposal application. */- tools: Pick<MaintenanceTools, 'createSkillIfAbsent' | 'replaceSkillContentCAS'>;+ /** Safe shared write tools used for approve-time proposal application. */+ tools: Pick<ToolSet, 'createSkillIfAbsent' | 'replaceSkillContentCAS'>;/** Persists updated proposal metadata. */- updateProposal: (proposal: MaintenanceProposalMetadata) => Promise<void>;+ updateProposal: (proposal: SelfReviewProposalMetadata) => Promise<void>;}interface PreparedToolAction {- action: MaintenanceProposalAction;- apply: () => Promise<MaintenanceToolWriteResult>;+ action: SelfReviewProposalAction;+ apply: () => Promise<ToolWriteResult>;}const toApplyResult = (- action: MaintenanceProposalAction,- status: MaintenanceProposalActionApplyResult['status'],+ action: SelfReviewProposalAction,+ status: SelfReviewProposalActionApplyResult['status'],summary: string,-): MaintenanceProposalActionApplyResult => ({+): SelfReviewProposalActionApplyResult => ({idempotencyKey: action.idempotencyKey,status,summary,@@ -74,9 +74,7 @@ const getRequiredString = (value: unknown) => {return text || undefined;};-const mapToolStatus = (- result: MaintenanceToolWriteResult,-): MaintenanceProposalActionApplyResult['status'] => {+const mapToolStatus = (result: ToolWriteResult): SelfReviewProposalActionApplyResult['status'] => {if (result.status === 'applied') return 'applied';if (result.status === 'deduped') return 'deduped';if (result.status === 'failed') return 'failed';@@ -87,8 +85,8 @@ const mapToolStatus = (};const getAttemptStatus = (- actionResults: MaintenanceProposalActionApplyResult[],-): MaintenanceProposalApplyAttempt['status'] => {+ actionResults: SelfReviewProposalActionApplyResult[],+): SelfReviewProposalApplyAttempt['status'] => {const hasApplied = actionResults.some((result) => result.status === 'applied' || result.status === 'deduped',);@@ -104,7 +102,7 @@ const getAttemptStatus = (return 'failed';};-const getProposalStatus = (status: MaintenanceProposalApplyAttempt['status']) => {+const getProposalStatus = (status: SelfReviewProposalApplyAttempt['status']) => {if (status === 'applied') return 'applied';if (status === 'partially_failed') return 'partially_failed';if (status === 'stale') return 'stale';@@ -113,27 +111,25 @@ const getProposalStatus = (status: MaintenanceProposalApplyAttempt['status']) =>};const getFirstConflictReason = (- result: MaintenanceProposalPreflightResult,-): MaintenanceProposalConflictReason | undefined => {+ result: SelfReviewProposalPreflightResult,+): SelfReviewProposalConflictReason | undefined => {if (result.allowed || result.reason === 'unsupported') return;return result.reason;};-const buildSyntheticResult = (- actionResults: MaintenanceProposalActionApplyResult[],-): MaintenanceReviewRunResult => ({+const buildSyntheticResult = (actionResults: SelfReviewProposalActionApplyResult[]): RunResult => ({actions: actionResults.map((result) => ({idempotencyKey: result.idempotencyKey,...(result.resourceId ? { resourceId: result.resourceId } : {}),status:result.status === 'failed'- ? MaintenanceActionStatus.Failed+ ? ActionStatus.Failed: result.status === 'deduped'- ? MaintenanceActionStatus.Deduped+ ? ActionStatus.Deduped: result.status === 'applied'- ? MaintenanceActionStatus.Applied- : MaintenanceActionStatus.Skipped,+ ? ActionStatus.Applied+ : ActionStatus.Skipped,...(result.summary ? { summary: result.summary } : {}),})),status: actionResults.some((result) => result.status === 'failed')@@ -143,7 +139,7 @@ const buildSyntheticResult = (: ReviewRunStatus.Skipped,});-const buildUnsupportedResult = (action: MaintenanceProposalAction) =>+const buildUnsupportedResult = (action: SelfReviewProposalAction) =>toApplyResult(action,'skipped_unsupported',@@ -151,10 +147,10 @@ const buildUnsupportedResult = (action: MaintenanceProposalAction) =>);const prepareToolAction = (- action: MaintenanceProposalAction,- input: ApplyMaintenanceProposalInput,- adapters: MaintenanceProposalApplyAdapters,-): MaintenanceProposalActionApplyResult | PreparedToolAction => {+ action: SelfReviewProposalAction,+ input: ApplySelfReviewProposalInput,+ adapters: SelfReviewProposalApplyAdapters,+): SelfReviewProposalActionApplyResult | PreparedToolAction => {if (action.actionType === 'consolidate_skill') {if (action.operation?.domain !== 'skill' ||@@ -283,7 +279,7 @@ const prepareToolAction = (};/**- * Creates the approve-time merge path for Agent Signal maintenance proposals.+ * Creates the approve-time merge path for Agent Signal self-review proposals.** Use when:* - A user approves an Agent Signal Daily Brief proposal@@ -291,17 +287,17 @@ const prepareToolAction = (** Expects:* - Callers persist proposal metadata through `updateProposal`- * - `tools` are safe maintenance write tools with their own idempotency and mutation guards+ * - `tools` are safe write tools with their own idempotency and mutation guards** Returns:* - A service that records one apply attempt and never reruns reviewer/planner*/-export const createMaintenanceProposalApplyService = (- adapters: MaintenanceProposalApplyAdapters,+export const createSelfReviewProposalApplyService = (+ adapters: SelfReviewProposalApplyAdapters,) => ({- apply: async (input: ApplyMaintenanceProposalInput): Promise<ApplyMaintenanceProposalResult> =>+ apply: async (input: ApplySelfReviewProposalInput): Promise<ApplySelfReviewProposalResult> =>tracer.startActiveSpan(- 'agent_signal.maintenance_proposal.apply',+ 'agent_signal.self_review_proposal.apply',{attributes: {'agent.signal.agent_id': input.agentId,@@ -315,9 +311,9 @@ export const createMaintenanceProposalApplyService = (try {const now = adapters.now?.() ?? new Date().toISOString();const gateResult = await adapters.checkGates();- const skippedResults: MaintenanceProposalActionApplyResult[] = [];+ const skippedResults: SelfReviewProposalActionApplyResult[] = [];const executableActions: PreparedToolAction[] = [];- let conflictReason: MaintenanceProposalConflictReason | undefined;+ let conflictReason: SelfReviewProposalConflictReason | undefined;if (!gateResult.allowed) {conflictReason = gateResult.reason;@@ -376,12 +372,12 @@ export const createMaintenanceProposalApplyService = (toApplyResult(action, 'failed', 'Proposal action was not evaluated.'),);const attemptStatus = getAttemptStatus(actionResults);- const applyAttempt: MaintenanceProposalApplyAttempt = {+ const applyAttempt: SelfReviewProposalApplyAttempt = {actionResults,appliedAt: now,status: attemptStatus,};- const proposal: MaintenanceProposalMetadata = {+ const proposal: SelfReviewProposalMetadata = {...input.proposal,applyAttempts: [...(input.proposal.applyAttempts ?? []), applyAttempt],...(conflictReason ? { conflictReason } : {}),diff --git a/src/server/services/agentSignal/services/maintenance/proposalPreflight.ts b/src/server/services/agentSignal/services/selfIteration/review/proposalPreflight.tssimilarity index 81%rename from src/server/services/agentSignal/services/maintenance/proposalPreflight.tsrename to src/server/services/agentSignal/services/selfIteration/review/proposalPreflight.tsindex 5d82bcecfa7..eb00ee1c4d5 100644--- a/src/server/services/agentSignal/services/maintenance/proposalPreflight.ts+++ b/src/server/services/agentSignal/services/selfIteration/review/proposalPreflight.ts@@ -1,13 +1,13 @@import type {- MaintenanceProposalAction,- MaintenanceProposalBaseSnapshot,- MaintenanceProposalConflictReason,+ SelfReviewProposalAction,+ SelfReviewProposalBaseSnapshot,+ SelfReviewProposalConflictReason,} from './proposal';-export type MaintenanceProposalPreflightReason = MaintenanceProposalConflictReason | 'unsupported';+export type SelfReviewProposalPreflightReason = SelfReviewProposalConflictReason | 'unsupported';/** Adapters required by proposal apply preflight. */-export interface MaintenanceProposalPreflightAdapters {+export interface SelfReviewProposalPreflightAdapters {/** Checks whether a proposed stable skill name is still absent. */isSkillNameAvailable: (input: {/** Agent namespace when the caller can provide it. */@@ -20,32 +20,32 @@ export interface MaintenanceProposalPreflightAdapters {/** Reads current managed skill target state by agent document id. */readSkillTargetSnapshot: (skillDocumentId: string,- ) => Promise<MaintenanceProposalBaseSnapshot | undefined>;+ ) => Promise<SelfReviewProposalBaseSnapshot | undefined>;}/** Successful proposal preflight result. */-export interface MaintenanceProposalPreflightAllowed {+export interface SelfReviewProposalPreflightAllowed {/** Whether the action may still be applied. */allowed: true;}/** Failed proposal preflight result with conflict reason. */-export interface MaintenanceProposalPreflightDenied {+export interface SelfReviewProposalPreflightDenied {/** Whether the action may still be applied. */allowed: false;/** Conflict reason recorded on stale or unsupported proposal actions. */- reason: MaintenanceProposalPreflightReason;+ reason: SelfReviewProposalPreflightReason;}-export type MaintenanceProposalPreflightResult =- | MaintenanceProposalPreflightAllowed- | MaintenanceProposalPreflightDenied;+export type SelfReviewProposalPreflightResult =+ | SelfReviewProposalPreflightAllowed+ | SelfReviewProposalPreflightDenied;/**- * Creates approve-time preflight checks for frozen maintenance proposal actions.+ * Creates approve-time preflight checks for frozen self-review proposal actions.** Use when:- * - A user approves a Daily Brief maintenance proposal+ * - A user approves a Daily Brief self-review proposal* - The merge path must detect stale, deleted, readonly, or retargeted skill documents first** Expects:@@ -55,12 +55,12 @@ export type MaintenanceProposalPreflightResult =* Returns:* - A service that accepts fresh create/refine skill proposals and rejects stale targets*/-export const createMaintenanceProposalPreflightService = (- adapters: MaintenanceProposalPreflightAdapters,+export const createSelfReviewProposalPreflightService = (+ adapters: SelfReviewProposalPreflightAdapters,) => ({checkAction: async (- action: MaintenanceProposalAction,- ): Promise<MaintenanceProposalPreflightResult> => {+ action: SelfReviewProposalAction,+ ): Promise<SelfReviewProposalPreflightResult> => {if (action.actionType === 'refine_skill') {return checkRefineSkillAction(action, adapters);}@@ -80,7 +80,7 @@ export const createMaintenanceProposalPreflightService = (const hasRequiredString = (value: unknown): value is string =>typeof value === 'string' && value.trim().length > 0;-const getOperationInputString = (action: MaintenanceProposalAction, key: string) => {+const getOperationInputString = (action: SelfReviewProposalAction, key: string) => {const input = action.operation?.input;if (!input || typeof input !== 'object' || !(key in input)) return;@@ -91,7 +91,7 @@ const getOperationInputString = (action: MaintenanceProposalAction, key: string)return hasRequiredString(value) ? value.trim() : undefined;};-const getOperationInputStringArray = (action: MaintenanceProposalAction, key: string) => {+const getOperationInputStringArray = (action: SelfReviewProposalAction, key: string) => {const input = action.operation?.input;if (!input || typeof input !== 'object' || !(key in input)) return [];@@ -103,7 +103,7 @@ const getOperationInputStringArray = (action: MaintenanceProposalAction, key: st: [];};-const getOperationInputSnapshots = (action: MaintenanceProposalAction, key: string) => {+const getOperationInputSnapshots = (action: SelfReviewProposalAction, key: string) => {const input = action.operation?.input;if (!input || typeof input !== 'object' || !(key in input)) return [];@@ -113,15 +113,15 @@ const getOperationInputSnapshots = (action: MaintenanceProposalAction, key: strireturn Array.isArray(value)? value.flatMap((item) =>item && typeof item === 'object' && !Array.isArray(item)- ? [item as MaintenanceProposalBaseSnapshot]+ ? [item as SelfReviewProposalBaseSnapshot]: [],): [];};const isCompleteRefineSnapshot = (- snapshot: MaintenanceProposalBaseSnapshot,-): snapshot is MaintenanceProposalBaseSnapshot & {+ snapshot: SelfReviewProposalBaseSnapshot,+): snapshot is SelfReviewProposalBaseSnapshot & {agentDocumentId: string;contentHash: string;documentId: string;@@ -134,9 +134,9 @@ const isCompleteRefineSnapshot = (snapshot.writable === true;const checkRefineSkillAction = async (- action: MaintenanceProposalAction,- adapters: MaintenanceProposalPreflightAdapters,-): Promise<MaintenanceProposalPreflightResult> => {+ action: SelfReviewProposalAction,+ adapters: SelfReviewProposalPreflightAdapters,+): Promise<SelfReviewProposalPreflightResult> => {const { baseSnapshot } = action;if (!baseSnapshot) return { allowed: false, reason: 'snapshot_missing' };if (!isCompleteRefineSnapshot(baseSnapshot)) {@@ -177,9 +177,9 @@ const checkRefineSkillAction = async (};const checkCreateSkillAction = async (- action: MaintenanceProposalAction,- adapters: MaintenanceProposalPreflightAdapters,-): Promise<MaintenanceProposalPreflightResult> => {+ action: SelfReviewProposalAction,+ adapters: SelfReviewProposalPreflightAdapters,+): Promise<SelfReviewProposalPreflightResult> => {const { baseSnapshot } = action;if (!baseSnapshot) return { allowed: false, reason: 'snapshot_missing' };if (@@ -211,9 +211,9 @@ const checkCreateSkillAction = async (};const checkSnapshotFresh = async (- baseSnapshot: MaintenanceProposalBaseSnapshot,- adapters: MaintenanceProposalPreflightAdapters,-): Promise<MaintenanceProposalPreflightResult> => {+ baseSnapshot: SelfReviewProposalBaseSnapshot,+ adapters: SelfReviewProposalPreflightAdapters,+): Promise<SelfReviewProposalPreflightResult> => {if (!isCompleteRefineSnapshot(baseSnapshot)) {return { allowed: false, reason: 'snapshot_incomplete' };}@@ -236,9 +236,9 @@ const checkSnapshotFresh = async (};const checkConsolidateSkillAction = async (- action: MaintenanceProposalAction,- adapters: MaintenanceProposalPreflightAdapters,-): Promise<MaintenanceProposalPreflightResult> => {+ action: SelfReviewProposalAction,+ adapters: SelfReviewProposalPreflightAdapters,+): Promise<SelfReviewProposalPreflightResult> => {if (action.operation?.domain !== 'skill' || action.operation.operation !== 'consolidate') {return { allowed: false, reason: 'unsupported' };}diff --git a/src/server/services/agentSignal/services/maintenance/proposalSnapshot.ts b/src/server/services/agentSignal/services/selfIteration/review/proposalSnapshot.tssimilarity index 65%rename from src/server/services/agentSignal/services/maintenance/proposalSnapshot.tsrename to src/server/services/agentSignal/services/selfIteration/review/proposalSnapshot.tsindex 462ece0a558..7ea170c293f 100644--- a/src/server/services/agentSignal/services/maintenance/proposalSnapshot.ts+++ b/src/server/services/agentSignal/services/selfIteration/review/proposalSnapshot.ts@@ -1,7 +1,7 @@-import type { MaintenanceProposalBaseSnapshot } from './proposal';+import type { SelfReviewProposalBaseSnapshot } from './proposal';/** Persistence adapters required to capture approve-time proposal target snapshots. */-export interface MaintenanceProposalSnapshotAdapters {+export interface SelfReviewProposalSnapshotAdapters {/** Checks whether a stable skill name is still available for the agent and user. */isSkillNameAvailable: (input: {/** Agent that will own the created skill. */@@ -14,11 +14,11 @@ export interface MaintenanceProposalSnapshotAdapters {/** Reads the current managed skill target snapshot by agent document id. */readSkillTargetSnapshot: (skillDocumentId: string,- ) => Promise<Omit<MaintenanceProposalBaseSnapshot, 'targetType'> | undefined>;+ ) => Promise<Omit<SelfReviewProposalBaseSnapshot, 'targetType'> | undefined>;}/** Input for capturing a complete proposal base snapshot before merge/apply. */-export interface CaptureMaintenanceProposalSnapshotInput {+export interface CaptureSelfReviewProposalSnapshotInput {/** Mergeable proposal action type to snapshot. */actionType: 'create_skill' | 'refine_skill';/** Agent that owns the target skill namespace. */@@ -29,27 +29,9 @@ export interface CaptureMaintenanceProposalSnapshotInput {userId: string;}-const getRequiredStringInput = (- input: Record<string, unknown>,- key: string,- errorMessage: string,-) => {- const value = input[key];-- if (typeof value === 'string' && value.trim().length > 0) return value.trim();-- throw new Error(errorMessage);-};--const getOptionalStringInput = (input: Record<string, unknown>, key: string) => {- const value = input[key];-- return typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined;-};-const requireCompleteRefineSkillSnapshot = (- snapshot: Omit<MaintenanceProposalBaseSnapshot, 'targetType'> | undefined,-): Omit<MaintenanceProposalBaseSnapshot, 'targetType'> => {+ snapshot: Omit<SelfReviewProposalBaseSnapshot, 'targetType'> | undefined,+): Omit<SelfReviewProposalBaseSnapshot, 'targetType'> => {if (!snapshot) throw new Error('Skill target snapshot is required');if (!snapshot.agentDocumentId) throw new Error('Skill target agentDocumentId is required');@@ -75,21 +57,21 @@ const requireCompleteRefineSkillSnapshot = (* Returns:* - A service that captures complete skill target snapshots for mergeable proposal actions*/-export const createMaintenanceProposalSnapshotService = (- adapters: MaintenanceProposalSnapshotAdapters,+export const createSelfReviewProposalSnapshotService = (+ adapters: SelfReviewProposalSnapshotAdapters,) => ({captureActionSnapshot: async ({actionType,agentId,input,userId,- }: CaptureMaintenanceProposalSnapshotInput): Promise<MaintenanceProposalBaseSnapshot> => {+ }: CaptureSelfReviewProposalSnapshotInput): Promise<SelfReviewProposalBaseSnapshot> => {if (actionType === 'refine_skill') {- const skillDocumentId = getRequiredStringInput(- input,- 'skillDocumentId',- 'skillDocumentId is required',- );+ const value = input.skillDocumentId;+ if (typeof value !== 'string' || value.trim().length === 0) {+ throw new Error('skillDocumentId is required');+ }+ const skillDocumentId = value.trim();const snapshot = requireCompleteRefineSkillSnapshot(await adapters.readSkillTargetSnapshot(skillDocumentId),);@@ -97,15 +79,21 @@ export const createMaintenanceProposalSnapshotService = (return { ...snapshot, targetType: 'skill' };}- const name = getRequiredStringInput(input, 'name', 'Skill name is required');+ const value = input.name;+ if (typeof value !== 'string' || value.trim().length === 0) {+ throw new Error('Skill name is required');+ }+ const name = value.trim();const available = await adapters.isSkillNameAvailable({ agentId, name, userId });if (!available) throw new Error('Skill name is already taken');+ const title = input.title;+return {absent: true,skillName: name,- targetTitle: getOptionalStringInput(input, 'title') ?? name,+ targetTitle: typeof title === 'string' && title.trim().length > 0 ? title.trim() : name,targetType: 'skill',};},diff --git a/src/server/services/agentSignal/services/maintenance/nightlySchedule.ts b/src/server/services/agentSignal/services/selfIteration/review/schedule.tssimilarity index 98%rename from src/server/services/agentSignal/services/maintenance/nightlySchedule.tsrename to src/server/services/agentSignal/services/selfIteration/review/schedule.tsindex e5c01b05cc9..e14c13b8b49 100644--- a/src/server/services/agentSignal/services/maintenance/nightlySchedule.ts+++ b/src/server/services/agentSignal/services/selfIteration/review/schedule.ts@@ -10,7 +10,7 @@ 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';+import { buildNightlyReviewSourceId } from '../types';dayjs.extend(utc);dayjs.extend(timezonePlugin);@@ -134,7 +134,7 @@ interface LocalNightWindow {withinWindow: boolean;}-export { buildNightlyReviewSourceId } from './types';+export { buildNightlyReviewSourceId } from '../types';const resolveTimezone = (timezone: string | null | undefined): string => {if (!timezone) return FALLBACK_TIMEZONE;@@ -178,7 +178,7 @@ const getLocalNightWindow = (now: Date, timezone: string | null | undefined): Lo* Returns:* - A scheduler service with one dispatch method*/-export const createNightlyReviewScheduleService = (+export const createSelfReviewScheduleService = (adapters: NightlyReviewScheduleAdapters,): NightlyReviewScheduleService => {return {@@ -289,7 +289,7 @@ export const createServerNightlyReviewScheduleService = (): NightlyReviewScheduleService => {const model = new AgentSignalNightlyReviewModel(db);- return createNightlyReviewScheduleService({+ return createSelfReviewScheduleService({enqueueSource: (input) =>enqueueAgentSignalSourceEvent(input, {agentId: input.payload.agentId,diff --git a/src/server/services/agentSignal/services/selfIteration/review/server.ts b/src/server/services/agentSignal/services/selfIteration/review/server.tsnew file mode 100644index 00000000000..a0c5551ebf1--- /dev/null+++ b/src/server/services/agentSignal/services/selfIteration/review/server.ts@@ -0,0 +1,1146 @@+import { DEFAULT_MINI_SYSTEM_AGENT_ITEM } from '@lobechat/const';+import { SpanStatusCode } from '@lobechat/observability-otel/api';+import { tracer } from '@lobechat/observability-otel/modules/agent-signal';++import { AgentSignalNightlyReviewModel } from '@/database/models/agentSignal/nightlyReview';+import { AgentSignalReviewContextModel } from '@/database/models/agentSignal/reviewContext';+import { BriefModel } from '@/database/models/brief';+import type { BriefItem } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';+import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';+import { AGENT_SIGNAL_DEFAULTS } from '@/server/services/agentSignal/constants';+import { isAgentSignalEnabledForUser } from '@/server/services/agentSignal/featureGate';+import { runMemoryActionAgent } from '@/server/services/agentSignal/policies/analyzeIntent/actions/userMemory';+import { redisSourceEventStore } from '@/server/services/agentSignal/store/adapters/redis/sourceEventStore';+import { SkillManagementDocumentService } from '@/server/services/skillManagement';++import { persistAgentSignalReceipts } from '../../receiptService';+import { createAgentRunner, executeSelfIteration } from '../execute';+import { projectRun } from '../projection';+import type { CreateServerSelfIterationPolicyOptions } from '../server';+import { listServerSelfReviewProposalActivity } from '../server';+import type {+ CloseSelfReviewProposalInput,+ CreateSelfReviewProposalInput,+ CreateSkillIfAbsentInput,+ OperationReservation,+ RefreshSelfReviewProposalInput,+ ReplaceSkillContentCASInput,+ SupersedeSelfReviewProposalInput,+ ToolReceiptInput,+ ToolWriteResult,+ WriteMemoryInput,+} from '../tools/shared';+import { createMemoryService, createToolSet } from '../tools/shared';+import type { EvidenceRef } from '../types';+import { Risk, Scope } from '../types';+import { createBriefSelfReviewService, createServerSelfReviewBriefWriter } from './brief';+import type {+ FeedbackActivityDigest,+ NightlyReviewManagedSkillSummary,+ NightlyReviewRelevantMemorySummary,+ NightlyReviewTopicActivityRow,+ ReceiptActivityDigest,+ ToolActivityDigest,+} from './collect';+import { createSelfReviewContextService, mapNightlyDocumentActivityRows } from './collect';+import type { CreateNightlyReviewSourceHandlerDependencies } from './handler';+import type { SelfReviewProposalAction, SelfReviewProposalMetadata } from './proposal';+import {+ getSelfReviewProposalFromBriefMetadata,+ refreshSelfReviewProposal,+ supersedeSelfReviewProposal,+} from './proposal';+import { createSelfReviewProposalPreflightService } from './proposalPreflight';+import { createSelfReviewProposalSnapshotService } from './proposalSnapshot';++const NIGHTLY_REVIEW_SOURCE_TYPE = 'agent.nightly_review.requested';+const SELF_ITERATION_OPERATION_STATE_TTL_SECONDS = AGENT_SIGNAL_DEFAULTS.receiptTtlSeconds;++interface ProposalBriefReader {+ listUnresolvedByAgentAndTrigger: (options: {+ agentId: string;+ limit?: number;+ trigger: string;+ }) => Promise<Awaited<ReturnType<BriefModel['listUnresolvedByAgentAndTrigger']>>>;+}++const selfIterationOperationScopeKey = (idempotencyKey: string) =>+ `shared-operation:${idempotencyKey}`;++const selfIterationOperationReserveKey = (idempotencyKey: string) =>+ `shared-operation-reserve:${idempotencyKey}`;++const parseStoredOperationResult = (+ payload: Record<string, string> | undefined,+): ToolWriteResult | undefined => {+ if (!payload?.result) return;++ try {+ const result = JSON.parse(payload.result) as ToolWriteResult;++ if (+ result.status === 'applied' ||+ result.status === 'deduped' ||+ result.status === 'failed' ||+ result.status === 'proposed' ||+ result.status === 'skipped_stale' ||+ result.status === 'skipped_unsupported'+ ) {+ return result;+ }+ } catch {+ return;+ }+};++const createSkippedOperationResult = (): ToolWriteResult => ({+ status: 'skipped_unsupported',+ summary:+ 'Self-iteration operation is already reserved or Redis is unavailable; skipped to avoid duplicate mutation.',+});++const reserveSelfIterationOperation = async (+ idempotencyKey: string,+): Promise<OperationReservation> => {+ const scopeKey = selfIterationOperationScopeKey(idempotencyKey);+ const existing = parseStoredOperationResult(await redisSourceEventStore.readWindow(scopeKey));++ if (existing) return { existing, reserved: false };++ // NOTICE:+ // Redis is the only available cross-worker idempotency boundary for nightly tool writes.+ // `tryDedupe` also returns false when the Redis client is unavailable, so the safe fallback is+ // to skip mutation instead of writing without a durable reservation.+ // Source/context: `src/server/services/agentSignal/store/adapters/redis/sourceEventStore.ts`.+ // Removal condition: replace with a database-backed self-iteration operation ledger.+ const reserved = await redisSourceEventStore.tryDedupe(+ selfIterationOperationReserveKey(idempotencyKey),+ SELF_ITERATION_OPERATION_STATE_TTL_SECONDS,+ );++ if (reserved) return { reserved: true };++ return {+ existing:+ parseStoredOperationResult(await redisSourceEventStore.readWindow(scopeKey)) ??+ createSkippedOperationResult(),+ reserved: false,+ };+};++const completeSelfIterationOperation = async (input: ToolReceiptInput) => {+ await redisSourceEventStore.writeWindow(+ selfIterationOperationScopeKey(input.idempotencyKey),+ {+ result: JSON.stringify({+ ...(input.receiptId ? { receiptId: input.receiptId } : {}),+ ...(input.resourceId ? { resourceId: input.resourceId } : {}),+ status: input.status,+ ...(input.summary ? { summary: input.summary } : {}),+ } satisfies ToolWriteResult),+ },+ SELF_ITERATION_OPERATION_STATE_TTL_SECONDS,+ );+};++const getToolReceiptStatus = (+ status: ToolReceiptInput['status'],+): 'applied' | 'failed' | 'proposed' | 'skipped' => {+ if (status === 'applied') return 'applied';+ if (status === 'failed') return 'failed';+ if (status === 'proposed') return 'proposed';++ return 'skipped';+};++const writeSelfReviewToolReceipt = async ({+ agentId,+ input,+ sourceId,+ userId,+}: {+ agentId: string;+ input: ToolReceiptInput;+ sourceId: string;+ userId: string;+}) => {+ await persistAgentSignalReceipts([+ {+ agentId,+ createdAt: Date.now(),+ detail: input.summary ?? `Self-review tool ${input.toolName} finished with ${input.status}.`,+ id: input.idempotencyKey,+ kind:+ input.toolName === 'createSkillIfAbsent' || input.toolName === 'replaceSkillContentCAS'+ ? 'skill'+ : 'review',+ metadata: {+ sourceType: NIGHTLY_REVIEW_SOURCE_TYPE,+ },+ sourceId,+ sourceType: NIGHTLY_REVIEW_SOURCE_TYPE,+ status: getToolReceiptStatus(input.status),+ ...(input.resourceId &&+ (input.toolName === 'createSkillIfAbsent' || input.toolName === 'replaceSkillContentCAS')+ ? {+ target: {+ id: input.resourceId,+ ...(input.summary ? { summary: input.summary } : {}),+ title: input.summary ?? input.resourceId,+ type: 'skill',+ },+ }+ : {}),+ title: input.summary ?? 'Self-review tool outcome',+ topicId: sourceId,+ userId,+ },+ ]);++ return { receiptId: input.idempotencyKey };+};++const createSkillProposalAction = (input: CreateSkillIfAbsentInput): SelfReviewProposalAction => ({+ actionType: 'create_skill',+ baseSnapshot: {+ absent: true,+ skillName: input.name,+ targetType: 'skill',+ },+ evidenceRefs: [],+ idempotencyKey: input.idempotencyKey,+ operation: {+ domain: 'skill',+ input: {+ bodyMarkdown: input.bodyMarkdown,+ description: input.description,+ name: input.name,+ title: input.title,+ userId: input.userId,+ },+ operation: 'create',+ },+ rationale: input.summary ?? `Create managed skill ${input.name}.`,+ risk: Risk.Low,+ target: { skillName: input.name },+});++const createRefineProposalAction = (+ input: ReplaceSkillContentCASInput,+): SelfReviewProposalAction => ({+ actionType: 'refine_skill',+ baseSnapshot: input.baseSnapshot,+ evidenceRefs: [],+ idempotencyKey: input.idempotencyKey,+ operation: {+ domain: 'skill',+ input: {+ bodyMarkdown: input.bodyMarkdown,+ patch: input.summary,+ skillDocumentId: input.skillDocumentId,+ userId: input.userId,+ },+ operation: 'refine',+ },+ rationale: input.summary ?? `Refine managed skill ${input.skillDocumentId}.`,+ risk: Risk.Low,+ target: { skillDocumentId: input.skillDocumentId },+});++const getRecord = (value: unknown): Record<string, unknown> =>+ value && typeof value === 'object' && !Array.isArray(value)+ ? (value as Record<string, unknown>)+ : {};++const getString = (value: unknown) =>+ typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined;++const getStringArray = (value: unknown) =>+ Array.isArray(value) ? value.flatMap((item) => (getString(item) ? [getString(item)!] : [])) : [];++const getBriefMetadataWithProposal = (+ brief: BriefItem,+ proposal: SelfReviewProposalMetadata,+): BriefItem['metadata'] => {+ const metadata = getRecord(brief.metadata);+ const agentSignal = getRecord(metadata.agentSignal);+ const nightlySelfReview = getRecord(agentSignal.nightlySelfReview);++ return {+ ...metadata,+ agentSignal: {+ ...agentSignal,+ nightlySelfReview: {+ ...nightlySelfReview,+ selfReviewProposal: proposal,+ },+ },+ };+};++const getProposalToolCallPayload = (+ toolName: string,+ input:+ | CreateSelfReviewProposalInput+ | RefreshSelfReviewProposalInput+ | SupersedeSelfReviewProposalInput,+) => ({+ apiName: toolName,+ arguments: JSON.stringify(input),+ id: `${input.idempotencyKey}:tool-call`,+ identifier: 'agent-signal-self-iteration',+ type: 'builtin' as const,+});++const collectPlanEvidenceRefs = (plan: ReturnType<typeof projectRun>['projectionPlan']) => {+ 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 getProposalActionSnapshotInput = (action: Record<string, unknown>) => {+ const operation = getRecord(action.operation);+ const operationInput = getRecord(operation.input);+ const target = getRecord(action.target);++ return {+ ...operationInput,+ name: getString(operationInput.name) ?? getString(target.skillName),+ skillDocumentId: getString(operationInput.skillDocumentId) ?? getString(target.skillDocumentId),+ title: getString(operationInput.title) ?? getString(target.skillName),+ };+};++const withCompleteProposalSnapshots = async ({+ agentId,+ input,+ snapshotService,+ userId,+}: {+ agentId: string;+ input: CreateSelfReviewProposalInput;+ snapshotService: ReturnType<typeof createSelfReviewProposalSnapshotService>;+ userId: string;+}): Promise<CreateSelfReviewProposalInput> => {+ if (!input.actions || input.actions.length === 0) {+ throw new Error('Self-review proposal requires at least one action.');+ }++ const actions = await Promise.all(+ input.actions.map(async (rawAction) => {+ const action = getRecord(rawAction);+ const actionType = action.actionType;++ if (actionType === 'consolidate_skill') {+ const operation = getRecord(action.operation);+ const operationInput = getRecord(operation.input);+ const canonicalSkillDocumentId = getString(operationInput.canonicalSkillDocumentId);+ const sourceSkillIds = getStringArray(operationInput.sourceSkillIds);+ const sourceSnapshots = await Promise.all(+ sourceSkillIds.map((skillDocumentId) =>+ snapshotService.captureActionSnapshot({+ actionType: 'refine_skill',+ agentId,+ input: { skillDocumentId },+ userId,+ }),+ ),+ );++ return {+ ...action,+ ...(canonicalSkillDocumentId+ ? {+ baseSnapshot: await snapshotService.captureActionSnapshot({+ actionType: 'refine_skill',+ agentId,+ input: { skillDocumentId: canonicalSkillDocumentId },+ userId,+ }),+ }+ : {}),+ operation: {+ ...operation,+ input: {+ ...operationInput,+ sourceSnapshots,+ },+ },+ };+ }++ if (actionType !== 'create_skill' && actionType !== 'refine_skill') return rawAction;++ return {+ ...action,+ baseSnapshot: await snapshotService.captureActionSnapshot({+ actionType,+ agentId,+ input: getProposalActionSnapshotInput(action),+ userId,+ }),+ };+ }),+ );++ return { ...input, actions };+};++const isCompleteRefineToolSnapshot = (+ snapshot: ReplaceSkillContentCASInput['baseSnapshot'],+): snapshot is NonNullable<ReplaceSkillContentCASInput['baseSnapshot']> & {+ agentDocumentId: string;+ contentHash: string;+ documentId: string;+} =>+ snapshot?.targetType === 'skill' &&+ typeof snapshot.agentDocumentId === 'string' &&+ snapshot.agentDocumentId.trim().length > 0 &&+ typeof snapshot.contentHash === 'string' &&+ snapshot.contentHash.trim().length > 0 &&+ typeof snapshot.documentId === 'string' &&+ snapshot.documentId.trim().length > 0 &&+ snapshot.managed === true &&+ snapshot.writable === true;++const withCompleteReplaceSkillSnapshot = async ({+ agentId,+ input,+ snapshotService,+ userId,+}: {+ agentId: string;+ input: ReplaceSkillContentCASInput;+ snapshotService: ReturnType<typeof createSelfReviewProposalSnapshotService>;+ userId: string;+}): Promise<ReplaceSkillContentCASInput> => {+ if (isCompleteRefineToolSnapshot(input.baseSnapshot)) return input;++ const baseSnapshot = await snapshotService.captureActionSnapshot({+ actionType: 'refine_skill',+ agentId,+ input: {+ skillDocumentId: input.skillDocumentId,+ },+ userId,+ });++ return {+ ...input,+ baseSnapshot,+ // NOTICE:+ // `replaceSkillContentCAS` can be called with either the managed skill bundle id or its+ // SKILL.md index agent document id. Snapshot capture resolves both to the bundle id, and+ // approve-time preflight compares the action target against that resolved bundle id.+ // Without normalizing here, a valid index-targeted write is reported as target drift+ // (`target_type_changed`) even though it points to the same managed skill.+ // Removal condition: remove only if preflight natively accepts equivalent bundle/index ids.+ skillDocumentId: baseSnapshot.agentDocumentId ?? input.skillDocumentId,+ };+};++const createProposalProjectionFromToolInput = ({+ input,+ localDate,+ sourceId,+ toolName,+ userId,+}: {+ input: CreateSelfReviewProposalInput;+ localDate: string;+ sourceId: string;+ toolName: 'createSelfReviewProposal';+ userId: string;+}) =>+ projectRun({+ content: input.summary,+ includeProposalLifecycleActions: true,+ localDate,+ outcomes: [+ {+ receiptId: input.idempotencyKey,+ status: 'proposed',+ summary: input.summary,+ toolName,+ },+ ],+ reviewScope: Scope.Nightly,+ sourceId,+ toolCalls: [getProposalToolCallPayload(toolName, input)],+ userId,+ });++const findSelfReviewProposalBrief = async ({+ agentId,+ briefModel,+ proposalId,+ proposalKey,+}: {+ agentId: string;+ briefModel: ProposalBriefReader;+ proposalId?: string;+ proposalKey?: string;+}) => {+ const rows = await briefModel.listUnresolvedByAgentAndTrigger({+ agentId,+ limit: 20,+ trigger: 'agent-signal:nightly-review',+ });++ return rows.find((row) => {+ if (proposalId && row.id === proposalId) return true;++ const proposal = getSelfReviewProposalFromBriefMetadata(row.metadata);++ return proposalKey ? proposal?.proposalKey === proposalKey : false;+ });+};++const updateSelfReviewProposalBrief = async ({+ agentId,+ briefModel,+ proposalId,+ proposalKey,+ updateProposal,+}: {+ agentId: string;+ briefModel: BriefModel;+ proposalId?: string;+ proposalKey?: string;+ updateProposal: (proposal: SelfReviewProposalMetadata) => SelfReviewProposalMetadata;+}) => {+ const brief = await findSelfReviewProposalBrief({+ agentId,+ briefModel,+ proposalId,+ proposalKey,+ });++ if (!brief) throw new Error('Self-review proposal not found');++ const existingProposal = getSelfReviewProposalFromBriefMetadata(brief.metadata);+ if (!existingProposal) throw new Error('Self-review proposal metadata not found');++ const updatedProposal = updateProposal(existingProposal);+ const updatedBrief = await briefModel.updateMetadata(+ brief.id,+ getBriefMetadataWithProposal(brief, updatedProposal),+ );++ return {+ resourceId: updatedBrief?.id ?? brief.id,+ summary: `Updated self-review proposal ${updatedProposal.proposalKey}.`,+ };+};++export const createServerToolSet = ({+ agentId,+ briefModel,+ context,+ db,+ localDate,+ proposalBriefWriter,+ skillDocumentService,+ sourceId,+ userId,+}: {+ agentId: string;+ briefModel: BriefModel;+ context: Parameters<+ CreateNightlyReviewSourceHandlerDependencies['runSelfReviewAgent']+ >[0]['context'];+ db: LobeChatDatabase;+ localDate: string;+ proposalBriefWriter: ReturnType<typeof createServerSelfReviewBriefWriter>;+ skillDocumentService: SkillManagementDocumentService;+ sourceId: string;+ userId: string;+}) => {+ const proposalPreflight = createSelfReviewProposalPreflightService({+ isSkillNameAvailable: async ({ agentId: targetAgentId, name }) => {+ const skills = await skillDocumentService.listSkills({ agentId: targetAgentId ?? agentId });++ return !skills.some((skill) => skill.name === name);+ },+ readSkillTargetSnapshot: (skillDocumentId) =>+ skillDocumentService.readSkillTargetSnapshot({+ agentDocumentId: skillDocumentId,+ agentId,+ }),+ });+ const proposalSnapshot = createSelfReviewProposalSnapshotService({+ isSkillNameAvailable: async ({ agentId: targetAgentId, name }) => {+ const skills = await skillDocumentService.listSkills({ agentId: targetAgentId ?? agentId });++ return !skills.some((skill) => skill.name === name);+ },+ readSkillTargetSnapshot: (skillDocumentId) =>+ skillDocumentService.readSkillTargetSnapshot({+ agentDocumentId: skillDocumentId,+ agentId,+ }),+ });++ return createToolSet({+ closeProposal: async (input: CloseSelfReviewProposalInput) =>+ updateSelfReviewProposalBrief({+ agentId,+ briefModel,+ proposalId: input.proposalId,+ proposalKey: input.proposalKey,+ updateProposal: (proposal) => ({+ ...proposal,+ status: 'dismissed',+ updatedAt: new Date().toISOString(),+ }),+ }),+ completeOperation: completeSelfIterationOperation,+ completeReplaceSkillInput: (input) =>+ withCompleteReplaceSkillSnapshot({+ agentId,+ input,+ snapshotService: proposalSnapshot,+ userId,+ }),+ createProposal: async (input) => {+ const projectionInput = await withCompleteProposalSnapshots({+ agentId,+ input,+ snapshotService: proposalSnapshot,+ userId,+ });+ const projection = createProposalProjectionFromToolInput({+ input: projectionInput,+ localDate,+ sourceId,+ toolName: 'createSelfReviewProposal',+ userId,+ });+ const brief = createBriefSelfReviewService().projectNightlyReviewBrief({+ agentId,+ evidenceRefs: collectPlanEvidenceRefs(projection.projectionPlan),+ ideas: projection.ideas,+ localDate,+ plan: projection.projectionPlan,+ result: projection.execution,+ reviewWindowEnd: context.reviewWindowEnd,+ reviewWindowStart: context.reviewWindowStart,+ timezone: 'UTC',+ userId,+ });++ if (!brief) throw new Error('Self-review proposal projection produced no brief');++ const result = await proposalBriefWriter.writeDailyBrief(brief);++ return {+ proposalId: result?.id,+ resourceId: result?.id,+ summary: input.summary ?? 'Created self-review proposal.',+ };+ },+ createSkill: async (input) => {+ const preflight = await proposalPreflight.checkAction(createSkillProposalAction(input));+ if (!preflight.allowed) {+ throw new Error(`Skill creation preflight failed: ${preflight.reason}`);+ }++ const result = await skillDocumentService.createSkill({+ agentId,+ bodyMarkdown: input.bodyMarkdown,+ description: input.description ?? 'Agent Signal managed skill.',+ name: input.name,+ title: input.title ?? input.name,+ });++ return {+ resourceId: result.bundle.agentDocumentId,+ summary: `Created managed skill ${result.name}.`,+ };+ },+ writeMemory: async (input: WriteMemoryInput) => {+ // TODO: Harden the real writeMemory E2E path. Local QStash verification showed this+ // tool reaches the memory action agent, but the agent does not always converge to an+ // applied receipt/brief. Keep this marker until the memory auto-apply case has a+ // deterministic eval plus a passing end-to-end run.+ const memoryService = createMemoryService({+ writeMemory: async ({ content, evidenceRefs, idempotencyKey }) => {+ const result = await runMemoryActionAgent(+ {+ agentId,+ message: content,+ reason: `Agent Signal self-review memory candidate from ${evidenceRefs.length} evidence refs.`,+ },+ {+ db,+ 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,+ };+ },+ });+ const result = await memoryService.writeMemory({+ evidenceRefs: input.evidenceRefs,+ idempotencyKey: input.idempotencyKey,+ input: {+ content: input.content,+ userId: input.userId,+ },+ });++ return {+ resourceId: result.memoryId,+ summary: result.summary,+ };+ },+ getEvidenceDigest: async ({ evidenceIds }) => {+ const selectedEvidenceIds = new Set(evidenceIds ?? []);+ const includeAll = selectedEvidenceIds.size === 0;+ const hasSelectedEvidence = (refs: { id: string }[] | undefined) =>+ refs?.some((ref) => selectedEvidenceIds.has(ref.id)) ?? false;++ return {+ documentActivity: context.documentActivity,+ selfReviewSignals: includeAll+ ? context.selfReviewSignals+ : context.selfReviewSignals.filter((signal) => hasSelectedEvidence(signal.evidenceRefs)),+ managedSkills: context.managedSkills,+ proposalActivity: context.proposalActivity,+ receiptActivity: context.receiptActivity,+ toolActivity: context.toolActivity,+ topics: includeAll+ ? context.topics+ : context.topics.filter(+ (topic) =>+ hasSelectedEvidence(topic.evidenceRefs) ||+ topic.failedMessages?.some((message) =>+ selectedEvidenceIds.has(message.messageId),+ ) ||+ topic.failedToolCalls?.some(+ (toolCall) =>+ selectedEvidenceIds.has(toolCall.messageId) ||+ (toolCall.toolCallId && selectedEvidenceIds.has(toolCall.toolCallId)),+ ),+ ),+ };+ },+ getManagedSkill: ({ agentId: targetAgentId, skillDocumentId }) =>+ skillDocumentService.getSkill({+ agentDocumentId: skillDocumentId,+ agentId: targetAgentId,+ includeContent: true,+ }),+ listSelfReviewProposals: ({ agentId: targetAgentId }) =>+ listServerSelfReviewProposalActivity({+ agentId: targetAgentId,+ briefModel,+ userId,+ }).then((digest) => [digest]),+ listManagedSkills: ({ agentId: targetAgentId }) =>+ skillDocumentService.listSkills({ agentId: targetAgentId }),+ preflight: async (input) => {+ if ('skillDocumentId' in input) {+ const result = await proposalPreflight.checkAction(createRefineProposalAction(input));++ return result.allowed ? { allowed: true } : { allowed: false, reason: result.reason };+ }++ return { allowed: true };+ },+ readProposal: async ({ proposalId, proposalKey }) => {+ const digest = await listServerSelfReviewProposalActivity({+ agentId,+ briefModel,+ userId,+ });++ return digest.active.find(+ (proposal) =>+ (proposalId && proposal.proposalId === proposalId) ||+ (proposalKey && proposal.proposalKey === proposalKey),+ );+ },+ refreshProposal: async (input: RefreshSelfReviewProposalInput) =>+ updateSelfReviewProposalBrief({+ agentId,+ briefModel,+ proposalId: input.proposalId,+ proposalKey: input.proposalKey,+ updateProposal: (proposal) =>+ refreshSelfReviewProposal({+ existing: proposal,+ incoming: proposal,+ now: new Date().toISOString(),+ }),+ }),+ replaceSkill: async (input) => {+ const result = await skillDocumentService.replaceSkillIndex({+ agentDocumentId: input.skillDocumentId,+ agentId,+ bodyMarkdown: input.bodyMarkdown,+ description: input.description,+ });++ if (!result) throw new Error('Skill target not found');++ return {+ resourceId: result.bundle.agentDocumentId,+ summary: `Refined managed skill ${result.name}.`,+ };+ },+ reserveOperation: reserveSelfIterationOperation,+ supersedeProposal: async (input: SupersedeSelfReviewProposalInput) =>+ updateSelfReviewProposalBrief({+ agentId,+ briefModel,+ proposalId: input.proposalId,+ proposalKey: input.proposalKey,+ updateProposal: (proposal) =>+ supersedeSelfReviewProposal({+ existing: proposal,+ now: new Date().toISOString(),+ supersededBy: input.supersededBy,+ }),+ }),+ writeReceipt: (input) => writeSelfReviewToolReceipt({ agentId, input, sourceId, userId }),+ });+};++/**+ * Creates server runtime handlers for periodic self-review sources.+ *+ * Call stack:+ *+ * runAgentSignalWorkflow+ * -> {@link createServerSelfReviewPolicyOptions}+ * -> review source handler dependencies+ * -> tool-first self-review executor+ *+ * Use when:+ * - The Agent Signal workflow consumes `agent.nightly_review.requested`+ * - Runtime policy composition needs collection, review, receipts, and Daily 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 createServerSelfReviewPolicyOptions = ({+ agentId,+ db,+ selfIterationEnabled = false,+ userId,+}: CreateServerSelfIterationPolicyOptions): CreateNightlyReviewSourceHandlerDependencies => {+ const nightlyReviewModel = new AgentSignalNightlyReviewModel(db);+ const reviewContextModel = new AgentSignalReviewContextModel(db, userId);+ const briefModel = new BriefModel(db, userId);+ const skillDocumentService = new SkillManagementDocumentService(db, userId);+ const collector = createSelfReviewContextService({+ listDocumentActivity: async ({ agentId: targetAgentId, reviewWindowEnd, reviewWindowStart }) =>+ tracer.startActiveSpan(+ 'agent_signal.nightly_review.collector.list_document_activity',+ {+ attributes: {+ 'agent.signal.agent_id': targetAgentId,+ 'agent.signal.user_id': userId,+ },+ },+ async (span) => {+ try {+ const rows = await reviewContextModel.listDocumentActivity({+ agentId: targetAgentId,+ windowEnd: new Date(reviewWindowEnd),+ windowStart: new Date(reviewWindowStart),+ });+ const digest = mapNightlyDocumentActivityRows(rows);++ span.setAttribute('agent.signal.nightly.document_activity_row_count', rows.length);+ span.setAttribute(+ 'agent.signal.nightly.document_skill_event_count',+ digest.skillBucket.length,+ );+ span.setStatus({ code: SpanStatusCode.OK });++ return digest;+ } catch (error) {+ span.setStatus({+ code: SpanStatusCode.ERROR,+ message:+ error instanceof Error+ ? error.message+ : 'AgentSignal nightly document activity read failed',+ });+ span.recordException(error as Error);++ throw error;+ } finally {+ span.end();+ }+ },+ ),+ listFeedbackActivity: async ({ agentId: targetAgentId }) =>+ tracer.startActiveSpan(+ 'agent_signal.nightly_review.collector.list_feedback_activity',+ {+ attributes: {+ 'agent.signal.agent_id': targetAgentId,+ 'agent.signal.user_id': userId,+ },+ },+ async (span): Promise<FeedbackActivityDigest> => {+ try {+ const digest: FeedbackActivityDigest = {+ neutralCount: 0,+ notSatisfied: [],+ satisfied: [],+ };++ span.setAttribute('agent.signal.nightly.feedback_satisfied_count', 0);+ span.setAttribute('agent.signal.nightly.feedback_not_satisfied_count', 0);+ span.setStatus({ code: SpanStatusCode.OK });++ return digest;+ } finally {+ span.end();+ }+ },+ ),+ 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,+ }));+ },+ listProposalActivity: ({ agentId: targetAgentId }) =>+ listServerSelfReviewProposalActivity({+ agentId: targetAgentId,+ briefModel,+ userId,+ }),+ 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(),+ }));+ },+ listReceiptActivity: async ({ agentId: targetAgentId }) =>+ tracer.startActiveSpan(+ 'agent_signal.nightly_review.collector.list_receipt_activity',+ {+ attributes: {+ 'agent.signal.agent_id': targetAgentId,+ 'agent.signal.user_id': userId,+ },+ },+ async (span): Promise<ReceiptActivityDigest> => {+ try {+ const digest: ReceiptActivityDigest = {+ appliedCount: 0,+ duplicateGroups: [],+ failedCount: 0,+ pendingProposalCount: 0,+ recentReceipts: [],+ reviewCount: 0,+ };++ span.setAttribute('agent.signal.nightly.receipt_pending_proposal_count', 0);+ span.setAttribute('agent.signal.nightly.receipt_recent_count', 0);+ span.setStatus({ code: SpanStatusCode.OK });++ return digest;+ } finally {+ span.end();+ }+ },+ ),+ listToolActivity: async ({ agentId: targetAgentId, reviewWindowEnd, reviewWindowStart }) =>+ tracer.startActiveSpan(+ 'agent_signal.nightly_review.collector.list_tool_activity',+ {+ attributes: {+ 'agent.signal.agent_id': targetAgentId,+ 'agent.signal.user_id': userId,+ },+ },+ async (span) => {+ try {+ const rows = await reviewContextModel.listToolActivity({+ agentId: targetAgentId,+ windowEnd: new Date(reviewWindowEnd),+ windowStart: new Date(reviewWindowStart),+ });+ const digest = rows.map<ToolActivityDigest>((row) => ({+ apiName: row.apiName,+ failedCount: row.failedCount,+ firstUsedAt: row.firstUsedAt?.toISOString(),+ identifier: row.identifier,+ lastUsedAt: row.lastUsedAt?.toISOString(),+ messageIds: row.messageIds.slice(0, 10),+ sampleArgs: row.sampleArgs.slice(0, 3),+ sampleErrors: row.sampleErrors.slice(0, 3),+ topicIds: row.topicIds.slice(0, 10),+ totalCount: row.totalCount,+ }));++ span.setAttribute('agent.signal.nightly.tool_activity_count', digest.length);+ span.setStatus({ code: SpanStatusCode.OK });++ return digest;+ } catch (error) {+ span.setStatus({+ code: SpanStatusCode.ERROR,+ message:+ error instanceof Error+ ? error.message+ : 'AgentSignal nightly tool activity read failed',+ });+ span.recordException(error as Error);++ throw error;+ } finally {+ span.end();+ }+ },+ ),+ 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) => ({+ correctionCount: row.correctionCount,+ correctionIds: row.correctionIds,+ evidenceRefs: row.topicId ? [{ id: row.topicId, type: 'topic' }] : [],+ failedMessages: row.failedMessages,+ failedToolCount: row.failedToolCount,+ failedToolCalls: row.failedToolCalls,+ failureCount: row.failureCount,+ lastActivityAt: row.lastActivityAt.toISOString(),+ messageCount: row.messageCount,+ summary: row.summary,+ title: row.title ?? undefined,+ topicId: row.topicId ?? undefined,+ }));+ },+ });+ const briefWriter = createServerSelfReviewBriefWriter(db, 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.collect(input),+ runSelfReviewAgent: async ({ context, localDate, sourceId, userId: runnerUserId }) => {+ const modelRuntime = await initModelRuntimeFromDB(+ db,+ runnerUserId,+ DEFAULT_MINI_SYSTEM_AGENT_ITEM.provider,+ );+ const toolSet = createServerToolSet({+ agentId: context.agentId,+ briefModel,+ context,+ db,+ localDate: localDate ?? context.reviewWindowEnd.slice(0, 10),+ proposalBriefWriter: briefWriter,+ skillDocumentService,+ sourceId,+ userId: runnerUserId,+ });+ const selfReviewAgentRunner = createAgentRunner({+ maxSteps: 10,+ run: async ({ context, localDate, maxSteps, reviewScope, sourceId, tools, userId }) => {+ const runtimeResult = await executeSelfIteration({+ agentId: context.agentId,+ context,+ maxSteps,+ model: DEFAULT_MINI_SYSTEM_AGENT_ITEM.model,+ modelRuntime,+ sourceId,+ tools,+ userId,+ });+ const projected = projectRun({+ content: runtimeResult.content,+ localDate,+ outcomes: runtimeResult.writeOutcomes.map((outcome) => ({+ ...outcome.result,+ toolName: outcome.toolName,+ })),+ reviewScope,+ sourceId,+ toolCalls: runtimeResult.toolCalls,+ userId,+ });++ return {+ ...projected,+ stepCount: runtimeResult.stepCount,+ };+ },+ tools: toolSet,+ });++ return selfReviewAgentRunner.run({+ context,+ localDate,+ sourceId,+ userId: runnerUserId,+ });+ },+ writeDailyBrief: (brief) => briefWriter.writeDailyBrief(brief),+ writeReceipts: (receipts) => persistAgentSignalReceipts(receipts),+ };+};diff --git a/src/server/services/agentSignal/services/maintenance/nightlySignals.ts b/src/server/services/agentSignal/services/selfIteration/review/signals.tssimilarity index 91%rename from src/server/services/agentSignal/services/maintenance/nightlySignals.tsrename to src/server/services/agentSignal/services/selfIteration/review/signals.tsindex b5eb1cb2025..67d7565c604 100644--- a/src/server/services/agentSignal/services/maintenance/nightlySignals.ts+++ b/src/server/services/agentSignal/services/selfIteration/review/signals.ts@@ -1,14 +1,14 @@+import type { EvidenceRef } from '../types';import type {DocumentActivityDigest,FeedbackActivityDigest,- MaintenanceSignal,NightlyReviewTopicDigest,ReceiptActivityDigest,+ SelfReviewSignal,ToolActivityDigest,-} from './nightlyCollector';-import type { EvidenceRef } from './types';+} from './collect';-interface DeriveNightlyMaintenanceSignalsInput {+interface DeriveSelfReviewSignalsInput {documentActivity: DocumentActivityDigest;feedbackActivity: FeedbackActivityDigest;receiptActivity: ReceiptActivityDigest;@@ -31,22 +31,22 @@ const createFeedbackFeatures = (feedbackActivity: FeedbackActivityDigest) =>}));/**- * Derives conservative nightly maintenance signals from bounded context buckets.+ * Derives conservative nightly self-review signals from bounded context buckets.** Use when:* - The nightly reviewer needs a small entry-point list before inspecting buckets- * - Tests need deterministic maintenance signal behavior without DB or LLM calls+ * - Tests need deterministic shared signal behavior without DB or LLM calls** Expects:* - Input buckets are already bounded, redacted, and review-window scoped** Returns:- * - Ordered maintenance signals where weak single-source evidence never authorizes mutation+ * - Ordered self-review signals where weak single-source evidence never authorizes mutation*/-export const deriveNightlyMaintenanceSignals = (- input: DeriveNightlyMaintenanceSignalsInput,-): MaintenanceSignal[] => {- const signals: MaintenanceSignal[] = [];+export const deriveSelfReviewSignals = (+ input: DeriveSelfReviewSignalsInput,+): SelfReviewSignal[] => {+ const signals: SelfReviewSignal[] = [];const feedbackFeatures = createFeedbackFeatures(input.feedbackActivity);for (const tool of input.toolActivity) {diff --git a/src/server/services/agentSignal/services/selfIteration/server.ts b/src/server/services/agentSignal/services/selfIteration/server.tsnew file mode 100644index 00000000000..5fa4ca4b3f9--- /dev/null+++ b/src/server/services/agentSignal/services/selfIteration/server.ts@@ -0,0 +1,234 @@+import { SpanStatusCode } from '@lobechat/observability-otel/api';+import { tracer } from '@lobechat/observability-otel/modules/agent-signal';++import type { AgentSignalReviewContextModel } from '@/database/models/agentSignal/reviewContext';+import type { BriefModel } from '@/database/models/brief';+import type { LobeChatDatabase } from '@/database/type';++import { NIGHTLY_REVIEW_BRIEF_TRIGGER } from './review/brief';+import type { ProposalActivityDigest } from './review/collect';+import { getSelfReviewProposalFromBriefMetadata } from './review/proposal';+import type { EvidenceRef } from './types';++/** Bounded unresolved Daily Brief read budget for proposal activity digesting. */+const NIGHTLY_PROPOSAL_ACTIVITY_LIMIT = 20;++const ACTIVE_PROPOSAL_STATUSES = new Set(['accepted', 'applying', 'pending']);++interface ProposalBriefReader {+ listUnresolvedByAgentAndTrigger: (options: {+ agentId: string;+ limit?: number;+ trigger: string;+ }) => Promise<Awaited<ReturnType<BriefModel['listUnresolvedByAgentAndTrigger']>>>;+}++/**+ * Options for composing server self-iteration policy handlers.+ */+export interface CreateServerSelfIterationPolicyOptions {+ /** 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;+}++/**+ * Checks whether a server self-iteration source may run for the current workflow scope.+ *+ * Use when:+ * - Review, reflection, and intent server adapters need the same feature and ownership gate+ * - Workflow payload `agentId` must constrain source-owned agent ids+ *+ * Expects:+ * - `selfIterationEnabled` was computed for the same user before policy execution+ * - `reviewContextModel` is scoped to the current user+ *+ * Returns:+ * - `true` only when feature gate, workflow agent scope, and agent-level DB gate all pass+ */+export const canRunSelfIterationSource = 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 getProposalTargetDigest = (+ proposal: NonNullable<ReturnType<typeof getSelfReviewProposalFromBriefMetadata>>,+): Pick<ProposalActivityDigest['active'][number], 'targetId' | 'targetTitle'> => {+ const action = proposal.actions[0];+ const target = action?.target;++ return {+ ...(target?.skillDocumentId+ ? { targetId: target.skillDocumentId }+ : target?.memoryId+ ? { targetId: target.memoryId }+ : target?.skillName+ ? { targetId: target.skillName }+ : {}),+ ...(action?.baseSnapshot?.targetTitle ? { targetTitle: action.baseSnapshot.targetTitle } : {}),+ };+};++const getProposalEvidenceCount = (+ proposal: NonNullable<ReturnType<typeof getSelfReviewProposalFromBriefMetadata>>,+) => {+ const evidenceRefs = new Map<string, EvidenceRef>();++ for (const evidenceRef of proposal.evidenceRefs ?? []) {+ evidenceRefs.set(`${evidenceRef.type}:${evidenceRef.id}`, evidenceRef);+ }++ for (const action of proposal.actions) {+ for (const evidenceRef of action.evidenceRefs) {+ evidenceRefs.set(`${evidenceRef.type}:${evidenceRef.id}`, evidenceRef);+ }+ }++ return evidenceRefs.size;+};++const hasPendingProposalExpired = ({ expiresAt, now }: { expiresAt: string; now: string }) => {+ const expiresAtMs = new Date(expiresAt).getTime();+ const nowMs = new Date(now).getTime();++ return Number.isFinite(expiresAtMs) && Number.isFinite(nowMs) && expiresAtMs <= nowMs;+};++const isNoopProposal = (+ proposal: NonNullable<ReturnType<typeof getSelfReviewProposalFromBriefMetadata>>,+) =>+ proposal.actionType === 'noop' ||+ proposal.actions.every((action) => action.actionType === 'noop');++/**+ * Lists existing server-side self-review proposal activity for one agent.+ *+ * Use when:+ * - Nightly self-review context needs unresolved proposal state+ * - Tests need the server adapter behavior without booting the full runtime+ *+ * Expects:+ * - `briefModel` applies user, agent, trigger, and unresolved filters before the limit+ * - `now` is an ISO timestamp used to treat expired pending proposals as inactive+ * - Stored metadata may be malformed and must be treated as absent+ *+ * Returns:+ * - Active unresolved proposal digests plus unresolved status counts+ */+export const listServerSelfReviewProposalActivity = async ({+ agentId,+ briefModel,+ now = new Date().toISOString(),+ userId,+}: {+ agentId: string;+ briefModel: ProposalBriefReader;+ now?: string;+ userId: string;+}): Promise<ProposalActivityDigest> =>+ tracer.startActiveSpan(+ 'agent_signal.nightly_review.collector.list_proposal_activity',+ {+ attributes: {+ 'agent.signal.agent_id': agentId,+ 'agent.signal.nightly.proposal_read_limit': NIGHTLY_PROPOSAL_ACTIVITY_LIMIT,+ 'agent.signal.user_id': userId,+ },+ },+ async (span) => {+ try {+ const rows = await briefModel.listUnresolvedByAgentAndTrigger({+ agentId,+ limit: NIGHTLY_PROPOSAL_ACTIVITY_LIMIT,+ trigger: NIGHTLY_REVIEW_BRIEF_TRIGGER,+ });+ const digest: ProposalActivityDigest = {+ active: [],+ dismissedCount: 0,+ expiredCount: 0,+ staleCount: 0,+ supersededCount: 0,+ };+ let validProposalCount = 0;++ for (const brief of rows) {+ if (brief.agentId !== agentId) continue;+ if (brief.trigger !== NIGHTLY_REVIEW_BRIEF_TRIGGER) continue;++ const proposal = getSelfReviewProposalFromBriefMetadata(brief.metadata);+ if (!proposal) continue;+ if (isNoopProposal(proposal)) continue;++ validProposalCount += 1;++ if (proposal.status === 'dismissed') digest.dismissedCount += 1;+ if (proposal.status === 'expired') digest.expiredCount += 1;+ if (proposal.status === 'stale') digest.staleCount += 1;+ if (proposal.status === 'superseded') digest.supersededCount += 1;++ if (+ proposal.status === 'pending' &&+ hasPendingProposalExpired({ expiresAt: proposal.expiresAt, now })+ ) {+ digest.expiredCount += 1;+ continue;+ }++ if (!ACTIVE_PROPOSAL_STATUSES.has(proposal.status)) continue;++ digest.active.push({+ actionType: proposal.actionType,+ createdAt: proposal.createdAt,+ evidenceCount: getProposalEvidenceCount(proposal),+ expiresAt: proposal.expiresAt,+ proposalId: brief.id,+ proposalKey: proposal.proposalKey,+ status: proposal.status,+ summary: brief.summary,+ ...getProposalTargetDigest(proposal),+ updatedAt: proposal.updatedAt,+ });+ }++ span.setAttribute('agent.signal.nightly.proposal_unresolved_row_count', rows.length);+ span.setAttribute('agent.signal.nightly.proposal_valid_count', validProposalCount);+ span.setAttribute('agent.signal.nightly.proposal_active_count', digest.active.length);+ span.setAttribute('agent.signal.nightly.proposal_dismissed_count', digest.dismissedCount);+ span.setAttribute('agent.signal.nightly.proposal_expired_count', digest.expiredCount);+ span.setAttribute('agent.signal.nightly.proposal_stale_count', digest.staleCount);+ span.setAttribute('agent.signal.nightly.proposal_superseded_count', digest.supersededCount);+ span.setStatus({ code: SpanStatusCode.OK });++ return digest;+ } catch (error) {+ span.setStatus({+ code: SpanStatusCode.ERROR,+ message:+ error instanceof Error+ ? error.message+ : 'AgentSignal nightly proposal activity read failed',+ });+ span.recordException(error as Error);++ throw error;+ } finally {+ span.end();+ }+ },+ );diff --git a/src/server/services/agentSignal/services/selfIteration/tools/__test__/reflection.test.ts b/src/server/services/agentSignal/services/selfIteration/tools/__test__/reflection.test.tsnew file mode 100644index 00000000000..205d614eaac--- /dev/null+++ b/src/server/services/agentSignal/services/selfIteration/tools/__test__/reflection.test.ts@@ -0,0 +1,116 @@+import { describe, expect, it, vi } from 'vitest';++import { getReflectionDisposition, ReflectionTools } from '../reflection';++describe('ReflectionTools', () => {+ /**+ * @example+ * getReflectionDisposition({ actionType: 'write_memory', confidence: 0.8 });+ * returns direct_apply only when every memory safety predicate passes.+ */+ it('direct-applies only supported high-confidence reflection candidates', () => {+ expect(+ getReflectionDisposition({+ actionType: 'write_memory',+ concreteFutureUse: true,+ confidence: 0.75,+ evidenceStrength: 'medium',+ usableMemoryContent: true,+ }),+ ).toBe('direct_apply');++ expect(+ getReflectionDisposition({+ actionType: 'write_memory',+ concreteFutureUse: true,+ confidence: 0.74,+ evidenceStrength: 'medium',+ usableMemoryContent: true,+ }),+ ).toBe('record_intent');++ expect(+ getReflectionDisposition({+ actionType: 'write_memory',+ concreteFutureUse: true,+ confidence: 0.95,+ evidenceStrength: 'strong',+ sensitive: true,+ usableMemoryContent: true,+ }),+ ).toBe('record_intent');++ expect(+ getReflectionDisposition({+ actionType: 'refine_skill',+ confidence: 0.9,+ evidenceStrength: 'strong',+ inPlacePatch: true,+ smallMutationScope: true,+ targetSkillDocumentId: 'skill-1',+ }),+ ).toBe('direct_apply');++ expect(+ getReflectionDisposition({+ actionType: 'consolidate_skill',+ confidence: 1,+ evidenceStrength: 'strong',+ }),+ ).toBe('record_intent');+ });++ /**+ * @example+ * await tools.recordReflectionIdea(idea);+ * expect(result.status).toBe('applied');+ */+ it('records reflection ideas through receipt-backed adapters', async () => {+ const recordReflectionIdea = vi.fn().mockResolvedValue({+ resourceId: 'idea-1',+ status: 'applied',+ });+ const tools = new ReflectionTools({ recordReflectionIdea });++ await expect(+ tools.recordReflectionIdea({+ evidenceRefs: [{ id: 'msg-1', type: 'message' }],+ idempotencyKey: 'idea-1',+ rationale: 'The agent noticed a local failure pattern.',+ risk: 'low',+ }),+ ).resolves.toEqual({ resourceId: 'idea-1', status: 'applied' });++ expect(recordReflectionIdea).toHaveBeenCalledOnce();+ });++ /**+ * @example+ * await tools.recordSelfFeedbackIntent(intent);+ * expect(result.status).toBe('applied');+ */+ it('records downgraded self-feedback intents without review proposal tools', async () => {+ const recordSelfFeedbackIntent = vi.fn().mockResolvedValue({+ resourceId: 'intent-1',+ status: 'applied',+ });+ const tools = new ReflectionTools({ recordSelfFeedbackIntent });++ await expect(+ tools.recordSelfFeedbackIntent({+ confidence: 0.62,+ downgradeReason: 'low_confidence',+ evidenceRefs: [{ id: 'tool-1', type: 'tool_call' }],+ idempotencyKey: 'intent-1',+ intentType: 'workflow',+ mode: 'reflection',+ rationale: 'The agent should revisit this pattern during self-review.',+ risk: 'medium',+ urgency: 'soon',+ }),+ ).resolves.toEqual({ resourceId: 'intent-1', status: 'applied' });++ expect(recordSelfFeedbackIntent).toHaveBeenCalledOnce();+ expect('createSelfReviewProposal' in tools).toBe(false);+ });+});diff --git a/src/server/services/agentSignal/services/selfIteration/tools/__test__/review.test.ts b/src/server/services/agentSignal/services/selfIteration/tools/__test__/review.test.tsnew file mode 100644index 00000000000..cc7235aa50e--- /dev/null+++ b/src/server/services/agentSignal/services/selfIteration/tools/__test__/review.test.ts@@ -0,0 +1,70 @@+import { describe, expect, it, vi } from 'vitest';++import { ReviewTools } from '../review';+import { createToolSet, ToolSetFacade } from '../shared';++const createToolSetFacade = () =>+ new ToolSetFacade({+ closeProposal: vi.fn().mockResolvedValue({ resourceId: 'proposal-1' }),+ createProposal: vi.fn().mockResolvedValue({ proposalId: 'proposal-1' }),+ preflight: vi.fn().mockResolvedValue({ allowed: true }),+ refreshProposal: vi.fn().mockResolvedValue({ resourceId: 'proposal-1' }),+ reserveOperation: vi.fn().mockResolvedValue({ reserved: true }),+ supersedeProposal: vi.fn().mockResolvedValue({ resourceId: 'proposal-1' }),+ writeReceipt: vi.fn().mockResolvedValue({ receiptId: 'receipt-1' }),+ });++describe('ReviewTools', () => {+ /**+ * @example+ * await tools.createSelfReviewProposal({ proposalKey: 'review:1' });+ * expect(result.status).toBe('proposed');+ */+ it('uses self-review names for proposal lifecycle operations', async () => {+ const tools = new ReviewTools(createToolSetFacade());++ await expect(+ tools.createSelfReviewProposal({+ idempotencyKey: 'op-proposal-1',+ proposalKey: 'review:proposal:1',+ userId: 'user-1',+ }),+ ).resolves.toEqual({+ receiptId: 'receipt-1',+ resourceId: 'proposal-1',+ status: 'proposed',+ });+ });++ /**+ * @example+ * await tools.recordSelfReviewIdea(idea);+ * expect(result.status).toBe('applied');+ */+ it('records self-review ideas through the review adapter', async () => {+ const recordSelfReviewIdea = vi.fn().mockResolvedValue({+ resourceId: 'idea-1',+ status: 'applied',+ });+ const tools = new ReviewTools(createToolSetFacade(), { recordSelfReviewIdea });++ await expect(+ tools.recordSelfReviewIdea({+ evidenceRefs: [{ id: 'msg-1', type: 'message' }],+ idempotencyKey: 'idea-1',+ rationale: 'Keep this for later review.',+ risk: 'low',+ }),+ ).resolves.toEqual({ resourceId: 'idea-1', status: 'applied' });++ expect(recordSelfReviewIdea).toHaveBeenCalledOnce();+ });++ /**+ * @example+ * expect(createToolSet).toBeTypeOf('function');+ */+ it('exports the shared factory used by concrete review tools', () => {+ expect(createToolSet).toBeTypeOf('function');+ });+});diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/tools.test.ts b/src/server/services/agentSignal/services/selfIteration/tools/__test__/shared.test.tssimilarity index 73%rename from src/server/services/agentSignal/services/maintenance/__tests__/tools.test.tsrename to src/server/services/agentSignal/services/selfIteration/tools/__test__/shared.test.tsindex 830807827af..d318bfb93de 100644--- a/src/server/services/agentSignal/services/maintenance/__tests__/tools.test.ts+++ b/src/server/services/agentSignal/services/selfIteration/tools/__test__/shared.test.ts@@ -1,7 +1,7 @@import { SpanStatusCode } from '@lobechat/observability-otel/api';import { beforeEach, describe, expect, it, vi } from 'vitest';-import type { MaintenanceProposalBaseSnapshot } from '../proposal';+import type { SelfReviewProposalBaseSnapshot } from '../../review/proposal';const { spanEnd, spanRecordException, spanSetAttribute, spanSetStatus, startActiveSpan } =vi.hoisted(() => {@@ -41,9 +41,9 @@ const refineSkillBaseSnapshot = {managed: true,targetType: 'skill',writable: true,-} satisfies MaintenanceProposalBaseSnapshot;+} satisfies SelfReviewProposalBaseSnapshot;-describe('createMaintenanceTools', () => {+describe('createToolSet', () => {beforeEach(() => {vi.clearAllMocks();});@@ -54,10 +54,10 @@ describe('createMaintenanceTools', () => {* expect(result.status).toBe('skipped_stale');*/it('replaceSkillContentCAS returns skipped_stale without writing when preflight fails', async () => {- const { createMaintenanceTools } = await import('../tools');+ const { createToolSet } = await import('../shared');const replaceSkill = vi.fn();const writeReceipt = vi.fn().mockResolvedValue({ receiptId: 'receipt-stale' });- const tools = createMaintenanceTools({+ const tools = createToolSet({preflight: vi.fn().mockResolvedValue({ allowed: false, reason: 'Document changed.' }),replaceSkill,reserveOperation: vi.fn().mockResolvedValue({ reserved: true }),@@ -97,11 +97,11 @@ describe('createMaintenanceTools', () => {* returns the existing receipt without calling preflight or replaceSkill.*/it('replaceSkillContentCAS dedupes existing reserved idempotency keys', async () => {- const { createMaintenanceTools } = await import('../tools');+ const { createToolSet } = await import('../shared');const preflight = vi.fn();const replaceSkill = vi.fn();const writeReceipt = vi.fn().mockResolvedValue({ receiptId: 'receipt-deduped' });- const tools = createMaintenanceTools({+ const tools = createToolSet({preflight,replaceSkill,reserveOperation: vi.fn().mockResolvedValue({@@ -143,23 +143,23 @@ describe('createMaintenanceTools', () => {/*** @example- * await tools.createMaintenanceProposal({ proposalKey: 'p1' });+ * await tools.createSelfReviewProposal({ proposalKey: 'p1' });* expect(result.status).toBe('proposed');*/- it('createMaintenanceProposal returns proposed and writes a receipt', async () => {- const { createMaintenanceTools } = await import('../tools');+ it('createSelfReviewProposal returns proposed and writes a receipt', async () => {+ const { createToolSet } = await import('../shared');const createProposal = vi.fn().mockResolvedValue({proposalId: 'proposal-1',summary: 'Proposal created.',});const writeReceipt = vi.fn().mockResolvedValue({ receiptId: 'receipt-proposed' });- const tools = createMaintenanceTools({+ const tools = createToolSet({createProposal,reserveOperation: vi.fn().mockResolvedValue({ reserved: true }),writeReceipt,});- const result = await tools.createMaintenanceProposal({+ const result = await tools.createSelfReviewProposal({idempotencyKey: 'op-proposal-1',proposalKey: 'proposal-skill-1',summary: 'Create proposal.',@@ -186,17 +186,17 @@ describe('createMaintenanceTools', () => {}),);expect(startActiveSpan).toHaveBeenCalledWith(- 'agent_signal.maintenance_tool.write',+ 'agent_signal.self_iteration_tool.write',expect.objectContaining({attributes: expect.objectContaining({- 'agent.signal.maintenance_tool.name': 'createMaintenanceProposal',+ 'agent.signal.self_iteration_tool.name': 'createSelfReviewProposal','agent.signal.proposal.key': 'proposal-skill-1',}),}),expect.any(Function),);expect(spanSetAttribute).toHaveBeenCalledWith(- 'agent.signal.maintenance_tool.write_status',+ 'agent.signal.self_iteration_tool.write_status','proposed',);expect(spanEnd).toHaveBeenCalled();@@ -208,10 +208,10 @@ describe('createMaintenanceTools', () => {* expect(result.status).toBe('failed');*/it('createSkillIfAbsent returns failed and writes a failed receipt when mutation throws', async () => {- const { createMaintenanceTools } = await import('../tools');+ const { createToolSet } = await import('../shared');const error = new Error('Skill write failed.');const writeReceipt = vi.fn().mockResolvedValue({ receiptId: 'receipt-failed' });- const tools = createMaintenanceTools({+ const tools = createToolSet({createSkill: vi.fn().mockRejectedValue(error),reserveOperation: vi.fn().mockResolvedValue({ reserved: true }),writeReceipt,@@ -243,14 +243,14 @@ describe('createMaintenanceTools', () => {/*** @example- * await tools.createMaintenanceProposal({ idempotencyKey: 'op-receipt-fails' });+ * await tools.createSelfReviewProposal({ idempotencyKey: 'op-receipt-fails' });* rejects when the terminal receipt cannot be written.*/- it('createMaintenanceProposal propagates receipt failures and records the write span exception', async () => {- const { createMaintenanceTools } = await import('../tools');+ it('createSelfReviewProposal propagates receipt failures and records the write span exception', async () => {+ const { createToolSet } = await import('../shared');const error = new Error('Receipt write failed.');const markOperationFailed = vi.fn().mockResolvedValue(undefined);- const tools = createMaintenanceTools({+ const tools = createToolSet({createProposal: vi.fn().mockResolvedValue({proposalId: 'proposal-1',summary: 'Proposal created.',@@ -261,7 +261,7 @@ describe('createMaintenanceTools', () => {});await expect(- tools.createMaintenanceProposal({+ tools.createSelfReviewProposal({idempotencyKey: 'op-receipt-fails-1',proposalKey: 'proposal-skill-1',userId: 'user-1',@@ -276,7 +276,7 @@ describe('createMaintenanceTools', () => {proposalKey: 'proposal-skill-1',resourceId: 'proposal-1',status: 'proposed',- toolName: 'createMaintenanceProposal',+ toolName: 'createSelfReviewProposal',userId: 'user-1',}),);@@ -293,9 +293,9 @@ describe('createMaintenanceTools', () => {* returns the known skill id when the adapter only returns a summary.*/it('replaceSkillContentCAS keeps the known resource id when replacement omits it', async () => {- const { createMaintenanceTools } = await import('../tools');+ const { createToolSet } = await import('../shared');const writeReceipt = vi.fn().mockResolvedValue({ receiptId: 'receipt-replace' });- const tools = createMaintenanceTools({+ const tools = createToolSet({preflight: vi.fn().mockResolvedValue({ allowed: true }),replaceSkill: vi.fn().mockResolvedValue({ summary: 'Skill replaced.' }),reserveOperation: vi.fn().mockResolvedValue({ reserved: true }),@@ -331,12 +331,12 @@ describe('createMaintenanceTools', () => {* skips unsupported refine payloads before calling replaceSkill.*/it('rejects patch-only refine payload before mutation with skipped_unsupported and receipt', async () => {- const { createMaintenanceTools } = await import('../tools');+ const { createToolSet } = await import('../shared');const preflight = vi.fn().mockResolvedValue({ allowed: true });const replaceSkill = vi.fn();const reserveOperation = vi.fn().mockResolvedValue({ reserved: true });const writeReceipt = vi.fn().mockResolvedValue({ receiptId: 'receipt-invalid-refine' });- const tools = createMaintenanceTools({+ const tools = createToolSet({preflight,replaceSkill,reserveOperation,@@ -375,10 +375,10 @@ describe('createMaintenanceTools', () => {* skips unsupported refine payloads without a complete base snapshot.*/it('rejects missing baseSnapshot refine payload before mutation with skipped_unsupported and receipt', async () => {- const { createMaintenanceTools } = await import('../tools');+ const { createToolSet } = await import('../shared');const preflight = vi.fn().mockResolvedValue({ allowed: true });const replaceSkill = vi.fn();- const tools = createMaintenanceTools({+ const tools = createToolSet({preflight,replaceSkill,reserveOperation: vi.fn().mockResolvedValue({ reserved: true }),@@ -409,10 +409,10 @@ describe('createMaintenanceTools', () => {* skips unsupported refine payloads with incomplete snapshots.*/it('rejects incomplete baseSnapshot refine payload before mutation with skipped_unsupported and receipt', async () => {- const { createMaintenanceTools } = await import('../tools');+ const { createToolSet } = await import('../shared');const preflight = vi.fn().mockResolvedValue({ allowed: true });const replaceSkill = vi.fn();- const tools = createMaintenanceTools({+ const tools = createToolSet({preflight,replaceSkill,reserveOperation: vi.fn().mockResolvedValue({ reserved: true }),@@ -450,10 +450,10 @@ describe('createMaintenanceTools', () => {* skips unsupported create payloads before calling createSkill.*/it('rejects missing or blank create body and name before mutation with skipped_unsupported and receipt', async () => {- const { createMaintenanceTools } = await import('../tools');+ const { createToolSet } = await import('../shared');const createSkill = vi.fn();const writeReceipt = vi.fn().mockResolvedValue({ receiptId: 'receipt-invalid-create' });- const tools = createMaintenanceTools({+ const tools = createToolSet({createSkill,reserveOperation: vi.fn().mockResolvedValue({ reserved: true }),writeReceipt,@@ -496,10 +496,10 @@ describe('createMaintenanceTools', () => {* returns a deduped receipt without calling createSkill.*/it('keeps dedupe behavior for valid writes', async () => {- const { createMaintenanceTools } = await import('../tools');+ const { createToolSet } = await import('../shared');const createSkill = vi.fn();const writeReceipt = vi.fn().mockResolvedValue({ receiptId: 'receipt-deduped-create' });- const tools = createMaintenanceTools({+ const tools = createToolSet({createSkill,reserveOperation: vi.fn().mockResolvedValue({existing: {@@ -530,19 +530,19 @@ describe('createMaintenanceTools', () => {/*** @example- * await tools.closeMaintenanceProposal({ proposalId: 'proposal-1' });+ * await tools.closeSelfReviewProposal({ proposalId: 'proposal-1' });* expect(result.status).toBe('skipped_unsupported');*/- it('closeMaintenanceProposal skips unsupported when preflight is missing and does not mutate', async () => {- const { createMaintenanceTools } = await import('../tools');+ it('closeSelfReviewProposal skips unsupported when preflight is missing and does not mutate', async () => {+ const { createToolSet } = await import('../shared');const closeProposal = vi.fn();- const tools = createMaintenanceTools({+ const tools = createToolSet({closeProposal,reserveOperation: vi.fn().mockResolvedValue({ reserved: true }),writeReceipt: vi.fn().mockResolvedValue({ receiptId: 'receipt-unsupported' }),});- const result = await tools.closeMaintenanceProposal({+ const result = await tools.closeSelfReviewProposal({idempotencyKey: 'op-close-1',proposalId: 'proposal-1',userId: 'user-1',@@ -553,26 +553,26 @@ describe('createMaintenanceTools', () => {receiptId: 'receipt-unsupported',resourceId: 'proposal-1',status: 'skipped_unsupported',- summary: 'Maintenance preflight is not supported.',+ summary: 'Tool preflight is not supported.',});});/*** @example- * await tools.readMaintenanceProposal({ proposalId: 'proposal-1' });+ * await tools.readSelfReviewProposal({ proposalId: 'proposal-1' });* rejects and records the read exception on the span.*/- it('readMaintenanceProposal propagates errors and ends the span with exception details', async () => {- const { createMaintenanceTools } = await import('../tools');+ it('readSelfReviewProposal propagates errors and ends the span with exception details', async () => {+ const { createToolSet } = await import('../shared');const error = new Error('Read failed.');- const tools = createMaintenanceTools({+ const tools = createToolSet({readProposal: vi.fn().mockRejectedValue(error),reserveOperation: vi.fn().mockResolvedValue({ reserved: true }),writeReceipt: vi.fn(),});await expect(- tools.readMaintenanceProposal({+ tools.readSelfReviewProposal({proposalId: 'proposal-1',proposalKey: 'proposal-key-1',userId: 'user-1',@@ -593,15 +593,15 @@ describe('createMaintenanceTools', () => {* returns adapter data and safe unsupported fallbacks for read tools.*/it('read tools call injected adapters and return undefined or empty arrays when unsupported', async () => {- const { createMaintenanceTools } = await import('../tools');+ const { createToolSet } = await import('../shared');const listManagedSkills = vi.fn().mockResolvedValue([{ name: 'skill-a' }]);const getManagedSkill = vi.fn().mockResolvedValue({ name: 'skill-a' });- const listMaintenanceProposals = vi.fn().mockResolvedValue([{ proposalId: 'proposal-1' }]);+ const listSelfReviewProposals = vi.fn().mockResolvedValue([{ proposalId: 'proposal-1' }]);const getEvidenceDigest = vi.fn().mockResolvedValue({ evidenceCount: 1 });- const tools = createMaintenanceTools({+ const tools = createToolSet({getEvidenceDigest,getManagedSkill,- listMaintenanceProposals,+ listSelfReviewProposals,listManagedSkills,reserveOperation: vi.fn().mockResolvedValue({ reserved: true }),writeReceipt: vi.fn(),@@ -618,7 +618,7 @@ describe('createMaintenanceTools', () => {}),).resolves.toEqual({ name: 'skill-a' });await expect(- tools.listMaintenanceProposals({ agentId: 'agent-1', userId: 'user-1' }),+ tools.listSelfReviewProposals({ agentId: 'agent-1', userId: 'user-1' }),).resolves.toEqual([{ proposalId: 'proposal-1' }]);await expect(tools.getEvidenceDigest({@@ -636,7 +636,7 @@ describe('createMaintenanceTools', () => {skillDocumentId: 'skill-1',userId: 'user-1',});- expect(listMaintenanceProposals).toHaveBeenCalledWith({+ expect(listSelfReviewProposals).toHaveBeenCalledWith({agentId: 'agent-1',userId: 'user-1',});@@ -648,16 +648,16 @@ describe('createMaintenanceTools', () => {userId: 'user-1',});expect(startActiveSpan).toHaveBeenCalledWith(- 'agent_signal.maintenance_tool.read',+ 'agent_signal.self_iteration_tool.read',expect.objectContaining({attributes: expect.objectContaining({- 'agent.signal.maintenance_tool.name': 'listManagedSkills',+ 'agent.signal.self_iteration_tool.name': 'listManagedSkills',}),}),expect.any(Function),);- const unsupportedTools = createMaintenanceTools({+ const unsupportedTools = createToolSet({reserveOperation: vi.fn().mockResolvedValue({ reserved: true }),writeReceipt: vi.fn(),});@@ -673,7 +673,7 @@ describe('createMaintenanceTools', () => {}),).resolves.toBeUndefined();await expect(- unsupportedTools.listMaintenanceProposals({ agentId: 'agent-1', userId: 'user-1' }),+ unsupportedTools.listSelfReviewProposals({ agentId: 'agent-1', userId: 'user-1' }),).resolves.toEqual([]);await expect(unsupportedTools.getEvidenceDigest({ agentId: 'agent-1', userId: 'user-1' }),@@ -682,11 +682,11 @@ describe('createMaintenanceTools', () => {/*** @example- * await tools.refreshMaintenanceProposal({ proposalId: 'proposal-1' });+ * await tools.refreshSelfReviewProposal({ proposalId: 'proposal-1' });* expect(result.status).toBe('proposed');*/- it('refreshMaintenanceProposal returns proposed and writes a receipt', async () => {- const { createMaintenanceTools } = await import('../tools');+ it('refreshSelfReviewProposal returns proposed and writes a receipt', async () => {+ const { createToolSet } = await import('../shared');const preflight = vi.fn().mockResolvedValue({ allowed: true });const refreshProposal = vi.fn().mockResolvedValue({resourceId: 'proposal-1',@@ -694,14 +694,14 @@ describe('createMaintenanceTools', () => {});const reserveOperation = vi.fn().mockResolvedValue({ reserved: true });const writeReceipt = vi.fn().mockResolvedValue({ receiptId: 'receipt-refresh' });- const tools = createMaintenanceTools({+ const tools = createToolSet({preflight,refreshProposal,reserveOperation,writeReceipt,});- const result = await tools.refreshMaintenanceProposal({+ const result = await tools.refreshSelfReviewProposal({idempotencyKey: 'op-refresh-1',proposalId: 'proposal-1',userId: 'user-1',@@ -727,3 +727,128 @@ describe('createMaintenanceTools', () => {);});});++describe('memory and skill services', () => {+ /**+ * @example+ * Explicit stable preference is passed to the existing memory write adapter.+ */+ it('writes explicit stable memory through the injected adapter', async () => {+ const { createMemoryService } = await import('../shared');+ const writeMemory = vi+ .fn()+ .mockResolvedValue({ memoryId: 'mem-1', summary: 'Saved preference.' });+ const service = createMemoryService({ 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 { createMemoryService } = await import('../shared');+ const writeMemory = vi.fn();+ const service = createMemoryService({ 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();+ });++ /**+ * @example+ * Writable managed skill documents may be refined automatically.+ */+ it('refines writable managed skills through the injected adapter', async () => {+ const { createSkillManagementService } = await import('../shared');+ 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: {+ bodyMarkdown:+ '# Release notes\n\n- 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+ * Patch descriptions are not accepted as complete executable skill replacement bodies.+ */+ it('rejects patch-only skill refinements before persistence', async () => {+ const { createSkillManagementService } = await import('../shared');+ const refineSkill = vi.fn();+ const service = createSkillManagementService({ refineSkill });++ await expect(+ service.refineSkill({+ evidenceRefs: [{ id: 'msg-1', type: 'message' }],+ idempotencyKey: 'source:refine_skill:skill:doc-1',+ input: {+ patch: 'Add a checklist step.',+ skillDocumentId: 'doc-1',+ userId: 'user-1',+ },+ }),+ ).rejects.toThrow('Skill refinement requires a complete replacement bodyMarkdown');++ expect(refineSkill).not.toHaveBeenCalled();+ });++ /**+ * @example+ * Readonly builtin or marketplace skills are not mutated by this service.+ */+ it('rejects readonly skill targets before persistence', async () => {+ const { createSkillManagementService } = await import('../shared');+ 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: {+ bodyMarkdown: '# Builtin skill\n\nChange 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/selfIteration/tools/index.ts b/src/server/services/agentSignal/services/selfIteration/tools/index.tsnew file mode 100644index 00000000000..a76429d1df7--- /dev/null+++ b/src/server/services/agentSignal/services/selfIteration/tools/index.ts@@ -0,0 +1,3 @@+export * from './reflection';+export * from './review';+export * from './shared';diff --git a/src/server/services/agentSignal/services/selfIteration/tools/reflection.ts b/src/server/services/agentSignal/services/selfIteration/tools/reflection.tsnew file mode 100644index 00000000000..afa2fb6ad14--- /dev/null+++ b/src/server/services/agentSignal/services/selfIteration/tools/reflection.ts@@ -0,0 +1,155 @@+import type { Idea, SelfFeedbackIntent } from '../types';+import type { ToolWriteResult } from './shared';++/** Reflection action class considered by the direct-apply policy. */+export type ReflectionActionType =+ | 'consolidate_skill'+ | 'create_skill'+ | 'noop'+ | 'proposal_only'+ | 'refine_skill'+ | 'write_memory';++/** Evidence strength used by reflection direct-apply policy. */+export type ReflectionEvidenceStrength = 'medium' | 'strong' | 'weak';++/** Reflection direct-apply policy result. */+export type ReflectionDisposition = 'direct_apply' | 'record_intent';++/** Candidate inspected by the reflection direct-apply policy. */+export interface ReflectionPolicyCandidate {+ /** Action class inferred from self-feedback. */+ actionType: ReflectionActionType;+ /** True when the payload is approval-gated or structural. */+ approvalRequired?: boolean;+ /** True when a memory is concrete and useful for future turns. */+ concreteFutureUse?: boolean;+ /** Confidence normalized from 0 to 1. */+ confidence: number;+ /** True when the candidate contradicts available context. */+ contradictory?: boolean;+ /** Evidence strength after source handling. */+ evidenceStrength: ReflectionEvidenceStrength;+ /** True when a refine_skill candidate is an in-place patch, not a broad rewrite. */+ inPlacePatch?: boolean;+ /** True when the candidate is only useful for the current turn. */+ localToCurrentTurn?: boolean;+ /** True when the content is sensitive. */+ sensitive?: boolean;+ /** True when a skill mutation is small and bounded. */+ smallMutationScope?: boolean;+ /** True when the content is speculative. */+ speculative?: boolean;+ /** True when the target is readonly. */+ targetReadonly?: boolean;+ /** Existing skill document id for refine_skill. */+ targetSkillDocumentId?: string;+ /** True when usable memory content exists. */+ usableMemoryContent?: boolean;+}++/**+ * Computes whether reflection may direct-apply a candidate or must record an intent.+ *+ * | Action | Direct-apply rule |+ * | --- | --- |+ * | `write_memory` | confidence >= 0.75, evidence medium/strong, normal sensitivity, concrete future-use content |+ * | `refine_skill` | confidence >= 0.9, strong evidence, existing writable skill target, small in-place mutation |+ * | `create_skill` / `consolidate_skill` / broad or approval-gated actions | record intent |+ *+ * Use when:+ * - Same-turn self-feedback needs a deterministic gate before mutating memory or skill resources+ * - Tests need to verify threshold math without running the model runtime+ *+ * Expects:+ * - Confidence has already been normalized to 0..1+ * - Target flags come from trusted source-handler or resource preflight context+ *+ * Returns:+ * - `direct_apply` only for low-risk supported actions+ * - `record_intent` for approval-gated, structural, unsupported, or low-confidence candidates+ */+export const getReflectionDisposition = (+ candidate: ReflectionPolicyCandidate,+): ReflectionDisposition => {+ if (candidate.approvalRequired) return 'record_intent';++ if (candidate.actionType === 'write_memory') {+ const evidenceIsUsable =+ candidate.evidenceStrength === 'medium' || candidate.evidenceStrength === 'strong';+ const unsafeMemory =+ candidate.sensitive ||+ candidate.speculative ||+ candidate.contradictory ||+ candidate.localToCurrentTurn;++ return candidate.confidence >= 0.75 &&+ evidenceIsUsable &&+ candidate.concreteFutureUse === true &&+ candidate.usableMemoryContent === true &&+ !unsafeMemory+ ? 'direct_apply'+ : 'record_intent';+ }++ if (candidate.actionType === 'refine_skill') {+ return candidate.confidence >= 0.9 &&+ candidate.evidenceStrength === 'strong' &&+ candidate.smallMutationScope === true &&+ candidate.inPlacePatch === true &&+ Boolean(candidate.targetSkillDocumentId) &&+ candidate.targetReadonly !== true+ ? 'direct_apply'+ : 'record_intent';+ }++ return 'record_intent';+};++/** Adapter surface for reflection-only receipt writes. */+export interface ReflectionToolsAdapters {+ /** Records a reflection idea into receipt metadata. */+ recordReflectionIdea?: (idea: Idea) => Promise<ToolWriteResult>;+ /** Records a downgraded self-feedback intent into receipt metadata. */+ recordSelfFeedbackIntent?: (intent: SelfFeedbackIntent) => Promise<ToolWriteResult>;+}++/**+ * Reflection-mode tool facade for immediate agent feedback output.+ *+ * Use when:+ * - Same-turn self-feedback needs to preserve ideas and intents in receipts+ * - Reflection must avoid review proposal lifecycle writes+ *+ * Expects:+ * - The caller already decided whether an action direct-applies or downgrades to an intent+ * - Reflection output persists through receipt metadata, not Daily Brief artifacts+ *+ * Returns:+ * - A class surface for receipt-backed reflection ideas and self-feedback intents+ */+export class ReflectionTools {+ constructor(private readonly adapters: ReflectionToolsAdapters = {}) {}++ async recordReflectionIdea(idea: Idea): Promise<ToolWriteResult> {+ if (!this.adapters.recordReflectionIdea) {+ return {+ status: 'skipped_unsupported',+ summary: 'Reflection idea recording is not supported.',+ };+ }++ return this.adapters.recordReflectionIdea(idea);+ }++ async recordSelfFeedbackIntent(intent: SelfFeedbackIntent): Promise<ToolWriteResult> {+ if (!this.adapters.recordSelfFeedbackIntent) {+ return {+ status: 'skipped_unsupported',+ summary: 'Self-iteration intent recording is not supported.',+ };+ }++ return this.adapters.recordSelfFeedbackIntent(intent);+ }+}diff --git a/src/server/services/agentSignal/services/selfIteration/tools/review.ts b/src/server/services/agentSignal/services/selfIteration/tools/review.tsnew file mode 100644index 00000000000..ff81d767d1d--- /dev/null+++ b/src/server/services/agentSignal/services/selfIteration/tools/review.ts@@ -0,0 +1,63 @@+import type { Idea } from '../types';+import type {+ CloseSelfReviewProposalInput,+ CreateSelfReviewProposalInput,+ RefreshSelfReviewProposalInput,+ SupersedeSelfReviewProposalInput,+ ToolSetFacade,+ ToolWriteResult,+} from './shared';++/** Adapter surface for review-only artifact writes. */+export interface ReviewToolsAdapters {+ /** Records a non-executable idea into the review output sink. */+ recordSelfReviewIdea?: (idea: Idea) => Promise<ToolWriteResult>;+}++/**+ * Review-mode tool facade for Daily Brief self-review output.+ *+ * Use when:+ * - Nightly self-review needs proposal lifecycle tools plus shared resource tools+ * - Review artifacts must stay separate from reflection receipts+ *+ * Expects:+ * - Shared tools are already scoped to the reviewed user and agent+ * - Proposal lifecycle writes are intentionally review-mode output+ *+ * Returns:+ * - A class surface with self-review naming for proposal and idea operations+ */+export class ReviewTools {+ constructor(+ private readonly shared: ToolSetFacade,+ private readonly adapters: ReviewToolsAdapters = {},+ ) {}++ createSelfReviewProposal(input: CreateSelfReviewProposalInput) {+ return this.shared.createSelfReviewProposal(input);+ }++ refreshSelfReviewProposal(input: RefreshSelfReviewProposalInput) {+ return this.shared.refreshSelfReviewProposal(input);+ }++ supersedeSelfReviewProposal(input: SupersedeSelfReviewProposalInput) {+ return this.shared.supersedeSelfReviewProposal(input);+ }++ closeSelfReviewProposal(input: CloseSelfReviewProposalInput) {+ return this.shared.closeSelfReviewProposal(input);+ }++ async recordSelfReviewIdea(idea: Idea): Promise<ToolWriteResult> {+ if (!this.adapters.recordSelfReviewIdea) {+ return {+ status: 'skipped_unsupported',+ summary: 'Self-review idea recording is not supported.',+ };+ }++ return this.adapters.recordSelfReviewIdea(idea);+ }+}diff --git a/src/server/services/agentSignal/services/selfIteration/tools/shared.ts b/src/server/services/agentSignal/services/selfIteration/tools/shared.tsnew file mode 100644index 00000000000..6473bd8c8d4--- /dev/null+++ b/src/server/services/agentSignal/services/selfIteration/tools/shared.ts@@ -0,0 +1,1072 @@+import { SpanStatusCode } from '@lobechat/observability-otel/api';+import { tracer } from '@lobechat/observability-otel/modules/agent-signal';++import type { SelfReviewProposalBaseSnapshot } from '../review/proposal';+import type { EvidenceRef } from '../types';++// TODO: Replace keyword regexp checks with a structured memory safety policy.+// Regex matching is too coarse for durable memory decisions and can both over-block benign+// content and miss unsafe phrasing that avoids these exact words.+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 memory candidate. */+export interface MemoryWriteInput {+ /** Candidate durable memory content. */+ content: string;+ /** User that owns the memory. */+ userId: string;+}++/** Request envelope for one memory write. */+export interface MemoryWriteRequest {+ /** Evidence supporting the memory write. */+ evidenceRefs: EvidenceRef[];+ /** Stable action idempotency key. */+ idempotencyKey: string;+ /** Domain payload for memory persistence. */+ input: MemoryWriteInput;+}++/** Result returned after a memory write adapter applies a candidate. */+export interface MemoryWriteResult {+ /** Durable memory id. */+ memoryId: string;+ /** Optional short persistence summary. */+ summary?: string;+}++/** Persistence adapter for memory writes. */+export interface MemoryWriter {+ /** Writes memory through the existing memory extraction/persistence stack. */+ writeMemory?: (input: {+ content: string;+ evidenceRefs: EvidenceRef[];+ idempotencyKey: string;+ userId: string;+ }) => Promise<MemoryWriteResult>;+}++/**+ * Error thrown when an injected same-turn adapter needs executor-style status mapping.+ */+export class MemoryActionError 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 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 = 'MemoryActionError';+ this.status = status;+ }+}++/** Common fields for skill domain requests. */+export interface SkillBaseInput {+ /** 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 SkillCreateInput extends SkillBaseInput {+ /** 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 SkillRefineInput extends SkillBaseInput {+ /** Full replacement Markdown body without YAML frontmatter. */+ bodyMarkdown?: string;+ /** Human-readable proposal patch text, not executable replacement content. */+ patch?: string;+ /** Writable managed skill agent document id. */+ skillDocumentId: string;+}++/** Input for consolidating managed skills into a canonical skill. */+export interface SkillConsolidateInput extends SkillBaseInput {+ /** Approval context that allows a consolidation mutation. */+ approval?: {+ /** Source of the approval decision. */+ source: 'proposal' | 'same_turn_feedback';+ };+ /** Full replacement Markdown body for the canonical skill. */+ bodyMarkdown?: string;+ /** Canonical writable managed skill agent document id. */+ canonicalSkillDocumentId: string;+ /** Optional description to persist with the canonical skill index. */+ description?: string;+ /** Source managed skill ids used to build the canonical skill. */+ sourceSkillIds: string[];+ /** Frozen source snapshots captured when the consolidation was proposed. */+ sourceSnapshots?: SkillTargetSnapshot[];+}++/** Frozen managed-skill target state used by approve-time consolidation preflight. */+export interface SkillTargetSnapshot {+ /** Managed skill bundle agent document id. */+ agentDocumentId?: string;+ /** Content hash observed when the proposal was created. */+ contentHash?: string;+ /** Canonical document id observed when the proposal was created. */+ documentId?: string;+ /** Whether the target was managed by Agent Signal. */+ managed?: boolean;+ /** Target domain captured by the proposal snapshot. */+ targetType?: 'skill';+ /** Whether the target was writable at proposal time. */+ writable?: boolean;+}++/** Request envelope for creating one skill. */+export interface SkillCreateRequest {+ /** Evidence supporting the skill creation. */+ evidenceRefs: EvidenceRef[];+ /** Stable action idempotency key. */+ idempotencyKey: string;+ /** Domain payload. */+ input: SkillCreateInput;+}++/** Request envelope for refining one skill. */+export interface SkillRefineRequest {+ /** Evidence supporting the refinement. */+ evidenceRefs: EvidenceRef[];+ /** Stable action idempotency key. */+ idempotencyKey: string;+ /** Domain payload. */+ input: SkillRefineInput;+}++/** Request envelope for consolidating managed skills. */+export interface SkillConsolidateRequest {+ /** Evidence supporting the consolidation. */+ evidenceRefs: EvidenceRef[];+ /** Stable action idempotency key. */+ idempotencyKey: string;+ /** Domain payload. */+ input: SkillConsolidateInput;+}++/** Result returned by skill adapters. */+export interface SkillResult {+ /** Affected writable managed skill document id. */+ skillDocumentId: string;+ /** Optional short persistence summary. */+ summary?: string;+}++/** Persistence adapters for managed skill operations. */+export interface SkillAdapters {+ /** Consolidates managed skills through the existing skill stack. */+ consolidateSkill?: (request: SkillConsolidateRequest) => Promise<SkillResult>;+ /** Creates managed skills through the existing skill stack. */+ createSkill?: (request: SkillCreateRequest) => Promise<SkillResult>;+ /** Refines managed skills through the existing skill stack. */+ refineSkill?: (request: SkillRefineRequest) => Promise<SkillResult>;+}++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');+ }+};++const assertWritableSkill = (targetReadonly: boolean | undefined) => {+ if (targetReadonly) {+ throw new Error('Skill target is readonly');+ }+};++const assertApprovedConsolidation = (input: SkillConsolidateInput) => {+ if (!input.approval) {+ throw new Error('Skill consolidation requires proposal or explicit same-turn approval');+ }+};++const assertCompleteRefineBody = (input: SkillRefineInput) => {+ if (!input.bodyMarkdown?.trim()) {+ throw new Error('Skill refinement requires a complete replacement bodyMarkdown');+ }+};++/**+ * Creates a memory service.+ *+ * Use when:+ * - Nightly self-review or self-reflection needs to write validated memory candidates+ * - Same-turn action handlers need a reusable 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 createMemoryService = (writer: MemoryWriter = {}) => ({+ writeMemory: async (request: MemoryWriteRequest): Promise<MemoryWriteResult> => {+ 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,+ });+ },+});++/**+ * Creates a skill management service.+ *+ * Use when:+ * - Self-iteration 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: SkillAdapters = {}) => ({+ consolidateSkill: async (request: SkillConsolidateRequest): Promise<SkillResult> => {+ 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: SkillCreateRequest): Promise<SkillResult> => {+ assertWritableSkill(request.input.targetReadonly);++ if (!adapters.createSkill) {+ throw new Error('Skill create adapter is required');+ }++ return adapters.createSkill(request);+ },+ refineSkill: async (request: SkillRefineRequest): Promise<SkillResult> => {+ assertWritableSkill(request.input.targetReadonly);+ assertCompleteRefineBody(request.input);++ if (!adapters.refineSkill) {+ throw new Error('Skill refine adapter is required');+ }++ return adapters.refineSkill(request);+ },+});++/** Terminal status emitted by safe write tools. */+export type ToolWriteStatus =+ | 'applied'+ | 'deduped'+ | 'failed'+ | 'proposed'+ | 'skipped_stale'+ | 'skipped_unsupported';++/** Public result returned by safe write tools. */+export interface ToolWriteResult {+ /** Receipt written for the terminal tool outcome. */+ receiptId?: string;+ /** Resource touched or considered by the tool. */+ resourceId?: string;+ /** Terminal write safety status. */+ status: ToolWriteStatus;+ /** Bounded human-readable tool result. */+ summary?: string;+}++/** Successful preflight result for an existing-resource write targeting an existing resource. */+export interface ToolPreflightAllowed {+ /** Whether the target is still safe to mutate. */+ allowed: true;+}++/** Failed preflight result for an existing-resource write targeting an existing resource. */+export interface ToolPreflightDenied {+ /** Whether the target is still safe to mutate. */+ allowed: false;+ /** Short stale/conflict reason to store in the receipt. */+ reason: string;+}++/** Preflight result emitted before existing-resource writes. */+export type ToolPreflightResult = ToolPreflightAllowed | ToolPreflightDenied;++/** Write envelope accepted by all resource tools. */+export interface ToolWriteInput {+ /** Stable operation key used to dedupe repeated tool calls. */+ idempotencyKey: string;+ /** Stable proposal key used for proposal-scoped tracing and receipts. */+ proposalKey?: string;+ /** Optional caller-provided summary, bounded before persistence. */+ summary?: string;+ /** User that owns the resource operation. */+ userId: string;+}++/** Input for replacing one managed skill using compare-and-swap safety checks. */+export interface ReplaceSkillContentCASInput extends ToolWriteInput {+ /** Complete target snapshot captured when the proposal was created. */+ baseSnapshot?: SelfReviewProposalBaseSnapshot;+ /** Replacement skill body. */+ bodyMarkdown: string;+ /** Optional replacement description. */+ description?: string;+ /** Existing managed skill document id. */+ skillDocumentId: string;+}++/** Input for creating one skill when no existing skill has been selected. */+export interface CreateSkillIfAbsentInput extends ToolWriteInput {+ /** Skill body or authoring payload. */+ bodyMarkdown: string;+ /** Optional skill description. */+ description?: string;+ /** Stable skill name. */+ name: string;+ /** Optional skill title. */+ title?: string;+}++/** Input for writing one durable memory candidate from explicit nightly evidence. */+export interface WriteMemoryInput extends ToolWriteInput {+ /** Candidate durable memory content. */+ content: string;+ /** Evidence supporting this memory write. */+ evidenceRefs: EvidenceRef[];+}++/** Input for listing managed skills in one agent scope. */+export interface ListManagedSkillsInput {+ /** Agent whose managed skills are visible to the tool call. */+ agentId: string;+ /** User that owns the read operation. */+ userId: string;+}++/** Input for reading one managed skill in one agent scope. */+export interface GetManagedSkillInput extends ListManagedSkillsInput {+ /** Existing managed skill document id. */+ skillDocumentId: string;+}++/** Input for listing self-review proposals in one agent scope. */+export interface ListSelfReviewProposalsInput {+ /** Agent whose proposals are visible to the tool call. */+ agentId: string;+ /** User that owns the read operation. */+ userId: string;+}++/** Input for reading an evidence digest in one agent scope. */+export interface GetEvidenceDigestInput {+ /** Agent whose evidence is visible to the tool call. */+ agentId: string;+ /** Optional bounded evidence ids selected by the caller. */+ evidenceIds?: string[];+ /** Optional inclusive review window end timestamp. */+ reviewWindowEnd?: string;+ /** Optional inclusive review window start timestamp. */+ reviewWindowStart?: string;+ /** User that owns the read operation. */+ userId: string;+}++/** Input for creating one user-visible self-review proposal. */+export interface CreateSelfReviewProposalInput extends ToolWriteInput {+ /** Proposal action payload retained by the injected proposal adapter. */+ actions?: unknown[];+ /** Proposal metadata retained by the injected proposal adapter. */+ metadata?: Record<string, unknown>;+}++/** Input for refreshing an existing self-review proposal. */+export interface RefreshSelfReviewProposalInput extends ToolWriteInput {+ /** Existing proposal id to refresh. */+ proposalId: string;+}++/** Input for superseding an existing self-review proposal. */+export interface SupersedeSelfReviewProposalInput extends ToolWriteInput {+ /** Existing proposal id to supersede. */+ proposalId: string;+ /** Replacement proposal key or id. */+ supersededBy: string;+}++/** Input for closing an existing self-review proposal. */+export interface CloseSelfReviewProposalInput extends ToolWriteInput {+ /** Existing proposal id to close. */+ proposalId: string;+ /** Lifecycle reason recorded by the injected adapter. */+ reason?: string;+}++/** Result returned by mutation adapters before receipt persistence. */+export interface ToolMutationResult {+ /** Resource created or updated by the adapter. */+ resourceId?: string;+ /** Short adapter summary. */+ summary?: string;+}++/** Receipt write request emitted after every terminal write outcome. */+export interface ToolReceiptInput extends ToolWriteResult {+ /** Stable operation key used to dedupe repeated tool calls. */+ idempotencyKey: string;+ /** Stable proposal key used for proposal-scoped tracing and receipts. */+ proposalKey?: string;+ /** Tool that produced this receipt. */+ toolName: string;+ /** User that owns the resource operation. */+ userId: string;+}++/** Receipt adapter result. */+export interface ToolReceiptResult {+ /** Persisted receipt id. */+ receiptId?: string;+}++/** Lifecycle request emitted after a reserved resource operation reaches a terminal state. */+export interface OperationLifecycleInput extends ToolReceiptInput {+ /** Persisted terminal receipt id, when the receipt adapter returns one. */+ receiptId?: string;+}++/** Lifecycle request emitted when a reserved operation cannot write its terminal receipt. */+export interface OperationFailureInput extends ToolReceiptInput {+ /** Error thrown while writing the terminal receipt. */+ error: unknown;+}++/** Atomic reservation result for a newly claimed resource operation. */+export interface ReservedOperation {+ /** True when the adapter atomically claimed this idempotency key for mutation. */+ reserved: true;+}++/** Atomic reservation result for a previously completed resource operation. */+export interface ExistingOperation {+ /** Prior terminal operation result returned without running mutation. */+ existing: ToolWriteResult;+ /** False when the adapter found an existing terminal operation for this key. */+ reserved: false;+}++/** Atomic idempotency reservation emitted before any write preflight or mutation. */+export type OperationReservation = ExistingOperation | ReservedOperation;++/** Adapters used by safe read/write tools. */+export interface ToolSetAdapters {+ /** Closes an existing self-review proposal. */+ closeProposal?: (input: CloseSelfReviewProposalInput) => Promise<ToolMutationResult>;+ /**+ * Marks a reserved idempotency operation as terminal after its receipt is persisted.+ *+ * Adapters that store in-progress reservations should use this hook to make the terminal+ * receipt/result the dedupe source of truth. Without it, repeated calls may either rerun+ * mutation or leave reservations stuck in an in-progress state.+ */+ completeOperation?: (input: OperationLifecycleInput) => Promise<void>;+ /** Completes server-owned CAS metadata before validating an existing skill replacement. */+ completeReplaceSkillInput?: (+ input: ReplaceSkillContentCASInput,+ ) => Promise<ReplaceSkillContentCASInput>;+ /** Creates one user-visible self-review proposal. */+ createProposal?: (+ input: CreateSelfReviewProposalInput,+ ) => Promise<ToolMutationResult & { proposalId?: string }>;+ /** Creates one managed skill. */+ createSkill?: (input: CreateSkillIfAbsentInput) => Promise<ToolMutationResult>;+ /** Reads a bounded evidence digest for self-iteration planning. */+ getEvidenceDigest?: (input: GetEvidenceDigestInput) => Promise<unknown | undefined>;+ /** Reads one managed skill in the requested agent scope. */+ getManagedSkill?: (input: GetManagedSkillInput) => Promise<unknown | undefined>;+ /** Lists managed skills in the requested agent scope. */+ listManagedSkills?: (input: ListManagedSkillsInput) => Promise<unknown[]>;+ /** Lists self-review proposals in the requested agent scope. */+ listSelfReviewProposals?: (input: ListSelfReviewProposalsInput) => Promise<unknown[]>;+ /**+ * Marks or releases a reserved operation when its terminal receipt cannot be persisted.+ *+ * Adapters should make this hook prevent duplicate mutation while avoiding permanently stuck+ * reservations. A common implementation records the failure against the idempotency key and+ * releases retryable reservation state only when the mutation contract is safe to retry.+ */+ markOperationFailed?: (input: OperationFailureInput) => Promise<void>;+ /** Checks freshness and writability before mutating existing resources. */+ preflight?: (+ input:+ | CloseSelfReviewProposalInput+ | RefreshSelfReviewProposalInput+ | ReplaceSkillContentCASInput+ | SupersedeSelfReviewProposalInput,+ ) => Promise<ToolPreflightResult>;+ /** Reads an existing self-review proposal. */+ readProposal?: (input: {+ proposalId?: string;+ proposalKey?: string;+ userId: string;+ }) => Promise<unknown>;+ /** Refreshes an existing self-review proposal. */+ refreshProposal?: (input: RefreshSelfReviewProposalInput) => Promise<ToolMutationResult>;+ /** Replaces existing managed skill content after CAS preflight. */+ replaceSkill?: (input: ReplaceSkillContentCASInput) => Promise<ToolMutationResult>;+ /** Atomically reserves an idempotency key before any preflight or mutation runs. */+ reserveOperation: (idempotencyKey: string) => Promise<OperationReservation>;+ /** Supersedes an existing self-review proposal. */+ supersedeProposal?: (input: SupersedeSelfReviewProposalInput) => Promise<ToolMutationResult>;+ /** Writes one durable memory candidate. */+ writeMemory?: (input: WriteMemoryInput) => Promise<ToolMutationResult>;+ /** Writes the audit receipt for a terminal tool status. */+ writeReceipt: (input: ToolReceiptInput) => Promise<ToolReceiptResult>;+}++const MAX_SUMMARY_LENGTH = 240;++/**+ * Normalizes tool summaries.+ *+ * Before:+ * - `" A very long summary ... "`+ *+ * After:+ * - `"A very long summary ..."`+ */+const boundSummary = (summary: string | undefined) => {+ if (!summary) return undefined;++ const normalized = summary.trim().replaceAll(/\s+/g, ' ');++ return normalized.length > MAX_SUMMARY_LENGTH+ ? `${normalized.slice(0, MAX_SUMMARY_LENGTH - 3)}...`+ : normalized;+};++const errorSummary = (error: unknown) =>+ boundSummary(error instanceof Error ? error.message : String(error));++const getErrorMessage = (error: unknown) =>+ error instanceof Error ? error.message : String(error);++const hasNonBlankString = (value: unknown): value is string =>+ typeof value === 'string' && value.trim().length > 0;++const isCompleteRefineBaseSnapshot = (+ snapshot: unknown,+): snapshot is SelfReviewProposalBaseSnapshot & {+ agentDocumentId: string;+ contentHash: string;+ documentId: string;+} => {+ if (!snapshot || typeof snapshot !== 'object') return false;++ const record = snapshot as Record<string, unknown>;++ return (+ record.targetType === 'skill' &&+ hasNonBlankString(record.agentDocumentId) &&+ hasNonBlankString(record.documentId) &&+ hasNonBlankString(record.contentHash) &&+ record.managed === true &&+ record.writable === true+ );+};++const getResultWithReceipt = async (+ adapters: ToolSetAdapters,+ input: ToolWriteInput,+ toolName: string,+ result: ToolWriteResult,+): Promise<ToolWriteResult> => {+ const boundedResult = { ...result, summary: boundSummary(result.summary) };+ const receipt = await adapters.writeReceipt({+ ...boundedResult,+ idempotencyKey: input.idempotencyKey,+ proposalKey: input.proposalKey,+ toolName,+ userId: input.userId,+ });++ return { ...boundedResult, receiptId: receipt.receiptId ?? boundedResult.receiptId };+};++const withWriteSpan = async <TInput extends ToolWriteInput>(+ toolName: string,+ input: TInput,+ operation: (recordConvertedException: (error: unknown) => void) => Promise<ToolWriteResult>,+) => {+ return tracer.startActiveSpan(+ 'agent_signal.self_iteration_tool.write',+ {+ attributes: {+ 'agent.signal.self_iteration_tool.name': toolName,+ ...(input.proposalKey ? { 'agent.signal.proposal.key': input.proposalKey } : {}),+ },+ },+ async (span) => {+ try {+ const result = await operation((error) => span.recordException(error as Error));++ span.setAttribute('agent.signal.self_iteration_tool.write_status', result.status);+ span.setStatus({+ code: result.status === 'failed' ? SpanStatusCode.ERROR : SpanStatusCode.OK,+ });++ return result;+ } catch (error) {+ span.recordException(error as Error);+ span.setStatus({ code: SpanStatusCode.ERROR, message: getErrorMessage(error) });++ throw error;+ } finally {+ span.end();+ }+ },+ );+};++const withReadSpan = async <TResult>(+ toolName: string,+ proposalKey: string | undefined,+ operation: () => Promise<TResult>,+) => {+ return tracer.startActiveSpan(+ 'agent_signal.self_iteration_tool.read',+ {+ attributes: {+ 'agent.signal.self_iteration_tool.name': toolName,+ ...(proposalKey ? { 'agent.signal.proposal.key': proposalKey } : {}),+ },+ },+ async (span) => {+ try {+ const result = await operation();++ span.setStatus({ code: SpanStatusCode.OK });++ return result;+ } catch (error) {+ span.recordException(error as Error);+ span.setStatus({ code: SpanStatusCode.ERROR, message: getErrorMessage(error) });++ throw error;+ } finally {+ span.end();+ }+ },+ );+};++const runWriteTool = async <TInput extends ToolWriteInput>({+ adapters,+ input,+ mutate,+ preflight,+ preflightRequired,+ resourceId,+ successStatus,+ toolName,+ unsupportedSummary,+ validate,+}: {+ adapters: ToolSetAdapters;+ input: TInput;+ mutate?: () => Promise<ToolMutationResult>;+ preflight?: () => Promise<ToolPreflightResult>;+ preflightRequired?: boolean;+ resourceId?: string;+ successStatus: Exclude<+ ToolWriteStatus,+ 'deduped' | 'failed' | 'skipped_stale' | 'skipped_unsupported'+ >;+ toolName: string;+ unsupportedSummary: string;+ validate?: () => ToolWriteResult | undefined;+}) => {+ return withWriteSpan(toolName, input, async (recordConvertedException) => {+ let operationReserved = false;+ const result = await (async (): Promise<ToolWriteResult> => {+ try {+ const reservation = await adapters.reserveOperation(input.idempotencyKey);++ if (!reservation.reserved) {+ return {+ resourceId: reservation.existing.resourceId,+ status: 'deduped',+ summary: reservation.existing.summary,+ };+ }++ operationReserved = true;++ const validationResult = validate?.();+ if (validationResult) return validationResult;++ if (!mutate) {+ return {+ resourceId,+ status: 'skipped_unsupported',+ summary: unsupportedSummary,+ };+ }++ if (preflightRequired && !preflight) {+ return {+ resourceId,+ status: 'skipped_unsupported',+ summary: 'Tool preflight is not supported.',+ };+ }++ if (preflight) {+ const preflightResult = await preflight();++ if (!preflightResult.allowed) {+ return {+ resourceId,+ status: 'skipped_stale',+ summary: preflightResult.reason || input.summary,+ };+ }+ }++ const mutationResult = await mutate();++ return {+ resourceId: mutationResult.resourceId ?? resourceId,+ status: successStatus,+ summary: mutationResult.summary ?? input.summary,+ };+ } catch (error) {+ recordConvertedException(error);++ return {+ resourceId,+ status: 'failed',+ summary: errorSummary(error),+ };+ }+ })();++ try {+ const resultWithReceipt = await getResultWithReceipt(adapters, input, toolName, result);++ if (operationReserved) {+ await adapters.completeOperation?.({+ ...resultWithReceipt,+ idempotencyKey: input.idempotencyKey,+ proposalKey: input.proposalKey,+ toolName,+ userId: input.userId,+ });+ }++ return resultWithReceipt;+ } catch (error) {+ if (operationReserved) {+ await adapters.markOperationFailed?.({+ ...result,+ error,+ idempotencyKey: input.idempotencyKey,+ proposalKey: input.proposalKey,+ toolName,+ userId: input.userId,+ });+ }++ throw error;+ }+ });+};++/**+ * Creates safe read/write resource tools with injected domain adapters.+ *+ * Use when:+ * - Agent Signal needs callable resource tools before runner wiring+ * - Tests need to verify write safety contracts without database services+ *+ * Expects:+ * - `idempotencyKey` is stable per intended write+ * - Existing-resource writes inject `preflight` before mutation+ *+ * Returns:+ * - Tool functions that dedupe, preflight, mutate, receipt, and trace consistently+ */+export const createToolSet = (adapters: ToolSetAdapters) => ({+ closeSelfReviewProposal: async (input: CloseSelfReviewProposalInput) =>+ runWriteTool({+ adapters,+ input,+ mutate: adapters.closeProposal ? () => adapters.closeProposal!(input) : undefined,+ preflight: adapters.preflight ? () => adapters.preflight!(input) : undefined,+ preflightRequired: true,+ resourceId: input.proposalId,+ successStatus: 'applied',+ toolName: 'closeSelfReviewProposal',+ unsupportedSummary: 'Self-review proposal close is not supported.',+ }),+ createSelfReviewProposal: async (input: CreateSelfReviewProposalInput) =>+ runWriteTool({+ adapters,+ input,+ mutate: adapters.createProposal+ ? async () => {+ const result = await adapters.createProposal!(input);++ return {+ resourceId: result.resourceId ?? result.proposalId,+ summary: result.summary,+ };+ }+ : undefined,+ successStatus: 'proposed',+ toolName: 'createSelfReviewProposal',+ unsupportedSummary: 'Self-review proposal creation is not supported.',+ }),+ createSkillIfAbsent: async (input: CreateSkillIfAbsentInput) =>+ runWriteTool({+ adapters,+ input,+ mutate: adapters.createSkill ? () => adapters.createSkill!(input) : undefined,+ successStatus: 'applied',+ toolName: 'createSkillIfAbsent',+ unsupportedSummary: 'Skill creation is not supported.',+ validate: () => {+ if (hasNonBlankString(input.name) && hasNonBlankString(input.bodyMarkdown)) {+ return undefined;+ }++ return {+ status: 'skipped_unsupported',+ summary: 'Skill creation requires a non-empty name and body.',+ };+ },+ }),+ writeMemory: async (input: WriteMemoryInput) =>+ runWriteTool({+ adapters,+ input,+ mutate: adapters.writeMemory ? () => adapters.writeMemory!(input) : undefined,+ successStatus: 'applied',+ toolName: 'writeMemory',+ unsupportedSummary: 'Memory writing is not supported.',+ }),+ getEvidenceDigest: async (input: GetEvidenceDigestInput) =>+ withReadSpan('getEvidenceDigest', undefined, async () => {+ if (!adapters.getEvidenceDigest) return undefined;++ return adapters.getEvidenceDigest(input);+ }),+ getManagedSkill: async (input: GetManagedSkillInput) =>+ withReadSpan('getManagedSkill', undefined, async () => {+ if (!adapters.getManagedSkill) return undefined;++ return adapters.getManagedSkill(input);+ }),+ listSelfReviewProposals: async (input: ListSelfReviewProposalsInput) =>+ withReadSpan('listSelfReviewProposals', undefined, async () => {+ if (!adapters.listSelfReviewProposals) return [];++ return adapters.listSelfReviewProposals(input);+ }),+ listManagedSkills: async (input: ListManagedSkillsInput) =>+ withReadSpan('listManagedSkills', undefined, async () => {+ if (!adapters.listManagedSkills) return [];++ return adapters.listManagedSkills(input);+ }),+ readSelfReviewProposal: async (input: {+ proposalId?: string;+ proposalKey?: string;+ userId: string;+ }) =>+ withReadSpan('readSelfReviewProposal', input.proposalKey, async () => {+ if (!adapters.readProposal) return undefined;++ return adapters.readProposal(input);+ }),+ refreshSelfReviewProposal: async (input: RefreshSelfReviewProposalInput) =>+ runWriteTool({+ adapters,+ input,+ mutate: adapters.refreshProposal ? () => adapters.refreshProposal!(input) : undefined,+ preflight: adapters.preflight ? () => adapters.preflight!(input) : undefined,+ preflightRequired: true,+ resourceId: input.proposalId,+ successStatus: 'proposed',+ toolName: 'refreshSelfReviewProposal',+ unsupportedSummary: 'Self-review proposal refresh is not supported.',+ }),+ replaceSkillContentCAS: async (input: ReplaceSkillContentCASInput) => {+ const enrichedInput = adapters.completeReplaceSkillInput+ ? await adapters.completeReplaceSkillInput(input)+ : input;++ return runWriteTool({+ adapters,+ input: enrichedInput,+ mutate: adapters.replaceSkill ? () => adapters.replaceSkill!(enrichedInput) : undefined,+ preflight: adapters.preflight ? () => adapters.preflight!(enrichedInput) : undefined,+ preflightRequired: true,+ resourceId: enrichedInput.skillDocumentId,+ successStatus: 'applied',+ toolName: 'replaceSkillContentCAS',+ unsupportedSummary: 'Skill replacement is not supported.',+ validate: () => {+ if (!hasNonBlankString(enrichedInput.bodyMarkdown)) {+ return {+ resourceId: enrichedInput.skillDocumentId,+ status: 'skipped_unsupported',+ summary: 'Skill replacement requires a non-empty body.',+ };+ }++ if (isCompleteRefineBaseSnapshot(enrichedInput.baseSnapshot)) return undefined;++ return {+ resourceId: enrichedInput.skillDocumentId,+ status: 'skipped_unsupported',+ summary: 'Skill replacement requires a complete base snapshot.',+ };+ },+ });+ },+ supersedeSelfReviewProposal: async (input: SupersedeSelfReviewProposalInput) =>+ runWriteTool({+ adapters,+ input,+ mutate: adapters.supersedeProposal ? () => adapters.supersedeProposal!(input) : undefined,+ preflight: adapters.preflight ? () => adapters.preflight!(input) : undefined,+ preflightRequired: true,+ resourceId: input.proposalId,+ successStatus: 'applied',+ toolName: 'supersedeSelfReviewProposal',+ unsupportedSummary: 'Self-review proposal supersede is not supported.',+ }),+});++/** Callable safe resource tools exposed to bounded agent runners. */+export type ToolSet = ReturnType<typeof createToolSet>;++/**+ * Class-backed boundary for self-iteration resource tools.+ *+ * Use when:+ * - Review and reflection modes need the same dedupe, preflight, receipt, and tracing behavior+ * - Tests need one mockable collaborator instead of many function overrides+ *+ * Expects:+ * - Adapters are scoped to one user/agent boundary by the server runtime+ * - Existing-resource writes provide preflight where required+ *+ * Returns:+ * - A stable class surface that delegates to the safe write/read implementation+ */+export class ToolSetFacade {+ private readonly adapters: ToolSetAdapters;+ private readonly tools: ToolSet;++ constructor(adapters: ToolSetAdapters) {+ this.adapters = adapters;+ this.tools = createToolSet(adapters);+ }++ createSkillIfAbsent(input: CreateSkillIfAbsentInput) {+ return this.tools.createSkillIfAbsent(input);+ }++ replaceSkillContentCAS(input: ReplaceSkillContentCASInput) {+ return this.tools.replaceSkillContentCAS(input);+ }++ writeMemory(input: WriteMemoryInput) {+ return this.tools.writeMemory(input);+ }++ reserveOperation(idempotencyKey: string) {+ return this.adapters.reserveOperation(idempotencyKey);+ }++ completeOperation(input: OperationLifecycleInput) {+ return this.adapters.completeOperation?.(input) ?? Promise.resolve();+ }++ getEvidenceDigest(input: GetEvidenceDigestInput) {+ return this.tools.getEvidenceDigest(input);+ }++ getManagedSkill(input: GetManagedSkillInput) {+ return this.tools.getManagedSkill(input);+ }++ listManagedSkills(input: ListManagedSkillsInput) {+ return this.tools.listManagedSkills(input);+ }++ listSelfReviewProposals(input: ListSelfReviewProposalsInput) {+ return this.tools.listSelfReviewProposals(input);+ }++ readSelfReviewProposal(input: { proposalId?: string; proposalKey?: string; userId: string }) {+ return this.tools.readSelfReviewProposal(input);+ }++ createSelfReviewProposal(input: CreateSelfReviewProposalInput) {+ return this.tools.createSelfReviewProposal(input);+ }++ refreshSelfReviewProposal(input: RefreshSelfReviewProposalInput) {+ return this.tools.refreshSelfReviewProposal(input);+ }++ supersedeSelfReviewProposal(input: SupersedeSelfReviewProposalInput) {+ return this.tools.supersedeSelfReviewProposal(input);+ }++ closeSelfReviewProposal(input: CloseSelfReviewProposalInput) {+ return this.tools.closeSelfReviewProposal(input);+ }+}diff --git a/src/server/services/agentSignal/services/selfIteration/types.ts b/src/server/services/agentSignal/services/selfIteration/types.tsnew file mode 100644index 00000000000..27ad646ea7d--- /dev/null+++ b/src/server/services/agentSignal/services/selfIteration/types.ts@@ -0,0 +1,385 @@+import type {+ MemoryWriteInput,+ SkillConsolidateInput,+ SkillCreateInput,+ SkillRefineInput,+} from './tools/shared';++/**+ * Evidence reference persisted in self-iteration plans, ideas, receipts, and brief artifacts.+ */+export interface EvidenceRef {+ /** Stable evidence id in its source domain. */+ id: string;+ /** Optional short reason this evidence matters. */+ summary?: string;+ /** Domain that owns the evidence id. */+ type:+ | 'topic'+ | 'message'+ | 'operation'+ | 'source'+ | 'receipt'+ | 'tool_call'+ | 'task'+ | 'agent_document'+ | 'memory';+}++/**+ * Input for a stable nightly self-review source id.+ */+export interface NightlyReviewSourceIdInput {+ /** Agent reviewed in the local nightly window. */+ agentId: string;+ /** Local date represented as `YYYY-MM-DD`. */+ localDate: string;+ /** User that owns the reviewed agent. */+ userId: string;+}++/**+ * Input for a stable immediate self-reflection source id.+ */+export interface SelfReflectionSourceIdInput {+ /** Agent associated with the weak-signal trigger. */+ agentId: string;+ /** Trigger reason emitted by the accumulator or caller. */+ reason: string;+ /** Scoped id selected for the reflection window. */+ scopeId: string;+ /** Scope family selected for the reflection window. */+ scopeType: 'topic' | 'task' | 'operation';+ /** User that owns the reflected agent. */+ userId: string;+ /** ISO timestamp for the end of the reflection window. */+ windowEnd: string;+ /** ISO timestamp for the beginning of the reflection window. */+ windowStart: string;+}++/**+ * Input for a stable agent-declared self-feedback intent source id.+ */+export interface SelfFeedbackIntentSourceIdInput {+ /** Agent that declared the intent. */+ agentId: string;+ /** Scope id selected from operation or topic context. */+ scopeId: string;+ /** Scope family selected for the declaration. */+ scopeType: 'operation' | 'topic';+ /** Tool call id that declared the intent. */+ toolCallId: string;+ /** User that owns the declaring agent. */+ userId: 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 immediate 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 self-feedback intent.+ *+ * Before:+ * - `{ userId: "u", agentId: "a", scopeType: "topic", scopeId: "topic", toolCallId: "call" }`+ *+ * After:+ * - `"self-feedback-intent:u:a:topic:topic:call"`+ */+export const buildSelfFeedbackIntentSourceId = (input: SelfFeedbackIntentSourceIdInput) =>+ `self-feedback-intent:${input.userId}:${input.agentId}:${input.scopeType}:${input.scopeId}:${input.toolCallId}`;++export enum Scope {+ Nightly = 'nightly',+ SelfFeedback = 'self_feedback',+ SelfReflection = 'self_reflection',+}++export enum ReviewRunStatus {+ Collected = 'collected',+ Completed = 'completed',+ Deduped = 'deduped',+ Failed = 'failed',+ PartiallyApplied = 'partially_applied',+ Planned = 'planned',+ Skipped = 'skipped',+}++export type ActionType =+ | 'write_memory'+ | 'create_skill'+ | 'refine_skill'+ | 'consolidate_skill'+ | 'noop'+ | 'proposal_only';++export enum ApplyMode {+ AutoApply = 'auto_apply',+ ProposalOnly = 'proposal_only',+ Skip = 'skip',+}++export enum Risk {+ High = 'high',+ Low = 'low',+ Medium = 'medium',+}++export enum ActionStatus {+ Applied = 'applied',+ Deduped = 'deduped',+ Failed = 'failed',+ Proposed = 'proposed',+ Skipped = 'skipped',+}++export interface DomainOperationCase<TDomain, TOperation, TInput> {+ domain: TDomain;+ input: TInput;+ operation: TOperation;+}++export type MemoryWriteOperation = DomainOperationCase<'memory', 'write', MemoryWriteInput>;++export type SkillCreateOperation = DomainOperationCase<'skill', 'create', SkillCreateInput>;++export type SkillRefineOperation = DomainOperationCase<'skill', 'refine', SkillRefineInput>;++export type SkillConsolidateOperation = DomainOperationCase<+ 'skill',+ 'consolidate',+ SkillConsolidateInput+>;++export type DomainOperation =+ | MemoryWriteOperation+ | SkillConsolidateOperation+ | SkillCreateOperation+ | SkillRefineOperation;++export interface ActionTarget {+ memoryId?: string;+ skillDocumentId?: string;+ skillName?: string;+ targetReadonly?: boolean;+ taskIds?: string[];+ topicIds?: string[];+}++export interface ActionPlan {+ actionType: ActionType;+ applyMode: ApplyMode;+ confidence: number;+ dedupeKey: string;+ evidenceRefs: EvidenceRef[];+ idempotencyKey: string;+ operation?: DomainOperation;+ rationale: string;+ risk: Risk;+ sourceActionId?: string;+ target?: ActionTarget;+}++export interface Plan {+ actions: ActionPlan[];+ localDate?: string;+ plannerVersion: string;+ reviewScope: Scope;+ summary: string;+}++export interface ActionResult {+ idempotencyKey: string;+ receiptId?: string;+ resourceId?: string;+ status: ActionStatus;+ summary?: string;+}++export interface RunResult {+ actions: ActionResult[];+ briefId?: string;+ sourceId?: string;+ status: ReviewRunStatus;+ summaryReceiptId?: string;+}++export interface ActionIdempotencyInput {+ actionType: ActionType;+ dedupeKey: string;+ sourceId: string;+}++/**+ * Builds a replay guard key for one planned self-review action.+ *+ * Before:+ * - `{ sourceId: "source", actionType: "write_memory", dedupeKey: "memory:abc" }`+ *+ * After:+ * - `"source:write_memory:memory:abc"`+ */+export const buildActionIdempotencyKey = (input: ActionIdempotencyInput) =>+ `${input.sourceId}:${input.actionType}:${input.dedupeKey}`;++export const isActionExecutable = (applyMode: ApplyMode) => applyMode === ApplyMode.AutoApply;++/**+ * Self-iteration execution mode.+ */+export type IterationMode = 'feedback' | 'reflection' | 'review';++/**+ * Stable status values emitted by shared runs.+ */+export enum RunStatus {+ Collected = 'collected',+ Completed = 'completed',+ Deduped = 'deduped',+ Failed = 'failed',+ PartiallyApplied = 'partially_applied',+ Planned = 'planned',+ Skipped = 'skipped',+}++/**+ * Evidence window used by review, reflection, and intent runs.+ */+export interface IterationWindow {+ /** End of the evidence window as an ISO timestamp. */+ end: string;+ /** Local review date for nightly review runs. */+ localDate?: string;+ /** Start of the evidence window as an ISO timestamp. */+ start: string;+ /** User timezone used to derive local review dates. */+ timezone?: string;+}++/**+ * Explicit shared target shape persisted in brief and receipt metadata.+ */+export interface IterationTarget {+ /** Stable user memory id when the idea targets one existing memory. */+ memoryId?: string;+ /** True when the target must never direct-apply. */+ readonly?: boolean;+ /** Agent document binding id for managed skills. */+ skillDocumentId?: string;+ /** Stable managed skill name when the binding id is not known yet. */+ skillName?: string;+ /** Task ids that contributed evidence. */+ taskIds?: string[];+ /** Topic ids that contributed evidence. */+ topicIds?: string[];+}++/**+ * A non-executable shared idea preserved for later review.+ */+export interface Idea {+ /** Evidence references that justify keeping the idea. */+ evidenceRefs: EvidenceRef[];+ /** Stable dedupe key for this idea. */+ idempotencyKey: string;+ /** Why the idea exists. */+ rationale: string;+ /** Risk if this idea became a mutation later. */+ risk: 'high' | 'low' | 'medium';+ /** Optional target this idea is about. */+ target?: IterationTarget;+ /** Optional short label for UI/artifact presentation. */+ title?: string;+}++/**+ * Programmatic resource operation that a self-feedback intent may carry.+ */+export type SelfFeedbackIntentOperation =+ | {+ domain: 'memory';+ input: { content: string; userId: string };+ operation: 'write';+ }+ | {+ domain: 'skill';+ input: {+ bodyMarkdown?: string;+ description?: string;+ name?: string;+ title?: string;+ userId: string;+ };+ operation: 'create';+ }+ | {+ domain: 'skill';+ input: {+ bodyMarkdown: string;+ description?: string;+ skillDocumentId: string;+ userId: string;+ };+ operation: 'refine';+ }+ | {+ domain: 'skill';+ input: {+ bodyMarkdown?: string;+ canonicalSkillDocumentId: string;+ description?: string;+ sourceSkillIds: string[];+ userId: string;+ };+ operation: 'consolidate';+ };++/**+ * Agent-authored immediate feedback intent stored in receipt metadata.+ */+export interface SelfFeedbackIntent extends Idea {+ /** Optional self-review action hint used when a reviewer later promotes the intent. */+ actionType?: string;+ /** Normalized confidence from 0 to 1. */+ confidence: number;+ /** Why this intent was downgraded instead of directly executable. */+ downgradeReason?: 'approval_required' | 'low_confidence' | 'unsupported_in_reflection';+ /** Resource class this intent is about. */+ intentType: 'memory' | 'skill' | 'tooling' | 'workflow';+ /** Immediate intents are reflection-mode output, not nightly review output. */+ mode: 'reflection';+ /** Optional executable operation after validation. */+ operation?: SelfFeedbackIntentOperation;+ /** How soon the agent should revisit this intent. */+ urgency: 'immediate' | 'later' | 'soon';+}diff --git a/src/server/services/agentSignal/services/selfReflection.ts b/src/server/services/agentSignal/services/selfReflection.tsindex 72ed6cee556..73a753bc5db 100644--- a/src/server/services/agentSignal/services/selfReflection.ts+++ b/src/server/services/agentSignal/services/selfReflection.ts@@ -3,7 +3,7 @@ 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';+import { buildSelfReflectionSourceId } from './selfIteration/types';type MaybePromise<TValue> = TValue | Promise<TValue>;diff --git a/src/server/services/agentSignal/store/adapters/redis/receiptStore.ts b/src/server/services/agentSignal/store/adapters/redis/receiptStore.tsindex 5bbb31f13be..50388f5ec8a 100644--- a/src/server/services/agentSignal/store/adapters/redis/receiptStore.ts+++ b/src/server/services/agentSignal/store/adapters/redis/receiptStore.ts@@ -67,12 +67,7 @@ const fromReceiptHash = (payload: Record<string, string>): AgentSignalReceipt |const createdAt = Number(payload.createdAt);if (!payload.id || !payload.userId || !payload.agentId || !payload.topicId) return;- if (- payload.kind !== 'maintenance' &&- payload.kind !== 'memory' &&- payload.kind !== 'review' &&- payload.kind !== 'skill'- ) {+ if (payload.kind !== 'memory' && payload.kind !== 'review' && payload.kind !== 'skill') {return;}if (diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.tsindex ea65c7bdb6f..8a5a73fa29c 100644--- a/src/server/services/aiAgent/index.ts+++ b/src/server/services/aiAgent/index.ts@@ -8,8 +8,8 @@ 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 {- injectSelfIterationIntentTool,- shouldExposeSelfIterationIntentTool,+ injectSelfFeedbackIntentTool,+ shouldExposeSelfFeedbackIntentTool,} from '@lobechat/builtin-tool-self-iteration';import { TaskIdentifier } from '@lobechat/builtin-tool-task';import { builtinTools, manualModeExcludeToolIds } from '@lobechat/builtin-tools';@@ -150,7 +150,7 @@ interface InternalExecAgentParams extends ExecAgentParams {/** 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;+ disableSelfFeedbackIntentTool?: 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 */@@ -1173,23 +1173,23 @@ export class AiAgentService {const agentSelfIterationEnabled = agentConfig.chatConfig?.selfIteration?.enabled === true;const shouldCheckUserSelfIterationGate =- agentSelfIterationEnabled && !params.disableSelfIterationIntentTool;+ agentSelfIterationEnabled && !params.disableSelfFeedbackIntentTool;if (shouldCheckUserSelfIterationGate &&- shouldExposeSelfIterationIntentTool({+ shouldExposeSelfFeedbackIntentTool({agentSelfIterationEnabled,- disableSelfIterationIntentTool: params.disableSelfIterationIntentTool,+ disableSelfFeedbackIntentTool: params.disableSelfFeedbackIntentTool,featureUserEnabled: await isAgentSignalEnabledForUser(this.db, this.userId),})) {tools = tools ?? [];- injectSelfIterationIntentTool({+ injectSelfFeedbackIntentTool({enabledToolIds: toolsResult.enabledToolIds,manifestMap: toolManifestMap,sourceMap: toolSourceMap,tools,});- log('execAgent: injected self-iteration intent declaration tool');+ log('execAgent: injected self-feedback intent declaration tool');}}diff --git a/src/server/services/toolExecution/serverRuntimes/__tests__/selfIterationIntent.test.ts b/src/server/services/toolExecution/serverRuntimes/__tests__/selfFeedbackIntent.test.tssimilarity index 77%rename from src/server/services/toolExecution/serverRuntimes/__tests__/selfIterationIntent.test.tsrename to src/server/services/toolExecution/serverRuntimes/__tests__/selfFeedbackIntent.test.tsindex f99593ef134..5117327dcc6 100644--- a/src/server/services/toolExecution/serverRuntimes/__tests__/selfIterationIntent.test.ts+++ b/src/server/services/toolExecution/serverRuntimes/__tests__/selfFeedbackIntent.test.ts@@ -2,7 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { enqueueAgentSignalSourceEvent } from '@/server/services/agentSignal';-import { selfIterationIntentRuntime } from '../selfIterationIntent';+import { selfFeedbackIntentRuntime } from '../selfFeedbackIntent';vi.mock('@/server/services/agentSignal', () => ({enqueueAgentSignalSourceEvent: vi.fn(),@@ -17,7 +17,7 @@ const createInput = () => ({summary: 'Refine the release workflow skill.',});-describe('selfIterationIntentRuntime', () => {+describe('selfFeedbackIntentRuntime', () => {beforeEach(() => {vi.clearAllMocks();vi.mocked(enqueueAgentSignalSourceEvent).mockResolvedValue({@@ -32,9 +32,9 @@ describe('selfIterationIntentRuntime', () => {* 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 runtime = selfFeedbackIntentRuntime.factory({ toolManifestMap: {} });- const result = await runtime.declareSelfIterationIntent(createInput(), {+ const result = await runtime.declareSelfFeedbackIntent(createInput(), {agentId: 'agent-1',operationId: 'operation-1',toolCallId: 'tool-call-1',@@ -47,7 +47,7 @@ describe('selfIterationIntentRuntime', () => {expect(JSON.parse(result.content)).toEqual({accepted: true,reason: null,- sourceId: 'self-iteration-intent:user-1:agent-1:operation:operation-1:tool-call-1',+ sourceId: 'self-feedback-intent:user-1:agent-1:operation:operation-1:tool-call-1',strength: 'strong',});expect(enqueueAgentSignalSourceEvent).toHaveBeenCalledWith(@@ -59,8 +59,8 @@ describe('selfIterationIntentRuntime', () => {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',+ sourceId: 'self-feedback-intent:user-1:agent-1:operation:operation-1:tool-call-1',+ sourceType: 'agent.self_feedback_intent.declared',}),{ agentId: 'agent-1', userId: 'user-1' },);@@ -71,9 +71,9 @@ describe('selfIterationIntentRuntime', () => {* 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 runtime = selfFeedbackIntentRuntime.factory({ toolManifestMap: {} });- const result = await runtime.declareSelfIterationIntent(createInput(), {+ const result = await runtime.declareSelfFeedbackIntent(createInput(), {agentId: 'agent-1',toolManifestMap: {},userId: 'user-1',@@ -93,9 +93,9 @@ describe('selfIterationIntentRuntime', () => {* 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 runtime = selfFeedbackIntentRuntime.factory({ toolManifestMap: {} });- const result = await runtime.declareSelfIterationIntent(+ const result = await runtime.declareSelfFeedbackIntent({ ...createInput(), confidence: 1.25 },{agentId: 'agent-1',@@ -121,10 +121,10 @@ describe('selfIterationIntentRuntime', () => {*/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: {} });+ const runtime = selfFeedbackIntentRuntime.factory({ toolManifestMap: {} });await expect(- runtime.declareSelfIterationIntent(createInput(), {+ runtime.declareSelfFeedbackIntent(createInput(), {agentId: 'agent-1',toolCallId,toolManifestMap: {},@@ -134,8 +134,8 @@ describe('selfIterationIntentRuntime', () => {).resolves.toMatchObject({ success: true });}- const runtime = selfIterationIntentRuntime.factory({ toolManifestMap: {} });- const result = await runtime.declareSelfIterationIntent(createInput(), {+ const runtime = selfFeedbackIntentRuntime.factory({ toolManifestMap: {} });+ const result = await runtime.declareSelfFeedbackIntent(createInput(), {agentId: 'agent-1',toolCallId: 'tool-call-4',toolManifestMap: {},diff --git a/src/server/services/toolExecution/serverRuntimes/index.ts b/src/server/services/toolExecution/serverRuntimes/index.tsindex 76684afdc44..532ff520966 100644--- a/src/server/services/toolExecution/serverRuntimes/index.ts+++ b/src/server/services/toolExecution/serverRuntimes/index.ts@@ -22,7 +22,7 @@ import { memoryRuntime } from './memory';import { messageRuntime } from './message';import { notebookRuntime } from './notebook';import { remoteDeviceRuntime } from './remoteDevice';-import { selfIterationIntentRuntime } from './selfIterationIntent';+import { selfFeedbackIntentRuntime } from './selfFeedbackIntent';import { skillManagementRuntime } from './skillManagement';import { skillsRuntime } from './skills';import { skillStoreRuntime } from './skillStore';@@ -72,7 +72,7 @@ registerRuntimes([knowledgeBaseRuntime,webOnboardingRuntime,lobeAgentRuntime,- selfIterationIntentRuntime,+ selfFeedbackIntentRuntime,]);// ==================== Registry API ====================diff --git a/src/server/services/toolExecution/serverRuntimes/selfIterationIntent.ts b/src/server/services/toolExecution/serverRuntimes/selfFeedbackIntent.tssimilarity index 66%rename from src/server/services/toolExecution/serverRuntimes/selfIterationIntent.tsrename to src/server/services/toolExecution/serverRuntimes/selfFeedbackIntent.tsindex 95a1e6b8014..98cfe5f4c49 100644--- a/src/server/services/toolExecution/serverRuntimes/selfIterationIntent.ts+++ b/src/server/services/toolExecution/serverRuntimes/selfFeedbackIntent.ts@@ -1,14 +1,14 @@-import { SELF_ITERATION_INTENT_IDENTIFIER } from '@lobechat/builtin-tool-self-iteration';+import { SELF_FEEDBACK_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 { DeclareSelfFeedbackIntentPayload } from '@/server/services/agentSignal/services/selfFeedbackIntent';+import { createSelfFeedbackIntentService } from '@/server/services/agentSignal/services/selfFeedbackIntent';import type { ToolExecutionContext, ToolExecutionResult } from '../types';import type { ServerRuntimeRegistration } from './types';-type SelfIterationIntentToolResultContent = {+type SelfFeedbackIntentToolResultContent = {accepted: boolean;reason: null | string;sourceId: null | string;@@ -16,14 +16,14 @@ type SelfIterationIntentToolResultContent = {};const createJsonResult = (- content: SelfIterationIntentToolResultContent,+ content: SelfFeedbackIntentToolResultContent,success: boolean,): ToolExecutionResult => ({content: JSON.stringify(content),success,});-const sharedSelfIterationIntentService = createSelfIterationIntentService({+const sharedSelfFeedbackIntentService = createSelfFeedbackIntentService({enqueueSource: (sourceEvent) =>enqueueAgentSignalSourceEvent(sourceEvent, {agentId: sourceEvent.payload.agentId,@@ -33,10 +33,10 @@ const sharedSelfIterationIntentService = createSelfIterationIntentService({});/**- * Server runtime for advisory self-iteration intent declarations.+ * Server runtime for advisory self-feedback intent declarations.** Use when:- * - A running agent calls declareSelfIterationIntent+ * - A running agent calls declareSelfFeedbackIntent* - The server should enqueue Agent Signal source events without mutating resources directly** Expects:@@ -46,9 +46,9 @@ const sharedSelfIterationIntentService = createSelfIterationIntentService({* Returns:* - JSON tool content with accepted status, source id, strength, and rejection reason*/-class SelfIterationIntentRuntime {- declareSelfIterationIntent = async (- input: DeclareSelfIterationIntentPayload,+class SelfFeedbackIntentRuntime {+ declareSelfFeedbackIntent = async (+ input: DeclareSelfFeedbackIntentPayload,context: ToolExecutionContext,): Promise<ToolExecutionResult> => {const { agentId, operationId, toolCallId, topicId, userId } = context;@@ -64,7 +64,7 @@ class SelfIterationIntentRuntime {};}- const result = await sharedSelfIterationIntentService.declareIntent({+ const result = await sharedSelfFeedbackIntentService.declareIntent({agentId,input,operationId,@@ -86,7 +86,7 @@ class SelfIterationIntentRuntime {}/**- * Registers the self-iteration intent builtin server runtime.+ * Registers the self-feedback intent builtin server runtime.** Use when:* - BuiltinToolsExecutor needs to resolve the injected declaration tool@@ -97,7 +97,7 @@ class SelfIterationIntentRuntime {* Returns:* - A lightweight runtime instance for the current execution*/-export const selfIterationIntentRuntime: ServerRuntimeRegistration = {- factory: () => new SelfIterationIntentRuntime(),- identifier: SELF_ITERATION_INTENT_IDENTIFIER,+export const selfFeedbackIntentRuntime: ServerRuntimeRegistration = {+ factory: () => new SelfFeedbackIntentRuntime(),+ identifier: SELF_FEEDBACK_INTENT_IDENTIFIER,};diff --git a/src/server/workflows/agentSignal/__tests__/run.test.ts b/src/server/workflows/agentSignal/__tests__/run.test.tsindex 26738121715..3fbed3ad50d 100644--- a/src/server/workflows/agentSignal/__tests__/run.test.ts+++ b/src/server/workflows/agentSignal/__tests__/run.test.ts@@ -6,10 +6,10 @@ import { agents, messages, threads, topics, users } from '@lobechat/database/schimport { getTestDB } from '@lobechat/database/test-utils';import { describe, expect, it, vi } from 'vitest';-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 { NightlyReviewContext } from '@/server/services/agentSignal/services/maintenance/nightlyCollector';+import type { SelfReflectionReviewContext } from '@/server/services/agentSignal/services/selfIteration/reflection/handler';+import type { NightlyReviewContext } from '@/server/services/agentSignal/services/selfIteration/review/collect';+import { ReviewRunStatus, Scope } from '@/server/services/agentSignal/services/selfIteration/types';import type { AgentSignalPolicyStateStore } from '@/server/services/agentSignal/store/types';import type { RunAgentSignalWorkflowDeps } from '@/server/workflows/agentSignal/run';import { runAgentSignalWorkflow } from '@/server/workflows/agentSignal/run';@@ -55,7 +55,7 @@ const createNightlyReviewContext = (input: {notSatisfied: [],satisfied: [],},- maintenanceSignals: [],+ selfReviewSignals: [],managedSkills: [],proposalActivity: {active: [],@@ -75,6 +75,7 @@ const createNightlyReviewContext = (input: {relevantMemories: [],reviewWindowEnd: input.reviewWindowEnd,reviewWindowStart: input.reviewWindowStart,+ selfFeedbackCandidates: [],toolActivity: [],topics: [],userId: input.userId,@@ -819,18 +820,18 @@ describe('runAgentSignalWorkflow', () => {userId,}),),- runMaintenanceReviewAgent: vi.fn(async () => ({+ runSelfReviewAgent: vi.fn(async () => ({execution: { actions: [], status: ReviewRunStatus.Completed },projectionPlan: {actions: [],plannerVersion: 'test',- reviewScope: MaintenanceReviewScope.Nightly,+ reviewScope: Scope.Nightly,summary: 'Noop',},})),};- const createNightlyReviewPolicyOptions: NonNullable<- RunAgentSignalWorkflowDeps['createNightlyReviewPolicyOptions']+ const createSelfReviewPolicyOptions: NonNullable<+ RunAgentSignalWorkflowDeps['createSelfReviewPolicyOptions']> = vi.fn(() => nightlyReviewPolicyOptions);const executeSourceEvent: NonNullable<RunAgentSignalWorkflowDeps['executeSourceEvent']> = vi.fn(async () => undefined,@@ -852,12 +853,12 @@ describe('runAgentSignalWorkflow', () => {});await runAgentSignalWorkflow(createWorkflowContext({ agentId, sourceEvent, userId }), {- createNightlyReviewPolicyOptions,+ createSelfReviewPolicyOptions,executeSourceEvent,getDb: async () => db,});- expect(createNightlyReviewPolicyOptions).toHaveBeenCalledWith({+ expect(createSelfReviewPolicyOptions).toHaveBeenCalledWith({agentId,db,selfIterationEnabled: true,@@ -894,18 +895,20 @@ describe('runAgentSignalWorkflow', () => {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(() => ({+ executeSelfIteration: vi.fn(async () => ({actions: [],- plannerVersion: 'test',- reviewScope: MaintenanceReviewScope.SelfReflection,- summary: 'Noop',- })),- runMaintenanceReviewAgent: vi.fn(async () => ({- actions: [],- findings: [],- summary: 'Noop',+ content: 'Noop',+ ideas: [],+ intents: [],+ status: ReviewRunStatus.Completed,+ stepCount: 0,+ toolCalls: [],+ usage: [],+ writeOutcomes: [],})),+ model: 'gpt-test',+ modelRuntime: { chat: vi.fn() },+ tools: {} as never,writeReceipt: vi.fn(async () => {}),};const createSelfReflectionPolicyOptions: NonNullable<@@ -957,26 +960,33 @@ describe('runAgentSignalWorkflow', () => {);});- it('installs self-iteration intent policy dependencies for declared intent sources', async () => {+ it('installs self-feedback 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 = {+ const sourceId = `self-feedback-intent:${userId}:${agentId}:topic:topic-1:tool-call-1`;+ const selfFeedbackIntentPolicyOptions = {acquireReviewGuard: vi.fn(async () => true),canRunReview: vi.fn(async () => true),- executePlan: vi.fn(async () => ({ actions: [], status: ReviewRunStatus.Completed })),- planReviewOutput: vi.fn(() => ({+ executeSelfIteration: vi.fn(async () => ({actions: [],- plannerVersion: 'test',- reviewScope: MaintenanceReviewScope.SelfIterationIntent,- summary: 'Noop',+ content: 'Noop',+ ideas: [],+ intents: [],+ status: ReviewRunStatus.Completed,+ stepCount: 0,+ toolCalls: [],+ usage: [],+ writeOutcomes: [],})),+ model: 'gpt-test',+ modelRuntime: { chat: vi.fn() },+ tools: {} as never,writeReceipt: vi.fn(async () => {}),};- const createSelfIterationIntentPolicyOptions: NonNullable<- RunAgentSignalWorkflowDeps['createSelfIterationIntentPolicyOptions']- > = vi.fn(() => selfIterationIntentPolicyOptions);+ const createSelfFeedbackIntentPolicyOptions: NonNullable<+ RunAgentSignalWorkflowDeps['createSelfFeedbackIntentPolicyOptions']+ > = vi.fn(() => selfFeedbackIntentPolicyOptions);const executeSourceEvent: NonNullable<RunAgentSignalWorkflowDeps['executeSourceEvent']> = vi.fn(async () => undefined,);@@ -996,17 +1006,17 @@ describe('runAgentSignalWorkflow', () => {},scopeKey: 'topic:topic-1',sourceId,- sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentSelfIterationIntentDeclared,+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentSelfFeedbackIntentDeclared,timestamp: Date.now(),});await runAgentSignalWorkflow(createWorkflowContext({ agentId, sourceEvent, userId }), {- createSelfIterationIntentPolicyOptions,+ createSelfFeedbackIntentPolicyOptions,executeSourceEvent,getDb: async () => db,});- expect(createSelfIterationIntentPolicyOptions).toHaveBeenCalledWith({+ expect(createSelfFeedbackIntentPolicyOptions).toHaveBeenCalledWith({agentId,db,selfIterationEnabled: true,@@ -1017,7 +1027,7 @@ describe('runAgentSignalWorkflow', () => {expect.any(Object),expect.objectContaining({policyOptions: expect.objectContaining({- selfIterationIntent: selfIterationIntentPolicyOptions,+ selfFeedbackIntent: selfFeedbackIntentPolicyOptions,skillManagement: {selfIterationEnabled: true,},diff --git a/src/server/workflows/agentSignal/run.ts b/src/server/workflows/agentSignal/run.tsindex 10fa01930da..d3b971cdaa1 100644--- a/src/server/workflows/agentSignal/run.ts+++ b/src/server/workflows/agentSignal/run.ts@@ -7,7 +7,7 @@ import {isAgentUserMessageSource,isClientRuntimeStartSource,isNightlyReviewSource,- isSelfIterationIntentSource,+ isSelfFeedbackIntentSource,isSelfReflectionSource,isToolOutcomeSource,} from '@lobechat/agent-signal/source';@@ -32,12 +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 { createServerSelfFeedbackIntentPolicyOptions } from '@/server/services/agentSignal/services/selfIteration/feedback/server';import {- createServerNightlyReviewPolicyOptions,createServerProcedurePolicyOptions,- createServerSelfIterationIntentPolicyOptions,createServerSelfReflectionPolicyOptions,-} from '@/server/services/agentSignal/services/maintenance/serverRuntime';+} from '@/server/services/agentSignal/services/selfIteration/reflection/server';+import { createServerSelfReviewPolicyOptions } from '@/server/services/agentSignal/services/selfIteration/review/server';import type { ClientRuntimeCompleteHydrationDiagnostic } from '@/server/services/agentSignal/sources/hydration/clientRuntimeComplete';import { resolveClientRuntimeCompleteFeedbackSource } from '@/server/services/agentSignal/sources/hydration/clientRuntimeComplete';import type { ClientRuntimeStartHydrationDiagnostic } from '@/server/services/agentSignal/sources/hydration/clientRuntimeStart';@@ -80,11 +80,11 @@ 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;+ createSelfFeedbackIntentPolicyOptions?: typeof createServerSelfFeedbackIntentPolicyOptions;createSelfReflectionPolicyOptions?: typeof createServerSelfReflectionPolicyOptions;+ createSelfReviewPolicyOptions?: typeof createServerSelfReviewPolicyOptions;createSnapshotStore?: () => ISnapshotStore | null;executeSourceEvent?: typeof executeAgentSignalSourceEvent;getDb?: typeof getServerDB;@@ -495,13 +495,13 @@ export const runAgentSignalWorkflow = async (const getDb = deps.getDb ?? getServerDB;const executeSourceEvent = deps.executeSourceEvent ?? executeAgentSignalSourceEvent;- const createNightlyReviewPolicyOptions =- deps.createNightlyReviewPolicyOptions ?? createServerNightlyReviewPolicyOptions;+ const createSelfReviewPolicyOptions =+ deps.createSelfReviewPolicyOptions ?? createServerSelfReviewPolicyOptions;const createSelfReflectionPolicyOptions =deps.createSelfReflectionPolicyOptions ?? createServerSelfReflectionPolicyOptions;- const createSelfIterationIntentPolicyOptions =- deps.createSelfIterationIntentPolicyOptions ??- createServerSelfIterationIntentPolicyOptions;+ const createSelfFeedbackIntentPolicyOptions =+ deps.createSelfFeedbackIntentPolicyOptions ??+ createServerSelfFeedbackIntentPolicyOptions;const createProcedurePolicyOptions =deps.createProcedurePolicyOptions ?? createServerProcedurePolicyOptions;const createGuardBackend =@@ -562,7 +562,7 @@ export const runAgentSignalWorkflow = async (async (executeSpan) => {try {const nightlyReview = isNightlyReviewSource(normalizedSourceEvent)- ? createNightlyReviewPolicyOptions({+ ? createSelfReviewPolicyOptions({agentId: payload.agentId,db,selfIterationEnabled,@@ -577,8 +577,8 @@ export const runAgentSignalWorkflow = async (userId: payload.userId,}): undefined;- const selfIterationIntent = isSelfIterationIntentSource(normalizedSourceEvent)- ? createSelfIterationIntentPolicyOptions({+ const selfFeedbackIntent = isSelfFeedbackIntentSource(normalizedSourceEvent)+ ? createSelfFeedbackIntentPolicyOptions({agentId: payload.agentId,db,selfIterationEnabled,@@ -607,7 +607,7 @@ export const runAgentSignalWorkflow = async (policyOptions: {...(nightlyReview ? { nightlyReview } : {}),...(procedure ? { procedure } : {}),- ...(selfIterationIntent ? { selfIterationIntent } : {}),+ ...(selfFeedbackIntent ? { selfFeedbackIntent } : {}),...(selfReflection ? { selfReflection } : {}),skillManagement: {selfIterationEnabled,