get-smart-guidance-v1.1.0.js•24.3 kB
#!/usr/bin/env node
/**
* Smart Guidance Tool v1.1.0 - FAIL-FAST RELIABILITY
* Provides essential guidance with robust validation and detailed error reporting
* @version 1.1.0 (January 20, 2025)
* @status ENHANCED - Fail-fast validation with comprehensive error messages
* @reference JIT workflow step 1 of 7
* @enhancement Strict validation, no fallbacks, detailed troubleshooting
*/
export class SmartGuidanceToolV110 {
constructor() {
this.processingStartTime = null;
this.validationErrors = [];
this.gradeConfigurations = this.initializeGradeConfigurations();
this.subjectProfiles = this.initializeSubjectProfiles();
}
/**
* Main guidance entry point with FAIL-FAST validation
* @param {Object} input - Contains prompt, subject, gradeLevel
* @returns {Object} Lightweight guidance with widget predictions OR detailed error
*/
async processGuidanceRequest(input) {
this.processingStartTime = new Date();
this.validationErrors = [];
try {
console.error('[SMART_GUIDANCE_V110] Starting fail-fast validation');
// FAIL-FAST VALIDATION PHASE
const validationResult = this.validateInputComprehensively(input);
if (!validationResult.valid) {
throw new Error(`Smart Guidance validation failed:\n\n${validationResult.errors.join('\n\n')}\n\nReceived input: ${JSON.stringify(input, null, 2)}`);
}
const { prompt, subject, gradeLevel } = validationResult.normalizedInput;
console.error(`[SMART_GUIDANCE_V110] Validation passed - Processing: "${prompt.substring(0, 50)}..." for ${subject} ${gradeLevel}`);
// ANALYSIS PHASE
const promptAnalysis = this.analyzePromptStructure(prompt);
const gradeConfig = this.getValidatedGradeConfiguration(gradeLevel);
const subjectProfile = this.getValidatedSubjectProfile(subject);
// WIDGET PREDICTION PHASE
const suggestedWidgets = this.predictOptimalWidgets(promptAnalysis, subjectProfile, gradeConfig);
// GUIDANCE GENERATION PHASE
const guidance = this.generateComprehensiveGuidance(promptAnalysis, gradeConfig, subjectProfile, suggestedWidgets);
console.error(`[SMART_GUIDANCE_V110] Success - Generated guidance with ${suggestedWidgets.length} widget suggestions`);
return {
success: true,
data: guidance,
metadata: {
version: "1.1.0",
timestamp: new Date().toISOString(),
processingTime: Date.now() - this.processingStartTime.getTime(),
inputValidation: "passed",
promptLength: prompt.length,
detectedComplexity: promptAnalysis.complexity
}
};
} catch (error) {
console.error('[SMART_GUIDANCE_V110] FAIL-FAST ERROR:', error.message);
return {
success: false,
error: {
code: 'SMART_GUIDANCE_VALIDATION_FAILED',
message: error.message,
timestamp: new Date().toISOString(),
processingTime: Date.now() - this.processingStartTime.getTime(),
failFast: true,
developmentMode: true,
troubleshooting: {
requiredInputStructure: {
prompt: "string (required) - Educational topic or content description",
subject: "string (optional) - One of: Ciências, Matemática, História, Português, Geografia, Arte, Educação Física, Inglês",
gradeLevel: "string (optional) - Format: '6º ano', '1º médio', etc."
},
validationChecks: [
"prompt must be a non-empty string with educational content",
"subject must be from predefined list or null/undefined",
"gradeLevel must follow Brazilian education format or null/undefined"
],
commonIssues: [
"Empty or missing prompt",
"Invalid subject name (check spelling and accents)",
"Incorrect gradeLevel format (use '6º ano', not 'grade 6')",
"Non-string input types"
],
debugSteps: [
"1. Verify input.prompt exists and is a string",
"2. Check subject spelling against valid list",
"3. Ensure gradeLevel follows Brazilian format",
"4. Check for null/undefined values"
]
}
}
};
}
}
/**
* COMPREHENSIVE FAIL-FAST INPUT VALIDATION
* No fallbacks - strict validation with detailed error reporting
*/
validateInputComprehensively(input) {
const errors = [];
// Basic input structure validation
if (!input || typeof input !== 'object') {
errors.push("❌ INPUT STRUCTURE ERROR:\nInput must be an object containing educational parameters.\nReceived: " + typeof input + "\nRequired format: { prompt: 'string', subject?: 'string', gradeLevel?: 'string' }");
return { valid: false, errors };
}
// Prompt validation (CRITICAL)
if (!input.prompt) {
errors.push("❌ PROMPT ERROR:\nPrompt is required and cannot be empty.\nThe prompt should describe the educational content or topic you want to create.\nExample: 'Create a lesson about photosynthesis for 7th grade'");
return { valid: false, errors };
}
if (typeof input.prompt !== 'string') {
errors.push(`❌ PROMPT TYPE ERROR:\nPrompt must be a string, received: ${typeof input.prompt}\nValue: ${JSON.stringify(input.prompt)}\nCorrect format: "Your educational topic description"`);
return { valid: false, errors };
}
if (input.prompt.trim().length < 5) {
errors.push(`❌ PROMPT LENGTH ERROR:\nPrompt too short: ${input.prompt.length} characters.\nMinimum required: 5 characters\nReceived: "${input.prompt}"\nProvide a meaningful educational topic description.`);
return { valid: false, errors };
}
if (input.prompt.trim().length > 1000) {
errors.push(`❌ PROMPT LENGTH ERROR:\nPrompt too long: ${input.prompt.length} characters.\nMaximum allowed: 1000 characters\nConsider summarizing your educational objective.`);
return { valid: false, errors };
}
// Subject validation (OPTIONAL but strict when provided)
const validSubjects = ['Ciências', 'Matemática', 'História', 'Português', 'Geografia', 'Arte', 'Educação Física', 'Inglês'];
if (input.subject !== undefined && input.subject !== null) {
if (typeof input.subject !== 'string') {
errors.push(`❌ SUBJECT TYPE ERROR:\nSubject must be a string, received: ${typeof input.subject}\nValue: ${JSON.stringify(input.subject)}\nValid subjects: ${validSubjects.join(', ')}`);
return { valid: false, errors };
}
if (!validSubjects.includes(input.subject)) {
errors.push(`❌ SUBJECT VALIDATION ERROR:\nInvalid subject: "${input.subject}"\n\nValid subjects:\n${validSubjects.map(s => ` • ${s}`).join('\n')}\n\nNote: Subject names are case-sensitive and must include proper Portuguese accents.`);
return { valid: false, errors };
}
}
// Grade level validation (OPTIONAL but strict when provided)
const validGradeLevels = [
'6º ano', '7º ano', '8º ano', '9º ano', // Ensino Fundamental II
'1º médio', '2º médio', '3º médio', // Ensino Médio
'Superior' // Ensino Superior
];
if (input.gradeLevel !== undefined && input.gradeLevel !== null) {
if (typeof input.gradeLevel !== 'string') {
errors.push(`❌ GRADE LEVEL TYPE ERROR:\nGrade level must be a string, received: ${typeof input.gradeLevel}\nValue: ${JSON.stringify(input.gradeLevel)}\nValid formats: ${validGradeLevels.join(', ')}`);
return { valid: false, errors };
}
if (!validGradeLevels.includes(input.gradeLevel)) {
errors.push(`❌ GRADE LEVEL VALIDATION ERROR:\nInvalid grade level: "${input.gradeLevel}"\n\nValid grade levels:\n${validGradeLevels.map(g => ` • ${g}`).join('\n')}\n\nNote: Use Brazilian education system format with proper ordinal indicators (º).`);
return { valid: false, errors };
}
}
// Normalize input
const normalizedInput = {
prompt: input.prompt.trim(),
subject: input.subject || null,
gradeLevel: input.gradeLevel || null
};
console.error(`[SMART_GUIDANCE_V110] Input validation passed`);
return { valid: true, normalizedInput, errors: [] };
}
/**
* VALIDATED PROMPT ANALYSIS with fail-fast approach
*/
analyzePromptStructure(prompt) {
try {
const analysis = {
topic: this.extractTopic(prompt),
complexity: this.assessComplexity(prompt),
contentType: this.identifyContentType(prompt),
educationalGoals: this.extractEducationalGoals(prompt),
keywords: this.extractKeywords(prompt)
};
// Validate analysis results
if (!analysis.topic || analysis.topic.length < 3) {
throw new Error(`Failed to extract meaningful topic from prompt: "${prompt}"`);
}
if (!analysis.complexity || !['basic', 'intermediate', 'advanced'].includes(analysis.complexity)) {
throw new Error(`Failed to assess prompt complexity. Prompt may be unclear or ambiguous.`);
}
return analysis;
} catch (error) {
throw new Error(`Prompt analysis failed: ${error.message}\nPrompt must be a clear educational objective or topic description.`);
}
}
/**
* VALIDATED GRADE CONFIGURATION with fail-fast approach
*/
getValidatedGradeConfiguration(gradeLevel) {
if (!gradeLevel) {
// Return default configuration
return this.gradeConfigurations['default'];
}
const config = this.gradeConfigurations[gradeLevel];
if (!config) {
throw new Error(`Grade configuration not found for: "${gradeLevel}"\nThis should not happen after validation. Check grade configurations.`);
}
// Validate configuration structure
const requiredProps = ['recommendedDuration', 'attentionSpan', 'complexity', 'exampleType'];
for (const prop of requiredProps) {
if (!config[prop]) {
throw new Error(`Invalid grade configuration for "${gradeLevel}": missing ${prop}`);
}
}
return config;
}
/**
* VALIDATED SUBJECT PROFILE with fail-fast approach
*/
getValidatedSubjectProfile(subject) {
if (!subject) {
// Return default profile
return this.subjectProfiles['default'];
}
const profile = this.subjectProfiles[subject];
if (!profile) {
throw new Error(`Subject profile not found for: "${subject}"\nThis should not happen after validation. Check subject profiles.`);
}
// Validate profile structure
const requiredProps = ['primaryFocus', 'visualImportance', 'interactionLevel'];
for (const prop of requiredProps) {
if (!profile[prop]) {
throw new Error(`Invalid subject profile for "${subject}": missing ${prop}`);
}
}
return profile;
}
/**
* COMPREHENSIVE GUIDANCE GENERATION
*/
generateComprehensiveGuidance(promptAnalysis, gradeConfig, subjectProfile, suggestedWidgets) {
return {
workflowInstructions: {
currentStep: "Step 1: FULL Content Creation",
nextRequiredAction: "CREATE COMPLETE EDUCATIONAL CONTENT FIRST (not just structure), THEN use analyze_content_for_widgets tool",
criticalNote: "⚠️ IMPORTANT: You MUST create FULL educational content (explanations, examples, vocabulary, assessments) BEFORE using any tools",
contentRequirement: "Content should be COMPREHENSIVE with detailed explanations, examples, and educational substance - NOT just titles and structure",
failFastNote: "🚨 v1.1.0: All tools now use fail-fast validation. Ensure content is complete and well-structured.",
toolSequence: [
"get_smart_guidance (current step - completed)",
"CREATE FULL CONTENT (required next)",
"analyze_content_for_widgets (only after content is complete)",
"get_widget_requirements",
"validate_lesson_data",
"format_for_composer",
"save_composition_api",
"open_composition_editor"
]
},
basicGuidelines: {
duration: gradeConfig.recommendedDuration,
minimumTextLength: 20,
widgetRange: "3-8 widgets recommended",
cognitiveLoadBalance: "Mix of low, medium, and high complexity widgets",
assessmentRequirement: "Include at least one assessment widget (quiz or flashcards)",
gradeSpecific: {
attentionSpan: gradeConfig.attentionSpan,
complexity: gradeConfig.complexity,
examples: gradeConfig.exampleType
},
subjectSpecific: {
focus: subjectProfile.primaryFocus,
visuals: subjectProfile.visualImportance,
interaction: subjectProfile.interactionLevel
},
qualityStandards: {
content: "Original, engaging content with real-world connections",
language: "Age-appropriate vocabulary and concepts",
structure: "Logical progression from introduction to assessment",
engagement: "Interactive elements to maintain attention"
}
},
suggestedWidgets: suggestedWidgets,
contentCreationGuidance: {
approach: "⭐ CREATE FULL EDUCATIONAL CONTENT in natural language (like writing a textbook chapter) - NOT just structure or outlines",
criticalRequirement: "🚨 CONTENT MUST BE COMPLETE AND DETAILED before proceeding to analyze_content_for_widgets",
contentStructure: {
introduction: "Write FULL engaging introduction with context and objectives (not just a title)",
mainContent: "Write COMPLETE explanations with details, examples, and educational substance",
practice: "Create ACTUAL exercises and activities (not just placeholders)",
assessment: "Write COMPLETE quiz questions with options and answers"
},
contentTypes: {
explanatory: "FULL detailed explanations (multiple paragraphs per concept)",
questions: "COMPLETE assessment questions with all options and correct answers",
vocabulary: "ACTUAL term definitions (not just lists of terms)",
activities: "DETAILED activity instructions with materials and procedures"
}
},
qualityAssurance: {
beforeNextStep: [
"Content has substantial educational substance (not just outlines)",
"All sections are complete with full explanations",
"Assessment questions include all options and correct answers",
"Vocabulary includes actual definitions",
"Activities have detailed instructions"
],
contentMinimums: {
totalWords: "Minimum 300 words for meaningful lesson",
sectionsRequired: "At least 3 content sections",
assessmentQuestions: "At least 2 complete questions if including assessment"
}
}
};
}
/**
* Extract topic from prompt
*/
extractTopic(prompt) {
// Simple topic extraction - can be enhanced
const words = prompt.toLowerCase().split(' ');
const stopWords = ['create', 'make', 'develop', 'about', 'on', 'lesson', 'class', 'aula'];
const topicWords = words.filter(word => !stopWords.includes(word) && word.length > 3);
return topicWords.slice(0, 3).join(' ') || prompt.substring(0, 30);
}
/**
* Assess prompt complexity
*/
assessComplexity(prompt) {
const complexKeywords = ['analysis', 'synthesis', 'evaluation', 'comparison', 'advanced'];
const intermediateKeywords = ['explain', 'describe', 'compare', 'demonstrate'];
const basicKeywords = ['list', 'identify', 'define', 'basic'];
const lowerPrompt = prompt.toLowerCase();
if (complexKeywords.some(word => lowerPrompt.includes(word))) {
return 'advanced';
} else if (intermediateKeywords.some(word => lowerPrompt.includes(word))) {
return 'intermediate';
} else {
return 'basic';
}
}
/**
* Identify content type from prompt
*/
identifyContentType(prompt) {
const lowerPrompt = prompt.toLowerCase();
if (lowerPrompt.includes('quiz') || lowerPrompt.includes('test') || lowerPrompt.includes('assessment')) {
return 'assessment';
} else if (lowerPrompt.includes('vocabulary') || lowerPrompt.includes('terms') || lowerPrompt.includes('definitions')) {
return 'vocabulary';
} else if (lowerPrompt.includes('activity') || lowerPrompt.includes('experiment') || lowerPrompt.includes('practice')) {
return 'activity';
} else {
return 'explanatory';
}
}
/**
* Extract educational goals
*/
extractEducationalGoals(prompt) {
const goals = [];
const lowerPrompt = prompt.toLowerCase();
if (lowerPrompt.includes('understand') || lowerPrompt.includes('learn')) {
goals.push('comprehension');
}
if (lowerPrompt.includes('apply') || lowerPrompt.includes('practice')) {
goals.push('application');
}
if (lowerPrompt.includes('analyze') || lowerPrompt.includes('evaluate')) {
goals.push('analysis');
}
if (lowerPrompt.includes('remember') || lowerPrompt.includes('memorize')) {
goals.push('memorization');
}
return goals.length > 0 ? goals : ['comprehension'];
}
/**
* Extract keywords
*/
extractKeywords(prompt) {
return prompt.toLowerCase()
.split(' ')
.filter(word => word.length > 4)
.filter(word => !['lesson', 'class', 'about', 'create', 'make'].includes(word))
.slice(0, 5);
}
/**
* Predict optimal widgets based on analysis
*/
predictOptimalWidgets(promptAnalysis, subjectProfile, gradeConfig) {
const widgets = [];
// Always include header
widgets.push({
type: "head-1",
reason: "Professional lesson header",
confidence: 1.0,
priority: 1
});
// Content widgets based on analysis
if (promptAnalysis.contentType === 'explanatory' || promptAnalysis.contentType === 'activity') {
widgets.push({
type: "text-1",
reason: "Main explanatory content",
confidence: 0.9,
priority: 2
});
}
// Subject-specific widgets
if (subjectProfile.visualImportance === 'high') {
widgets.push({
type: "image-1",
reason: "Visual learning enhancement for " + (subjectProfile.name || 'subject'),
confidence: 0.8,
priority: 3
});
}
// Assessment widgets
if (promptAnalysis.contentType === 'assessment' || promptAnalysis.educationalGoals.includes('memorization')) {
widgets.push({
type: "quiz-1",
reason: "Assessment and knowledge validation",
confidence: 0.85,
priority: 4
});
}
// Vocabulary widgets
if (promptAnalysis.contentType === 'vocabulary' || promptAnalysis.keywords.length > 3) {
widgets.push({
type: "flashcards-1",
reason: "Vocabulary and term reinforcement",
confidence: 0.8,
priority: 5
});
}
return widgets;
}
/**
* Initialize grade configurations
*/
initializeGradeConfigurations() {
return {
'6º ano': {
recommendedDuration: '45 minutes',
attentionSpan: '15-20 minutes per segment',
complexity: 'basic to intermediate',
exampleType: 'concrete, familiar examples'
},
'7º ano': {
recommendedDuration: '45 minutes',
attentionSpan: '15-20 minutes per segment',
complexity: 'basic to intermediate',
exampleType: 'concrete with some abstract concepts'
},
'8º ano': {
recommendedDuration: '50 minutes',
attentionSpan: '20-25 minutes per segment',
complexity: 'intermediate',
exampleType: 'mix of concrete and abstract'
},
'9º ano': {
recommendedDuration: '50 minutes',
attentionSpan: '20-25 minutes per segment',
complexity: 'intermediate to advanced',
exampleType: 'abstract concepts with real-world applications'
},
'1º médio': {
recommendedDuration: '50 minutes',
attentionSpan: '25-30 minutes per segment',
complexity: 'intermediate to advanced',
exampleType: 'complex real-world applications'
},
'2º médio': {
recommendedDuration: '50 minutes',
attentionSpan: '25-30 minutes per segment',
complexity: 'advanced',
exampleType: 'complex theoretical and practical applications'
},
'3º médio': {
recommendedDuration: '50 minutes',
attentionSpan: '30+ minutes per segment',
complexity: 'advanced',
exampleType: 'university-prep level complexity'
},
'Superior': {
recommendedDuration: '90 minutes',
attentionSpan: '45+ minutes per segment',
complexity: 'advanced to expert',
exampleType: 'professional and research applications'
},
'default': {
recommendedDuration: '45 minutes',
attentionSpan: '20 minutes per segment',
complexity: 'intermediate',
exampleType: 'balanced concrete and abstract'
}
};
}
/**
* Initialize subject profiles
*/
initializeSubjectProfiles() {
return {
'Ciências': {
name: 'Ciências',
primaryFocus: 'scientific_method',
visualImportance: 'high',
interactionLevel: 'high'
},
'Matemática': {
name: 'Matemática',
primaryFocus: 'problem_solving',
visualImportance: 'medium',
interactionLevel: 'high'
},
'História': {
name: 'História',
primaryFocus: 'context_analysis',
visualImportance: 'medium',
interactionLevel: 'medium'
},
'Português': {
name: 'Português',
primaryFocus: 'language_skills',
visualImportance: 'low',
interactionLevel: 'medium'
},
'Geografia': {
name: 'Geografia',
primaryFocus: 'spatial_analysis',
visualImportance: 'high',
interactionLevel: 'medium'
},
'Arte': {
name: 'Arte',
primaryFocus: 'creative_expression',
visualImportance: 'very_high',
interactionLevel: 'high'
},
'Educação Física': {
name: 'Educação Física',
primaryFocus: 'practical_application',
visualImportance: 'medium',
interactionLevel: 'very_high'
},
'Inglês': {
name: 'Inglês',
primaryFocus: 'communication_skills',
visualImportance: 'low',
interactionLevel: 'high'
},
'default': {
name: 'General',
primaryFocus: 'knowledge_transfer',
visualImportance: 'medium',
interactionLevel: 'medium'
}
};
}
}
/**
* Create and export the tool instance for JIT server integration
*/
export function createSmartGuidanceToolV110() {
const guidanceTool = new SmartGuidanceToolV110();
return {
name: 'get_smart_guidance_v110',
description: 'STEP 1 v1.1.0: Get lightweight educational guidance with fail-fast validation. Provides widget predictions and comprehensive planning with detailed error reporting for development.',
inputSchema: {
type: 'object',
properties: {
prompt: {
type: 'string',
description: 'Educational content prompt or topic (required)'
},
subject: {
type: 'string',
description: 'Subject area (optional)',
enum: ['Ciências', 'Matemática', 'História', 'Português', 'Geografia', 'Arte', 'Educação Física', 'Inglês']
},
gradeLevel: {
type: 'string',
description: 'Brazilian grade level (optional)',
enum: ['6º ano', '7º ano', '8º ano', '9º ano', '1º médio', '2º médio', '3º médio', 'Superior']
}
},
required: ['prompt']
},
handler: async (input) => {
return await guidanceTool.processGuidanceRequest(input);
}
};
}