@@ -162,19 +162,37 @@ export async function POST(request: NextRequest, { params }: { params: Promise<{
162162 }
163163
164164 const tagSlotMapping : Record < string , string > = { }
165+ const newTagSlotMapping : Record < string , string > = { }
165166
166167 if ( connectorConfig . tagDefinitions ?. length ) {
167168 const disabledIds = new Set ( ( sourceConfig . disabledTagIds as string [ ] | undefined ) ?? [ ] )
168169 const enabledDefs = connectorConfig . tagDefinitions . filter ( ( td ) => ! disabledIds . has ( td . id ) )
169170
170171 const existingDefs = await db
171- . select ( { tagSlot : knowledgeBaseTagDefinitions . tagSlot } )
172+ . select ( {
173+ tagSlot : knowledgeBaseTagDefinitions . tagSlot ,
174+ displayName : knowledgeBaseTagDefinitions . displayName ,
175+ } )
172176 . from ( knowledgeBaseTagDefinitions )
173177 . where ( eq ( knowledgeBaseTagDefinitions . knowledgeBaseId , knowledgeBaseId ) )
174178
175179 const usedSlots = new Set < string > ( existingDefs . map ( ( d ) => d . tagSlot ) )
176- const { mapping, skipped : skippedTags } = allocateTagSlots ( enabledDefs , usedSlots )
180+ const existingByName = new Map ( existingDefs . map ( ( d ) => [ d . displayName , d . tagSlot ] ) )
181+
182+ /** Reuse existing tag definitions that match by display name */
183+ const defsNeedingSlots : typeof enabledDefs = [ ]
184+ for ( const td of enabledDefs ) {
185+ const existingSlot = existingByName . get ( td . displayName )
186+ if ( existingSlot ) {
187+ tagSlotMapping [ td . id ] = existingSlot
188+ } else {
189+ defsNeedingSlots . push ( td )
190+ }
191+ }
192+
193+ const { mapping, skipped : skippedTags } = allocateTagSlots ( defsNeedingSlots , usedSlots )
177194 Object . assign ( tagSlotMapping , mapping )
195+ Object . assign ( newTagSlotMapping , mapping )
178196
179197 for ( const name of skippedTags ) {
180198 logger . warn ( `[${ requestId } ] No available slots for "${ name } "` )
@@ -208,7 +226,7 @@ export async function POST(request: NextRequest, { params }: { params: Promise<{
208226 throw new Error ( 'Knowledge base not found' )
209227 }
210228
211- for ( const [ semanticId , slot ] of Object . entries ( tagSlotMapping ) ) {
229+ for ( const [ semanticId , slot ] of Object . entries ( newTagSlotMapping ) ) {
212230 const td = connectorConfig . tagDefinitions ! . find ( ( d ) => d . id === semanticId ) !
213231 await createTagDefinition (
214232 {
0 commit comments