/**
* Synthesis generation for multi-persona thinking
*/
/**
* Generate final synthesis from all persona analyses and contradictions
*/
export async function generateSynthesis(topic, personaAnalysis, contradictions, pollinationsAPI) {
const allInsights = [];
const allRecommendations = [];
const allConcerns = [];
// Collect all insights from all cycles
personaAnalysis.forEach(cycle => {
cycle.personas.forEach(persona => {
allInsights.push(...persona.keyInsights);
allRecommendations.push(...persona.recommendations);
allConcerns.push(...persona.concerns);
});
});
// Prepare synthesis prompt
let synthesisPrompt = `You are a strategic synthesis expert. Analyze the following multi-perspective thinking session and create a comprehensive strategic synthesis.\n\n`;
synthesisPrompt += `Topic: "${topic}"\n\n`;
synthesisPrompt += `MULTI-PERSONA ANALYSIS SUMMARY:\n`;
personaAnalysis.forEach((cycle, index) => {
synthesisPrompt += `\nCycle ${index + 1}:\n`;
cycle.personas.forEach(persona => {
synthesisPrompt += `${persona.persona} (${persona.focus}):\n`;
synthesisPrompt += `- Key insights: ${persona.keyInsights.slice(0, 2).join('; ')}\n`;
synthesisPrompt += `- Recommendations: ${persona.recommendations.slice(0, 2).join('; ')}\n`;
});
});
synthesisPrompt += `\nIDENTIFIED CONTRADICTIONS:\n`;
contradictions.forEach((cycleContradictions, index) => {
if (cycleContradictions.contradictions.length > 0) {
synthesisPrompt += `Cycle ${index + 1}: ${cycleContradictions.contradictions.length} contradictions found\n`;
cycleContradictions.contradictions.forEach(contradiction => {
synthesisPrompt += `- ${contradiction.description}\n`;
});
}
});
synthesisPrompt += `\nYour task is to create a strategic synthesis that:\n`;
synthesisPrompt += `1. Reconciles the contradictions into a balanced perspective\n`;
synthesisPrompt += `2. Identifies the strongest strategic insights across all personas\n`;
synthesisPrompt += `3. Provides a clear, actionable strategic recommendation\n`;
synthesisPrompt += `4. Acknowledges key risks and mitigation strategies\n`;
synthesisPrompt += `5. Suggests next steps for implementation\n\n`;
synthesisPrompt += `Format your response as:\n`;
synthesisPrompt += `## Strategic Synthesis\n`;
synthesisPrompt += `### Core Strategic Insight\n`;
synthesisPrompt += `### Balanced Perspective (addressing contradictions)\n`;
synthesisPrompt += `### Primary Recommendation\n`;
synthesisPrompt += `### Risk Mitigation\n`;
synthesisPrompt += `### Next Steps\n`;
synthesisPrompt += `### Success Indicators\n\n`;
synthesisPrompt += `Be strategic, actionable, and synthesize the best thinking from all perspectives.`;
try {
const synthesisResponse = await pollinationsAPI(synthesisPrompt);
return {
rawSynthesis: synthesisResponse,
structuredSynthesis: parseSynthesis(synthesisResponse),
contradictionsAddressed: contradictions.reduce((total, cycle) => total + cycle.contradictions.length, 0),
totalInsights: allInsights.length,
totalRecommendations: allRecommendations.length,
timestamp: new Date().toISOString()
};
} catch (error) {
return {
error: error.message,
fallbackSynthesis: generateFallbackSynthesis(allInsights, allRecommendations, allConcerns),
timestamp: new Date().toISOString()
};
}
}
/**
* Parse synthesis response into structured format
*/
function parseSynthesis(synthesisText) {
const sections = {
coreInsight: '',
balancedPerspective: '',
primaryRecommendation: '',
riskMitigation: '',
nextSteps: [],
successIndicators: []
};
const lines = synthesisText.split('\n');
let currentSection = null;
for (const line of lines) {
const trimmed = line.trim();
if (trimmed.includes('Core Strategic Insight')) {
currentSection = 'coreInsight';
} else if (trimmed.includes('Balanced Perspective')) {
currentSection = 'balancedPerspective';
} else if (trimmed.includes('Primary Recommendation')) {
currentSection = 'primaryRecommendation';
} else if (trimmed.includes('Risk Mitigation')) {
currentSection = 'riskMitigation';
} else if (trimmed.includes('Next Steps')) {
currentSection = 'nextSteps';
} else if (trimmed.includes('Success Indicators')) {
currentSection = 'successIndicators';
} else if (trimmed && !trimmed.startsWith('#')) {
if (currentSection === 'nextSteps' || currentSection === 'successIndicators') {
if (trimmed.startsWith('-') || trimmed.startsWith('•') || trimmed.match(/^\d+\./)) {
const content = trimmed.replace(/^[-•]\s*|^\d+\.\s*/, '').trim();
sections[currentSection].push(content);
}
} else if (currentSection) {
sections[currentSection] += (sections[currentSection] ? ' ' : '') + trimmed;
}
}
}
return sections;
}
/**
* Generate fallback synthesis if API call fails
*/
function generateFallbackSynthesis(insights, recommendations, concerns) {
return {
coreInsight: `Based on multi-perspective analysis of ${insights.length} insights`,
balancedPerspective: 'Multiple viewpoints considered with contradictions identified',
primaryRecommendation: recommendations.length > 0 ? recommendations[0] : 'Further analysis needed',
riskMitigation: concerns.length > 0 ? concerns.slice(0, 2).join('; ') : 'Standard risk assessment required',
nextSteps: ['Review detailed analysis', 'Validate assumptions', 'Develop implementation plan'],
successIndicators: ['Clear progress metrics', 'Stakeholder alignment', 'Measurable outcomes']
};
}