virtue-cli
Version:
Personal character development CLI tool for tracking virtues and philosophical alignment
990 lines (893 loc) • 82.5 kB
JavaScript
import { log } from '@clack/prompts';
import Anthropic from '@anthropic-ai/sdk';
import { getCoreVirtues, validateVirtueWeights } from '../core/CoreVirtues.js';
export class ClaudeService {
isClaudeCodeEnvironment;
anthropic = null;
constructor() {
// Detect if we're running inside Claude Code environment
this.isClaudeCodeEnvironment = this.detectClaudeCodeEnvironment();
// Initialize Anthropic client if API key is available
if (process.env.ANTHROPIC_API_KEY) {
this.anthropic = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY,
});
}
}
detectClaudeCodeEnvironment() {
// Claude Code detection - check if we're running in the Claude Code environment
// This is a more conservative check - we assume we're in Claude Code if running in development
return !!(process.env.NODE_ENV === 'development' ||
process.env.CLAUDE_CODE_SESSION ||
process.env.ANTHROPIC_API_KEY ||
process.env.CLAUDE_API_URL ||
global.claudeCode);
}
isConfigured() {
return this.isClaudeCodeEnvironment || !!this.anthropic;
}
async startPhilosophicalDiscovery(initialResponses) {
if (!this.isConfigured()) {
throw new Error('Claude API not configured');
}
const prompt = `# Philosophical Virtue Framework Discovery
You are an expert philosopher and ethicist helping someone discover their personal virtue framework through guided questioning. Your goal is to understand their philosophical inclinations and derive a coherent, actionable virtue system.
## Framework Context
You will be helping create a **3-level hierarchical virtue framework**:
**Level 1 (Core Virtues)**: 4-8 fundamental virtues that capture the person's moral essence
- Examples: Intellectual Honesty, Compassionate Action, Courageous Authenticity, Mindful Presence
- Each has a clear definition and priority weight (0.5-1.0)
- These are treated as orthogonal dimensions in a high-dimensional virtue space
**Level 2 (Sub-Dimensions)**: 2-4 component aspects for each core virtue
- Examples: Under "Intellectual Honesty" → Truth-Seeking, Cognitive Humility, Bias Recognition, Evidence Integration
- These are orthogonal dimensions that mathematically decompose the virtue
- Each can be independently developed and measured
**Level 3 (Practical Skills)**: Specific, measurable behaviors for each sub-dimension
- Examples: Under "Truth-Seeking" → Active Research, Source Verification, Questioning Assumptions, Perspective Integration
- These are concrete actions the person can practice and track daily
- Must be observable and quantifiable for the want-pull scoring system
## Mathematical Integration Notes
This framework uses cosine similarity for daily want-pull alignment tracking, with:
- Want Vector: Conscious aspirations and intentions (psychological)
- Pull Vector: Automatic responses and behaviors (physiological)
- The goal is to minimize ||Want - Pull|| across all virtue dimensions
- Each virtue operates as an orthogonal dimension to avoid mathematical dependencies
## Initial Responses Analysis
${initialResponses.map(r => `- ${r.question}: ${Array.isArray(r.answer) ? r.answer.join(', ') : r.answer}`).join('\n')}
## Advanced Personalization Instructions
This is a CRITICAL setup phase. You must create questions that deeply explore their philosophical foundations and help generate accurate virtue definitions. Analyze their responses and craft questions that:
### Primary Goals:
1. **Definition Exploration**: Understand how they personally define virtues and character traits
2. **Value Hierarchies**: Identify what matters most in their moral reasoning
3. **Applied Ethics**: See how they handle real-world moral complexity
4. **Personal Philosophy**: Understand their underlying worldview and principles
### Analysis Framework:
- **Truth vs Kindness**: ${initialResponses.find(r => r.question === 'Truth vs Kindness')?.answer || 'unknown'}
- **Decision Style**: ${initialResponses.find(r => r.question === 'Decision Making')?.answer || 'unknown'}
- **Growth Focus**: ${initialResponses.find(r => r.question === 'Growth Focus')?.answer || 'unknown'}
- **Top Character Aspects**: ${Array.isArray(initialResponses.find(r => r.question === 'Character Aspect Rankings')?.answer) ? (initialResponses.find(r => r.question === 'Character Aspect Rankings')?.answer).slice(0, 3).join(', ') : 'unknown'}
### Comprehensive Question Bank by Category:
**Core Definition Questions** (Priority - essential for personalization):
- "When you think about [their top virtue/aspect], what comes to mind? Is it more about [specific options based on their responses]?"
- "In your cultural or family background, who would be considered [virtuous in their top area]? What made them that way?"
- "How do you distinguish between [top aspect] and [related concept]? What's the difference for you?"
- "What does '[aspect they ranked highly]' mean to you personally versus how society typically defines it?"
**Cultural & Context Questions**:
- "How do these character traits show up differently in your work versus personal relationships?"
- "What role does your cultural background play in how you understand [their priority virtue]?"
- "Given your current life stage, how have your definitions of character evolved?"
**Applied Ethics & Boundaries**:
- "When might [their top virtue] go too far? How do you know when it becomes a weakness?"
- "Describe a recent situation where you had to choose between [their #1 and #2 aspects]. How did you decide?"
- "What makes [their challenge area] most difficult for you? What gets in the way?"
**Personal Integration Questions**:
- "How do [their top 3 aspects] work together in your ideal character?"
- "What would someone notice if they watched you embody [their priority virtue] at your best?"
- "Tell me about a time you felt you acted against your values. What did you learn about yourself?"
**Measurement & Daily Practice**:
- "In your daily life, what would help you recognize when you're embodying [virtue] versus when you're falling short?"
- "What does a 3/10 versus 8/10 day look like for [their top aspect] in your actual context?"
- "What patterns or triggers tend to make [virtue] more difficult for you to embody?"
**Deeper Philosophical Exploration**:
- "Who or what most influenced your understanding of right and wrong?"
- "How do you handle the tension between being [their preference] while also being [competing value]?"
- "What experiences have most shaped your current understanding of [their priority area]?"
Select questions that:
1. Build directly on their specific initial responses
2. Explore definitions rather than just applications
3. Honor their cultural and personal context
4. Help distinguish between overlapping concepts
5. Reveal what makes virtue personally meaningful to them
Respond with a JSON object:
{
"nextQuestion": "Your chosen opening question here",
"isComplete": false,
"phase": 1,
"reasoning": "Brief explanation of why you chose this specific question based on their initial responses"
}`;
try {
const response = await this.callClaudeAPI(prompt);
return this.extractJSON(response);
}
catch (error) {
log.error('Failed to start philosophical discovery: ' + error);
throw error;
}
}
async continuePhilosophicalDiscovery(conversationHistory, currentPhase) {
if (!this.isConfigured()) {
throw new Error('Claude API not configured');
}
const prompt = `# Philosophical Virtue Framework Discovery - Follow-Up Analysis
## Complete Conversation History
${conversationHistory.map(r => `Q: ${r.question}\nA: ${Array.isArray(r.answer) ? r.answer.join(', ') : r.answer}`).join('\n\n')}
## Current Phase: ${currentPhase}/3
## Critical Phase ${currentPhase}/3 - Definition Discovery Instructions
This phase is ESSENTIAL for creating accurate virtue definitions. You must craft questions that deeply explore their personal understanding of character and values.
### Phase Goals by Number:
**Phase 1**: Definition Foundation - How do they personally define key character traits?
**Phase 2**: Values Integration - How do different virtues interact in their worldview?
**Phase 3**: Applied Philosophy - How do they live these values in complex situations?
### Conversation Analysis:
${conversationHistory.map(r => `- ${r.question}: ${Array.isArray(r.answer) ? r.answer.join(' | ') : r.answer}`).join('\n')}
### Required Question Types by Phase:
**Phase 1 Questions** (Definition Foundation):
- Core Understanding: "When you think about [their top virtue/aspect], what comes to mind? Is it more about [specific options based on responses]?"
- Cultural Context: "In your cultural or family background, who embodies [their priority trait]? What makes them that way?"
- Personal Definition: "How would you define [aspect] in your own words, different from how most people see it?"
- Distinctions: "What's the difference between [trait A] and [trait B] in your view? How do you tell them apart?"
- Boundaries: "When might [their top virtue] go too far? How do you know when it becomes unhelpful?"
**Phase 2 Questions** (Values Integration):
- Conflict Resolution: "When [virtue A] conflicts with [virtue B], how do you decide which takes priority?"
- Synergy Exploration: "How do [their top 3 aspects] work together in your ideal character?"
- Context Sensitivity: "Does [their priority virtue] look different in work versus personal relationships? How so?"
- Value Evolution: "How has your understanding of [virtue] changed as you've grown?"
- Cultural Integration: "How does your [cultural/professional] background influence your approach to [virtue]?"
**Phase 3 Questions** (Applied Philosophy & Daily Practice):
- Difficult Embodiment: "Describe a time when living by [their value] was challenging but important."
- Practical Recognition: "In daily life, what helps you recognize when you're embodying [virtue] vs. falling short?"
- Observable Behavior: "What would someone notice if they watched you embody [virtue] at your best?"
- Measurement Guidance: "What does a 3/10 versus 8/10 day look like for [aspect] in your actual life?"
- Challenge Patterns: "What situations or triggers make [virtue] most difficult for you to embody?"
- Growth Integration: "How do you stay authentic to yourself while growing in [challenging virtue area]?"
### Mandatory Analysis Points:
1. **Their Definition Gaps**: What virtues haven't they defined clearly yet?
2. **Unresolved Tensions**: Where do their stated values conflict?
3. **Personal Examples**: What specific stories reveal their character?
4. **Practical Application**: How do they actually live these values?
Generate a question that directly builds on their previous answer and explores their PERSONAL definitions of character.
## Analysis Framework
Based on their specific responses, analyze for:
1. **Emerging Metaethical Patterns**:
- Are they primarily consequentialist (outcome-focused)?
- Deontological (rule/duty-focused)?
- Virtue ethics oriented (character-focused)?
- Existentialist (authenticity-focused)?
- Pragmatist (effectiveness-focused)?
2. **Moral Foundation Priorities** (rate 0-1):
- Care/Harm: How much do they prioritize protecting others from suffering?
- Fairness/Cheating: How important is justice and reciprocity?
- Loyalty/Betrayal: How much do they value group commitment?
- Authority/Subversion: What's their relationship to hierarchy and tradition?
- Sanctity/Degradation: Do they have strong purity/sacred concerns?
- Liberty/Oppression: How important is freedom from domination?
3. **Foundation-Specific Questions** to choose from based on uncertainty:
**Care Foundation:**
- "Save one person you love or five strangers?"
- "Should you prioritize helping others even when you're struggling yourself?"
**Fairness Foundation:**
- "Give everyone the same, or give people what they need?"
- "What's more important: fair process or fair outcome?"
**Loyalty Foundation:**
- "Your friend did something wrong. Do you cover for them or tell the truth?"
- "Your friend and a stranger both need help. You can only help one. Who do you choose?"
**Authority Foundation:**
- "Break a rule that doesn't make sense, or follow it anyway?"
- "Should experts have more say in decisions than regular people?"
**Liberty Foundation:**
- "More safety with less freedom, or more freedom with less safety?"
- "Let people make bad choices, or protect them from themselves?"
**Sanctity Foundation:**
- "Are there things you should never do, even for a good cause?"
## Phase Guidelines
**Phase 1**: Focus on moral intuitions, emotional resonance, core motivations
**Phase 2**: Explore philosophical influences, systematic thinking, complexity handling
**Phase 3**: Clarify practical applications, development priorities, life integration
## Response Format
If continuing conversation (typically 1-3 more questions needed):
{
"nextQuestion": "Your selected crisp question from the bank above",
"isComplete": false,
"phase": ${currentPhase},
"reasoning": "Why this specific question based on their response pattern",
"foundationHypotheses": {
"care": 0.7,
"fairness": 0.8,
"loyalty": 0.4,
"authority": 0.3,
"sanctity": 0.2,
"liberty": 0.9
},
"detectedPatterns": ["Quick", "decisive", "responses", "suggest", "clear", "value", "hierarchy"]
}
If ready for virtue framework generation (usually after 4-6 crisp exchanges):
{
"isComplete": true,
"phase": "complete",
"readyForFrameworkGeneration": true,
"conversationSummary": "Brief summary of their revealed value priorities and reasoning patterns"
}`;
try {
const response = await this.callClaudeAPI(prompt);
return this.extractJSON(response);
}
catch (error) {
log.error('Failed to continue philosophical discovery: ' + error);
throw error;
}
}
async deriveVirtueFramework(conversationHistory) {
if (!this.isConfigured()) {
throw new Error('Claude API not configured');
}
const prompt = `# Virtue Framework Derivation from Philosophical Profile
## Complete Conversation History
${conversationHistory.map(r => `Q: ${r.question}\nA: ${Array.isArray(r.answer) ? r.answer.join(', ') : r.answer}`).join('\n\n')}
## Derivation Instructions
Based on this philosophical exploration, derive a personalized 3-level virtue framework that is:
- **Mathematically Coherent**: Each virtue operates as an orthogonal dimension
- **Personally Authentic**: Genuinely reflects their expressed values and reasoning patterns
- **Practically Actionable**: Can be tracked daily using want-pull scoring
- **Philosophically Grounded**: Consistent with their metaethical framework and moral foundations
## Analysis Process
**Step 1: Philosophical Profile Assessment**
Analyze their responses to determine:
- Primary metaethical framework (consequentialist/deontological/virtue ethics/existentialist/pragmatist)
- Moral foundation priorities (0-1 scale for each of Haidt's 6 foundations)
- Cultural and philosophical influences mentioned or implied
- Personality indicators relevant to virtue development
- Contextual priorities across life domains
**Step 2: Core Virtue Identification (Level 1)**
Derive 4-6 core virtues that:
- Authentically represent their deepest values and moral commitments
- Are philosophically coherent with their worldview and reasoning style
- Are orthogonal to each other (independent dimensions)
- Are actionable in daily life with clear behavioral manifestations
- Cover the breadth of their moral concerns without redundancy
**Step 3: Sub-Dimension Decomposition (Level 2)**
For each core virtue, identify 2-4 component dimensions that:
- Are mathematically orthogonal to each other
- Comprehensively span the virtue's scope
- Are specific enough to be independently developed
- Connect to observable behaviors and practices
**Step 4: Practical Skills Identification (Level 3)**
For each sub-dimension, identify 2-4 concrete skills that:
- Are observable, measurable behaviors
- Can be practiced and developed daily
- Are relevant to their specific life context and challenges
- Support the want-pull scoring methodology
## Output Format
{
"philosophicalProfile": {
"metaethicalFramework": "primary framework with confidence score",
"moralFoundations": {
"care": 0.0-1.0,
"fairness": 0.0-1.0,
"loyalty": 0.0-1.0,
"authority": 0.0-1.0,
"sanctity": 0.0-1.0,
"liberty": 0.0-1.0
},
"culturalInfluences": ["specific", "traditions", "mentioned"],
"philosophicalTraditions": ["schools", "of", "thought", "referenced"],
"personalityTraits": {
"reflectiveness": 0.0-1.0,
"systematicThinking": 0.0-1.0,
"practicalOrientation": 0.0-1.0,
"relationalFocus": 0.0-1.0,
"growthMotivation": 0.0-1.0
},
"developmentContext": {
"lifeStage": "their current focus and priorities",
"primaryDomains": ["work", "relationships", "community", "personal"],
"currentChallenges": ["specific", "areas", "they", "mentioned"]
}
},
"derivedFramework": {
"templateName": "Descriptive name that captures their philosophical essence",
"philosophicalBasis": "2-3 sentence explanation connecting their framework to philosophical traditions",
"coreVirtues": [
{
"id": "virtue-1-id",
"name": "Virtue Name (that resonates with their language)",
"definition": "Clear, actionable definition using their terminology and values",
"priority": 0.5-1.0,
"subDimensions": [
{
"name": "Sub-dimension Name",
"definition": "Clear definition of this component",
"practicalSkills": [
{
"name": "Specific Skill Name",
"description": "What this skill involves in practice",
"measurableIndicators": [
"Observable behavior 1 that can be tracked daily",
"Observable behavior 2 that can be tracked daily"
]
}
]
}
],
"derivationReasoning": "Specific explanation of why this virtue emerged from their responses"
}
],
"frameworkCoherence": 0.0-1.0,
"personalRelevance": 0.0-1.0,
"practicalViability": 0.0-1.0
},
"implementationGuidance": {
"startingFocus": "Which virtue or sub-dimension to emphasize first",
"developmentSequence": "Suggested order for developing different aspects",
"contextualAdaptations": {
"work": "How framework applies in professional context",
"relationships": "Application in personal relationships",
"community": "Broader social and civic applications",
"personal": "Individual growth and self-development focus"
},
"potentialChallenges": ["Specific", "obstacles", "based", "on", "their", "responses"],
"strengthsToLeverage": ["Natural", "advantages", "they", "already", "possess"],
"trackingTips": ["Specific", "guidance", "for", "daily", "want-pull", "assessment"]
}
}
Generate a framework that honors both their philosophical sophistication and practical needs for daily virtue development.`;
try {
const response = await this.callClaudeAPI(prompt);
return this.extractJSON(response);
}
catch (error) {
log.error('Failed to derive virtue framework: ' + error);
throw error;
}
}
async deriveVirtuesFromResponses(responses) {
if (!this.isConfigured()) {
// If AI not available, return core virtues with default priorities
return getCoreVirtues();
}
try {
const personalizedVirtues = await this.personalizeVirtues(responses);
// Validate the AI response
if (validateVirtueWeights(personalizedVirtues)) {
return personalizedVirtues;
}
else {
log.warning('AI returned invalid virtue weights, using defaults');
return getCoreVirtues();
}
}
catch (error) {
log.error('Failed to personalize virtues, using core framework: ' + error);
return getCoreVirtues();
}
}
extractEmojiFromName(name) {
// Extract emoji if present in the virtue name
const emojiRegex = /[\u{1F600}-\u{1F64F}]|[\u{1F300}-\u{1F5FF}]|[\u{1F680}-\u{1F6FF}]|[\u{1F700}-\u{1F77F}]|[\u{1F780}-\u{1F7FF}]|[\u{1F800}-\u{1F8FF}]|[\u{2600}-\u{26FF}]|[\u{2700}-\u{27BF}]/gu;
const match = name.match(emojiRegex);
return match ? match[0] : null;
}
extractJSON(response) {
// Try to extract JSON from Claude's response which might contain extra text
// First, try parsing the entire response
try {
return JSON.parse(response.trim());
}
catch {
// If that fails, look for JSON object within the response
}
// Look for JSON object patterns
const jsonPatterns = [
/\{[\s\S]*\}/, // Match { ... }
/\[[\s\S]*\]/, // Match [ ... ]
];
for (const pattern of jsonPatterns) {
const match = response.match(pattern);
if (match) {
try {
return JSON.parse(match[0]);
}
catch {
continue;
}
}
}
// Look for code blocks with json
const codeBlockMatch = response.match(/```(?:json)?\s*(\{[\s\S]*?\}|\[[\s\S]*?\])\s*```/);
if (codeBlockMatch) {
try {
return JSON.parse(codeBlockMatch[1]);
}
catch {
// Continue to other attempts
}
}
// If all else fails, throw the original error
throw new Error('Could not extract valid JSON from response');
}
extractCulturalContext(responses) {
const culturalIndicators = [];
// Look for cultural/family references in responses
const culturalKeywords = ['family', 'culture', 'tradition', 'community', 'background', 'heritage', 'upbringing', 'values', 'beliefs', 'religion', 'spiritual'];
responses.forEach(response => {
const answer = Array.isArray(response.answer) ? response.answer.join(' ') : response.answer;
const lowerAnswer = answer.toLowerCase();
culturalKeywords.forEach(keyword => {
if (lowerAnswer.includes(keyword)) {
culturalIndicators.push(`- References ${keyword} in context: "${response.question}" → "${answer}"`);
}
});
// Identify cultural learning patterns
if (lowerAnswer.includes('elder') || lowerAnswer.includes('mentor') || lowerAnswer.includes('teacher')) {
culturalIndicators.push(`- Values learning from authority figures: "${answer}"`);
}
// Identify collectivist vs individualist tendencies
if (lowerAnswer.includes('community') || lowerAnswer.includes('group') || lowerAnswer.includes('others')) {
culturalIndicators.push(`- Shows collectivist orientation: "${answer}"`);
}
if (lowerAnswer.includes('individual') || lowerAnswer.includes('personal') || lowerAnswer.includes('myself')) {
culturalIndicators.push(`- Shows individualist orientation: "${answer}"`);
}
});
if (culturalIndicators.length === 0) {
return "No explicit cultural references found - use universal virtue language with room for personal interpretation.";
}
return culturalIndicators.join('\n');
}
extractBehavioralIndicators(responses) {
const behavioralPatterns = [];
// Analyze decision-making style
const decisionStyle = responses.find(r => r.question === 'Decision Making')?.answer;
if (decisionStyle) {
behavioralPatterns.push(`- Decision-making style: ${decisionStyle} - tailor behavioral indicators accordingly`);
}
// Analyze growth focus
const growthFocus = responses.find(r => r.question === 'Growth Focus')?.answer;
if (growthFocus) {
behavioralPatterns.push(`- Growth orientation: ${growthFocus} - emphasize behavioral measures in this domain`);
}
// Analyze relationship to truth vs kindness
const truthVsKindness = responses.find(r => r.question === 'Truth vs Kindness')?.answer;
if (truthVsKindness) {
behavioralPatterns.push(`- Moral priority: ${truthVsKindness} - weight behavioral indicators toward this value`);
}
// Look for action-oriented language
responses.forEach(response => {
const answer = Array.isArray(response.answer) ? response.answer.join(' ') : response.answer;
const actionWords = ['do', 'act', 'behave', 'practice', 'implement', 'apply', 'exercise', 'demonstrate'];
actionWords.forEach(word => {
if (answer.toLowerCase().includes(word)) {
behavioralPatterns.push(`- Action-oriented response: "${response.question}" mentions "${word}" in context of "${answer}"`);
}
});
});
// Character aspect rankings reveal behavioral preferences
const rankings = responses.find(r => r.question === 'Character Aspect Rankings')?.answer;
if (Array.isArray(rankings)) {
const topThree = rankings.slice(0, 3);
behavioralPatterns.push(`- Prioritizes behaviors related to: ${topThree.join(', ')} - emphasize concrete behavioral measures for these aspects`);
}
return behavioralPatterns.length > 0 ? behavioralPatterns.join('\n') : "Focus on universal behavioral indicators with room for personal expression.";
}
extractValueHierarchies(responses) {
const valuePatterns = [];
// Truth vs Kindness preference
const truthVsKindness = responses.find(r => r.question === 'Truth vs Kindness')?.answer;
if (truthVsKindness === 'truth') {
valuePatterns.push(`- Values honesty and authenticity highly - prioritize Integrity and Wisdom virtues`);
}
else if (truthVsKindness === 'kindness') {
valuePatterns.push(`- Values compassion and harmony highly - prioritize Compassion and Justice virtues`);
}
// Character aspect rankings reveal value hierarchy
const rankings = responses.find(r => r.question === 'Character Aspect Rankings')?.answer;
if (Array.isArray(rankings)) {
const virtueMapping = {
'Critical Thinking': 'Wisdom',
'Learning Orientation': 'Wisdom',
'Practical Judgment': 'Wisdom',
'Honesty': 'Integrity',
'Authenticity': 'Integrity',
'Reliability': 'Integrity',
'Empathy': 'Compassion',
'Kindness': 'Compassion',
'Service': 'Compassion',
'Fairness': 'Justice',
'Advocacy': 'Justice',
'Responsibility': 'Justice',
'Moral Courage': 'Courage',
'Resilience': 'Courage',
'Initiative': 'Courage'
};
const virtueWeights = {};
rankings.forEach((aspect, index) => {
const virtue = virtueMapping[aspect];
if (virtue) {
virtueWeights[virtue] = (virtueWeights[virtue] || 0) + (15 - index);
}
});
const sortedVirtues = Object.entries(virtueWeights)
.sort(([, a], [, b]) => b - a)
.map(([virtue, weight]) => `${virtue} (${weight})`);
valuePatterns.push(`- Virtue priority based on character aspects: ${sortedVirtues.join(' > ')}`);
}
// Growth focus reveals value emphasis
const growthFocus = responses.find(r => r.question === 'Growth Focus')?.answer;
if (growthFocus === 'intellectual') {
valuePatterns.push(`- Intellectual growth valued - emphasize Wisdom and learning-oriented definitions`);
}
else if (growthFocus === 'emotional') {
valuePatterns.push(`- Emotional growth valued - emphasize Compassion and relationship-oriented definitions`);
}
else if (growthFocus === 'spiritual') {
valuePatterns.push(`- Spiritual growth valued - incorporate transcendent and meaning-oriented language`);
}
else if (growthFocus === 'social') {
valuePatterns.push(`- Social impact valued - emphasize Justice and service-oriented definitions`);
}
return valuePatterns.length > 0 ? valuePatterns.join('\n') : "Balanced approach to all virtues with equal emphasis.";
}
analyzeResponsesStructured(responses) {
const culturalContext = this.analyzeCulturalContext(responses);
const behavioralIndicators = this.analyzeBehavioralIndicators(responses);
const valueHierarchy = this.analyzeValueHierarchy(responses);
// Calculate personalization score based on depth of responses
const personalizationScore = this.calculatePersonalizationScore(responses, culturalContext, behavioralIndicators, valueHierarchy);
// Determine overall depth
const overallDepth = this.determineResponseDepth(responses, personalizationScore);
return {
culturalContext,
behavioralIndicators,
valueHierarchy,
overallDepth,
personalizationScore
};
}
analyzeCulturalContext(responses) {
const culturalKeywords = [];
let collectivistOrientation = false;
let individualistOrientation = false;
let authorityRespect = false;
let communityFocus = false;
let traditionalValues = false;
let spiritualOrientation = false;
const culturalTerms = ['family', 'culture', 'tradition', 'community', 'background', 'heritage', 'upbringing', 'values', 'beliefs', 'religion', 'spiritual'];
responses.forEach(response => {
const answer = Array.isArray(response.answer) ? response.answer.join(' ') : response.answer;
const lowerAnswer = answer.toLowerCase();
// Check for cultural keywords
culturalTerms.forEach(term => {
if (lowerAnswer.includes(term)) {
culturalKeywords.push(term);
}
});
// Detect orientation patterns
if (lowerAnswer.includes('community') || lowerAnswer.includes('group') || lowerAnswer.includes('together') || lowerAnswer.includes('collective')) {
collectivistOrientation = true;
communityFocus = true;
}
if (lowerAnswer.includes('individual') || lowerAnswer.includes('personal') || lowerAnswer.includes('myself') || lowerAnswer.includes('independence')) {
individualistOrientation = true;
}
if (lowerAnswer.includes('elder') || lowerAnswer.includes('authority') || lowerAnswer.includes('mentor') || lowerAnswer.includes('teacher') || lowerAnswer.includes('leader')) {
authorityRespect = true;
}
if (lowerAnswer.includes('tradition') || lowerAnswer.includes('heritage') || lowerAnswer.includes('customs') || lowerAnswer.includes('ancestral')) {
traditionalValues = true;
}
if (lowerAnswer.includes('spiritual') || lowerAnswer.includes('religion') || lowerAnswer.includes('faith') || lowerAnswer.includes('sacred') || lowerAnswer.includes('divine')) {
spiritualOrientation = true;
}
});
return {
collectivistOrientation,
individualistOrientation,
authorityRespect,
communityFocus,
culturalKeywords: [...new Set(culturalKeywords)], // Remove duplicates
traditionalValues,
spiritualOrientation
};
}
analyzeBehavioralIndicators(responses) {
const actionWords = ['do', 'act', 'behave', 'practice', 'implement', 'apply', 'exercise', 'demonstrate'];
const actionOrientation = [];
// Extract structured responses
const decisionMakingResponse = responses.find(r => r.question === 'Decision Making');
const growthResponse = responses.find(r => r.question === 'Growth Focus');
const truthKindnessResponse = responses.find(r => r.question === 'Truth vs Kindness');
const rankingsResponse = responses.find(r => r.question === 'Character Aspect Rankings');
// Look for action-oriented language
responses.forEach(response => {
const answer = Array.isArray(response.answer) ? response.answer.join(' ') : response.answer;
actionWords.forEach(word => {
if (answer.toLowerCase().includes(word)) {
actionOrientation.push(`${word} (from: ${response.question})`);
}
});
});
const prioritizedBehaviors = Array.isArray(rankingsResponse?.answer)
? rankingsResponse.answer.slice(0, 3)
: [];
return {
decisionMakingStyle: decisionMakingResponse?.answer || null,
growthOrientation: growthResponse?.answer || null,
moralPriority: truthKindnessResponse?.answer || null,
actionOrientation: [...new Set(actionOrientation)],
prioritizedBehaviors
};
}
analyzeValueHierarchy(responses) {
const truthKindnessResponse = responses.find(r => r.question === 'Truth vs Kindness');
const rankingsResponse = responses.find(r => r.question === 'Character Aspect Rankings');
const growthResponse = responses.find(r => r.question === 'Growth Focus');
const virtueMapping = {
'Critical Thinking': 'Wisdom',
'Learning Orientation': 'Wisdom',
'Practical Judgment': 'Wisdom',
'Honesty': 'Integrity',
'Authenticity': 'Integrity',
'Reliability': 'Integrity',
'Empathy': 'Compassion',
'Kindness': 'Compassion',
'Service': 'Compassion',
'Fairness': 'Justice',
'Advocacy': 'Justice',
'Responsibility': 'Justice',
'Moral Courage': 'Courage',
'Resilience': 'Courage',
'Initiative': 'Courage'
};
const virtueWeights = {};
// Calculate weights from character aspect rankings
if (Array.isArray(rankingsResponse?.answer)) {
rankingsResponse.answer.forEach((aspect, index) => {
const virtue = virtueMapping[aspect];
if (virtue) {
virtueWeights[virtue] = (virtueWeights[virtue] || 0) + (15 - index);
}
});
}
const emphasisAreas = [];
if (growthResponse?.answer) {
emphasisAreas.push(`${growthResponse.answer} growth`);
}
const balancedApproach = Object.keys(virtueWeights).length === 0;
return {
truthVsKindnessPreference: truthKindnessResponse?.answer || null,
virtueWeights,
emphasisAreas,
balancedApproach
};
}
calculatePersonalizationScore(responses, cultural, behavioral, values) {
let score = 0;
let maxScore = 0;
// Cultural context indicators (30% of score)
maxScore += 30;
if (cultural.culturalKeywords.length > 0)
score += 10;
if (cultural.collectivistOrientation || cultural.individualistOrientation)
score += 10;
if (cultural.authorityRespect || cultural.traditionalValues || cultural.spiritualOrientation)
score += 10;
// Behavioral indicators (40% of score)
maxScore += 40;
if (behavioral.decisionMakingStyle)
score += 10;
if (behavioral.growthOrientation)
score += 10;
if (behavioral.actionOrientation.length > 0)
score += 10;
if (behavioral.prioritizedBehaviors.length > 0)
score += 10;
// Value hierarchy (30% of score)
maxScore += 30;
if (values.truthVsKindnessPreference)
score += 10;
if (Object.keys(values.virtueWeights).length > 0)
score += 10;
if (values.emphasisAreas.length > 0)
score += 10;
return score / maxScore;
}
determineResponseDepth(responses, personalizationScore) {
if (personalizationScore >= 0.8)
return 'deep';
if (personalizationScore >= 0.5)
return 'moderate';
return 'surface';
}
enhanceResponses(responses) {
const analysis = this.analyzeResponsesStructured(responses);
return responses.map((response, index) => ({
...response,
culturalContext: analysis.culturalContext,
behavioralIndicators: analysis.behavioralIndicators,
valueHierarchy: analysis.valueHierarchy,
timestamp: new Date(),
phase: Math.floor(index / 5) + 1, // Approximate phase based on question order
responseDepth: analysis.overallDepth
}));
}
async personalizeVirtues(responses) {
const prompt = `# Virtue Definition Discovery Framework
## System Context
You are helping someone create highly personalized, actionable definitions and behavioral indicators for these five core virtues and their sub-dimensions: **Wisdom, Integrity, Compassion, Justice, and Courage**. These definitions will be used in a daily tracking system where the person rates their psychological want (aspiration/intention) and physiological pull (automatic behavior) for each virtue on a 0-10 scale.
**Enhanced Discovery Process**: This comprehensive 15-25 question discovery ensures we have enough detail to create truly personalized indicators that reflect their specific life context, relationships, challenges, and cultural background.
### Framework Requirements
**Philosophical Grounding**: Definitions must honor established virtue ethics traditions while being personally meaningful to the individual's worldview and cultural context.
**Practical Actionability**: Each virtue definition must help the person recognize when they're embodying it in daily life and when they're falling short.
**Cultural Sensitivity**: Definitions should respect the person's cultural background, religious/spiritual orientation, professional context, and life circumstances.
**Mathematical Compatibility**: Sub-dimensions must be truly orthogonal (independent) to ensure clean mathematical analysis of want-pull alignment and drift detection.
**Daily Applicability**: Definitions must be concrete enough that someone can meaningfully assess their daily embodiment from 0-10 while remaining aspirational enough to drive growth.
### The Five Core Virtues and Sub-Dimensions
**1. Wisdom 🧠**
- **Critical Thinking**: Analyzing information objectively and questioning assumptions
- **Learning Orientation**: Actively pursuing knowledge and being open to changing your mind
- **Practical Judgment**: Applying knowledge wisely in real-world situations
**2. Integrity 💎**
- **Honesty**: Being truthful in communication and interactions
- **Authenticity**: Expressing your genuine self while respecting contexts
- **Reliability**: Following through on commitments and being dependable
**3. Compassion ❤️**
- **Empathy**: Understanding and feeling with others' emotional experiences
- **Kindness**: Acting with genuine care and consideration in daily interactions
- **Service**: Contributing to others' wellbeing and the greater good
**4. Justice ⚖️**
- **Fairness**: Applying consistent standards and ensuring equitable treatment
- **Advocacy**: Speaking up for those who lack power or voice
- **Responsibility**: Taking ownership of your impact on others and addressing harm
**5. Courage 🦁**
- **Moral Courage**: Standing up for what's right despite opposition or consequences
- **Resilience**: Bouncing back from setbacks and maintaining hope through challenges
- **Initiative**: Taking the first step toward positive change and embracing opportunities
## User's Philosophical Discovery Responses
${responses.map(r => `- ${r.question}: ${Array.isArray(r.answer) ? r.answer.join(', ') : r.answer}`).join('\n')}
### Cultural Context Analysis
${this.extractCulturalContext(responses)}
### Behavioral Patterns Identified
${this.extractBehavioralIndicators(responses)}
### Value Hierarchies and Priorities
${this.extractValueHierarchies(responses)}
## Creating Personalized Definitions
Based on their responses, create definitions that:
1. **Honor Their Language**: Use the specific terms, concepts, and way of speaking they've demonstrated
2. **Reflect Their Context**: Incorporate their cultural background, life stage, professional context, and relationship priorities
3. **Address Their Challenges**: Reference the specific situations, tensions, or growth edges they've mentioned
4. **Build on Their Strengths**: Acknowledge the wisdom and approaches they already demonstrate
5. **Ensure Daily Utility**: Make definitions concrete enough for daily 0-10 self-assessment
### Definition Structure
Each definition should follow this pattern:
**"For you, [Virtue/Sub-dimension] means: [personalized definition that incorporates their language, context, and understanding]. In daily life, this shows up as [specific behaviors they mentioned or would resonate with]. You might rate yourself higher when [concrete positive indicators] and lower when [concrete challenges they identified]. This connects to your broader values of [tie to their philosophical/cultural context]."**
### Behavioral Indicators Requirements
For each sub-dimension, generate exactly 3 practical behavioral indicators that:
1. **Reference Their Context**: Use situations, relationships, or environments they've mentioned
2. **Match Their Language**: Employ the specific terms and concepts they use naturally
3. **Enable Daily Assessment**: Be specific enough to recognize in day-to-day life
4. **Show Progressive Levels**: Indicate what basic, intermediate, and advanced embodiment looks like
5. **Connect to Their Values**: Reflect the priorities and concerns they've expressed
**Indicator Quality Examples:**
- ❌ Generic: "Shows empathy toward others"
- ✅ Personalized: "Listens without giving advice when your partner shares work frustrations"
- ❌ Vague: "Makes good decisions"
- ✅ Specific: "Takes time to research before major purchases, even when excited about something"
### Quality Checks
- Does this definition resonate emotionally with the person?
- Are the indicators specific enough that they could recognize these behaviors tomorrow?
- Is it specific enough to guide daily assessment but broad enough to remain relevant over time?
- Does it honor their philosophical and cultural context?
- Would this definition help them recognize both strengths and growth opportunities?
- Is it differentiated enough from the other sub-dimensions to track independently?
- Do the indicators reflect their actual life circumstances and relationships?
## Response Format
Return a JSON array with exactly these 5 virtues including deeply personalized definitions:
[
{
"name": "Wisdom",
"definition": "Personalized definition incorporating their understanding, language, and context",
"priority_weight": 0.85,
"template_source": "ai-personalized",
"emoji": "🧠",
"sub_dimensions": [
{
"name": "Critical Thinking",
"definition": "Their personal understanding incorporating their approach to analysis, skepticism level, and decision-making style",
"indicators": ["Pauses to fact-check information before sharing it with friends or on social media", "Questions their initial emotional reaction to difficult news or decisions", "Seeks multiple perspectives before forming opinions on complex topics"]
},
{
"name": "Learning Orientation",
"definition": "How they personally approach learning, growth, and changing their mind based on their responses",
"indicators": ["Actively seeks feedback from colleagues or mentors when trying new approaches", "Changes their mind when presented with compelling evidence, even about strongly held beliefs", "Dedicates specific time weekly to learning something new in their field or interests"]
},
{
"name": "Practical Judgment",
"definition": "How they bridge knowledge and action in their specific context and relationships",
"indicators": ["Considers how decisions will affect family members or team dynamics, not just immediate outcomes", "Applies lessons from past experiences to similar current situations", "Balances ideal principles with practical constraints when making choices"]
}
]
}
// ... continue for all 5 virtues with their 3 sub-dimensions each
]
**CRITICAL**: Each sub-dimension MUST include exactly 3 behavioral indicators that are:
- Specific to their life circumstances and relationships
- Observable in daily life
- Varied in difficulty (some easier to recognize, some more challenging)
- Culturally appropriate for their background
- Actionable enough to guide daily 0-10 self-assessment
Remember: These definitions and indicators will guide their daily self-reflection and growth. Make them personally meaningful, culturally sensitive, and practically actionable for their specific life context.`;
try {
const response = await this.callClaudeAPI(prompt);
const virtues = this.extractJSON(response);
// Ensure we got exactly 5 virtues with the right names
const expectedNames = ['Wisdom', 'Integrity', 'Compassion', 'Justice', 'Courage'];
if (!Array.isArray(virtues) || virtues.length !== 5) {
throw new Error('AI did not return exactly 5 virtues');
}
for (const expectedName of expectedNames) {
if (!virtues.some(v => v.name === expectedName)) {
throw new Error(`Missing virtue: ${expectedName}`);
}
}
return virtues;
}
catch (error) {
log.error('Failed to get personalized virtues from AI: ' + error);
throw error;
}
}
async callClaudeAPI(prompt) {
// Use real Anthropic API if available
if (this.anthropic) {
try {
const response = await this.anthropic.messages.create({
model: 'claude-3-5-sonnet-20241022',
max_tokens: 1024,
messages: [
{
role: 'user',
content: prompt
}
]
});
return response.content[0].type === 'text' ? response.content[0].text : '';
}
catch (error) {
log.error('Anthropic API call failed: ' + error);
// Fall through to simulation
}
}
else {
// Add a small delay to simulate processing time
await new Promise(resolve => setTimeout(resolve, 800));
}
// Simulate intelligent responses based on prompt content as fallback
// Handle initial philosophical discovery
if (prompt.includes('Philosophical Virtue Framework Discovery') && prompt.includes('Initial Responses')) {
// Extract user responses for personalization
const truthVsKindness = prompt.includes('Truth vs Kindness: truth') ? 'truth' : 'kindness';
const decisionStyle = prompt.includes('Decision Making: logic') ? 'logic' :
prompt.includes('Decision Making: intuition') ? 'intuition' :
prompt.includes('Decision Making: principles') ? 'principles' : 'relationships';
let personalizedQuestion = "";
let reasoning = "";
if (truthVsKindness === 'truth' && decisionStyle === 'logic') {
personalizedQuestion = "You've shown a preference for truth and logical reasoning. Can you describe a situation where being completely honest might hurt someone you care about - how do you navigate that tension?";
reasoning = "Building on their truth/logic preferences to explore how they handle conflicts between analytical honesty and care for others.";
}
else if (truthVsKindness === 'kindness' && decisionStyle === 'intuition') {
personalizedQuestion = "You prioritize kindness and trust your intuition in decisions. How do you handle situations where your gut feeling tells you someone needs tough love rather than gentle support?";
reasoning = "Exploring how their kindness/intuition preferences work when intuition suggests being less gentle.";
}
else if (truthVsKindness === 'truth' && decisionStyle === 'relationships') {
personalizedQuestion = "Interesting - you value truth but rely on others when making decisions. How do you balance staying honest to your principles while being influenced by the people you trust?";
reasoning = "Probing the tension between independent truth-seeking and relationship-dependent decision-maki