import { Injectable, Logger } from '@nestjs/common'; import { PrismaService } from '../../infrastructure/database/prisma.service'; import { KnowledgeImportWorkflow } from '../ai/workflows/knowledge-import.workflow'; import type { KnowledgeGenerationSnapshot } from './knowledge-generation-snapshot-builder'; @Injectable() export class KnowledgeGenerationExecutor { private readonly logger = new Logger(KnowledgeGenerationExecutor.name); constructor( private readonly prisma: PrismaService, private readonly workflow: KnowledgeImportWorkflow, ) {} async execute(snapshot: KnowledgeGenerationSnapshot, aiJobId: string) { const { taskId, sourceId, knowledgeBaseId, userId, rawText, sourceName } = snapshot.snapshot; const txOps = [ this.prisma.knowledgeGenerationTask.updateMany({ where: { id: taskId, aiJobId, status: { in: ['queued', 'running'] } }, data: { status: 'running', startedAt: new Date(), errorCode: null, errorMessage: null, }, }), ]; if (sourceId) { txOps.push( this.prisma.knowledgeSource.updateMany({ where: { id: sourceId, knowledgeBaseId, userId }, data: { learningStatus: 'running' }, }), ); } await this.prisma.$transaction(txOps); const result = await this.workflow.execute({ userId, rawText, sourceName, }); this.logger.log( `Knowledge Generation Executor completed: job=${aiJobId} ` + `task=${taskId} source=${sourceId ?? 'n/a'} points=${result.knowledgePoints?.length ?? 0}`, ); return { parsed: result }; } }