This is an advanced AI-powered deep research system built with Mastra framework, designed for intelligent, autonomous research and reporting. The system leverages multiple AI agents, sophisticated workflows, and cutting-edge RAG (Retrieval-Augmented Generation) capabilities to conduct comprehensive research with human-in-the-loop approval.
- Mastra: AI orchestration framework for agents, workflows, and tools
- TypeScript: Primary programming language with strict type safety
- Node.js 20.9+: Runtime environment with modern ES modules
- Google AI Gemini 2.5: Advanced multimodal AI with search grounding and caching
- AI SDK: Unified interface for multiple AI providers
- Exa AI: Primary web search and content discovery API
- Vector Embeddings: Semantic search and similarity matching
- Graph RAG: Knowledge graph-based reasoning and retrieval
- LibSQL: High-performance SQLite-compatible database (currently in-memory configuration)
- Vector Indexes: Multiple specialized indexes for different content types
- Memory Processors: 11 specialized processors for context optimization
- OpenTelemetry: Comprehensive tracing with child spans
- Performance Metrics: Processing time, resource usage, API costs
- Error Tracking: Structured error logging and failure analysis
- Research Agent: Multi-phase research with web search and evaluation
- Report Agent: Comprehensive report generation from research data
- Evaluation Agent: Content relevance and quality assessment
- Learning Extraction Agent: Key insights and follow-up question generation
- Web Summarization Agent: Content condensation and synthesis
- RAG Agent: Vector search and retrieval-augmented generation
- Comprehensive Research Workflow: End-to-end research with human approval
- Generate Report Workflow: Automated report creation
- Research Workflow: Basic research orchestration
- Web Search Tool: Intelligent web scraping and content extraction
- Vector Query Tool: Semantic search over embedded content
- Chunker Tool: Document segmentation for RAG
- Rerank Tool: Result relevance optimization
- Evaluation Tool: Content quality assessment
- Learning Extraction Tool: Insight mining from research data
- TokenLimiterProcessor: Prevents context overflow
- PersonalizationProcessor: Boosts user-relevant content
- ErrorCorrectionProcessor: Deduplicates content via checksum
- HierarchicalMemoryProcessor: Filters episodic vs semantic content
- CitationExtractorProcessor: Prioritizes cited content
- MultiPerspectiveProcessor: Multi-viewpoint evaluation
- TemporalReasoningProcessor: Time-based relationship analysis
- UncertaintyQuantificationProcessor: Confidence scoring
- KnowledgeGraphProcessor: Graph construction and reasoning
- BayesianBeliefProcessor: Probabilistic belief updating
- CircuitBreakerProcessor: Fault tolerance and recovery
- TypeScript Strict Mode: All code must be fully typed with no
anytypes - ESLint: Code quality and consistency enforcement
- Zod Validation: Runtime type validation for all data structures
- Error Handling: Comprehensive error handling with proper logging
- Documentation: JSDoc comments for all public APIs and complex functions
- Agent-Based Architecture: Modular, specialized AI agents
- Workflow Orchestration: Declarative workflow definitions
- Tool Composition: Reusable, composable tools
- Memory Management: Hierarchical memory with specialized processors
- Event-Driven: Async/await patterns with proper error propagation
- Token Optimization: Efficient context management and compression
- Caching Strategy: Multi-level caching (explicit, implicit, search)
- Batch Processing: Optimized for bulk operations
- Resource Monitoring: Comprehensive performance tracking
- Cost Optimization: API usage monitoring and optimization
deep-research/
├── src/mastra/ # Core framework code
│ ├── index.ts # Main entry point
│ ├── agents/ # AI agent implementations
│ ├── workflows/ # Workflow definitions
│ ├── tools/ # Specialized tools
│ ├── networks/ # Multi-agent networks
│ ├── config/ # Configuration modules
│ └── mcp/ # MCP server implementation
├── docs/ # Documentation
├── templates/ # Code templates
├── memory/ # Memory and context data
├── scripts/ # Build and utility scripts
└── tests/ # Test suites
- Query Analysis: Understand user intent and research scope
- Web Research: Multi-source information gathering
- Content Evaluation: Relevance and credibility assessment
- Learning Extraction: Key insights and pattern identification
- Synthesis: Information consolidation and structuring
- Report Generation: Comprehensive output creation
- Human Review: Interactive approval and refinement
- Source Credibility: Automated source evaluation
- Content Freshness: Recency analysis and prioritization
- Cross-Reference Validation: Multi-source verification
- Bias Detection: Perspective diversity assessment
- Fact-Checking: Automated verification where possible
- Google AI Gemini: Primary AI model provider
- Exa AI: Alternative search and research capabilities
- GitHub API: Repository and issue management
- Web Scraping: Content extraction from web sources
- Model Context Protocol: Standardized AI tool integration
- Real-time Communication: WebSocket-based tool communication
- Tool Discovery: Dynamic tool registration and management
- Security: Sandboxed tool execution
- Environment Variables: Secure API key management
- Database URLs: LibSQL connection configuration
- Logging Levels: Configurable verbosity
- Performance Tuning: Resource allocation optimization
- Health Checks: System status monitoring
- Performance Metrics: Response times and resource usage
- Error Tracking: Comprehensive error logging
- Cost Monitoring: API usage and budget tracking
- Transparency: Clear explanation of AI-generated content
- Bias Mitigation: Multi-perspective evaluation
- Privacy Protection: User data minimization
- Content Verification: Source credibility assessment
- Human Oversight: Human-in-the-loop approval processes
- Academic Integrity: Proper citation and attribution
- Source Diversity: Multiple perspective inclusion
- Fact Verification: Automated and manual validation
- Misinformation Prevention: Content quality filtering
- Archon Integration: Knowledge management and task tracking
- GitHub Issues: Feature requests and bug tracking
- Pull Requests: Code review and integration
- Documentation: Comprehensive project documentation
- Unit Tests: Individual component testing
- Integration Tests: End-to-end workflow testing
- Performance Tests: Load and stress testing
- AI Evaluation: Model output quality assessment
- Multi-Modal Support: Image, video, and audio processing
- Advanced Graph RAG: Enhanced knowledge graph capabilities
- Real-time Collaboration: Multi-user research sessions
- Custom Model Training: Domain-specific model fine-tuning
- Advanced Analytics: Research trend analysis and insights
- Cross-Disciplinary Research: Multi-domain knowledge integration
- Longitudinal Studies: Time-series analysis and tracking
- Predictive Analytics: Trend forecasting and prediction
- Automated Literature Review: Academic paper analysis
- Competitive Intelligence: Market and competitor analysis
The system has access to several MCP (Model Context Protocol) servers that provide additional capabilities for Gemini CLI:
- mastraBlog: Get Mastra.ai blog content and announcements
- mastraDocs: Access comprehensive Mastra.ai documentation and guides
- mastraExamples: Retrieve code examples from the Mastra.ai examples directory
- mastraChanges: Get changelog information for Mastra.ai packages
- Usage: Query documentation, get code examples, check changelogs
Purpose: Metacognitive questioning tool for identifying assumptions and preventing tunnel vision Schema:
plan(string, required): Current plan or thinking to analyzeuserRequest(string, required): Original user request for alignment checkingthinkingLog(string, optional): Raw sequential thinking transcriptavailableTools(array, optional): List of available MCP toolsfocusAreas(array, optional): Specific focus areas for analysissessionId(string, optional): Session ID for state managementpreviousAdvice(string, optional): Previous feedback to avoid repetitionphase(enum, optional): Current project phase (planning, implementation, review)confidence(number, optional): Agent's confidence level (0-1)
Usage Examples:
"Analyze this plan for potential assumptions before implementing"
"Check if this approach aligns with the user's original request"
"Identify blind spots in this debugging strategy"
Best Practices:
- Use before major implementation steps
- Always provide the original user request for alignment checking
- Include thinking logs for deeper analysis
- Use multiple times during complex problem-solving
Purpose: Pattern recognition system for tracking common errors and solutions Schema:
mistake(string, required): One-sentence description of the learning entrycategory(enum, required): Error category (Complex Solution Bias, Feature Creep, Premature Implementation, Misalignment, Overtooling, Preference, Success, Other)solution(string, optional): How the issue was correctedtype(enum, optional): Type of learning entry (mistake, preference, success)sessionId(string, optional): Session ID for state management
Usage Examples:
"Log this debugging approach for future reference"
"Record successful problem-solving pattern"
"Track common implementation mistakes"
Purpose: Problem-solving using Lotus Sutra wisdom framework with multiple approaches Schema:
tag(enum, required): Processing technique (upaya, expedient, direct, gradual, sudden, recognize, transform, integrate, transcend, embody, examine, reflect, verify, refine, complete, open, engage, transform, express, meditate, OUTPUT)content(string, required): Content of the current processing stepstepNumber(integer, required): Current number in sequence (minimum: 1)totalSteps(integer, required): Estimated total steps needed (minimum: 1)nextStepNeeded(boolean, required): Whether another step is neededisMeditation(boolean, optional): Whether this step is a meditative pausemeditationDuration(integer, optional): Duration for meditation in seconds (minimum: 1)
Usage Examples:
"Apply Lotus wisdom framework to analyze this architectural decision"
"Use multiple approaches to understand this complex problem"
"Transform confusion into clarity using wisdom techniques"
Meditation Integration:
- Set
isMeditation: truefor pause steps - Use
meditationDurationto specify pause length - Combine with multiple
tagvalues for comprehensive analysis
Best Practices:
- Use step-by-step process (open → engage → transform → express → OUTPUT)
- Include meditation pauses for complex problems
- Apply multiple wisdom techniques sequentially
Purpose: Dynamic and reflective problem-solving through structured thoughts Schema:
thought(string, required): Current thinking stepnextThoughtNeeded(boolean, required): Whether another thought step is neededthoughtNumber(integer, required): Current thought number (minimum: 1)totalThoughts(integer, required): Estimated total thoughts needed (minimum: 1)isRevision(boolean, optional): Whether this revises previous thinkingrevisesThought(integer, optional): Which thought number is being reconsideredbranchFromThought(integer, optional): Branching point thought numberbranchId(string, optional): Identifier for the current branchneedsMoreThoughts(boolean, optional): If more thoughts are needed
Usage Examples:
"Break down this complex problem into sequential steps"
"Revise my previous approach based on new information"
"Branch into alternative solutions for this issue"
Purpose: Application of structured mental models for problem-solving Schema:
modelName(enum, required): Mental model to apply (first_principles, opportunity_cost, error_propagation, rubber_duck, pareto_principle, occams_razor)problem(string, required): Problem to analyzesteps(array, optional): Analysis stepsreasoning(string, optional): Reasoning processconclusion(string, optional): Final conclusion
Usage Examples:
"Apply first principles thinking to this database optimization"
"Use opportunity cost analysis for feature prioritization"
"Apply Occam's razor to simplify this complex solution"
Purpose: Systematic debugging approaches for technical issues Schema:
approachName(enum, required): Debugging method (binary_search, reverse_engineering, divide_conquer, backtracking, cause_elimination, program_slicing)issue(string, required): Issue to debugsteps(array, optional): Debugging stepsfindings(string, optional): Investigation findingsresolution(string, optional): Final resolution
Usage Examples:
"Use binary search to isolate this performance issue"
"Apply divide and conquer to this complex bug"
"Use reverse engineering to understand this third-party API"
Purpose: Simulated expert collaboration with diverse perspectives Schema:
topic(string, required): Topic for collaborative analysispersonas(array, required): Expert personas with backgroundscontributions(array, required): Individual contributionsstage(enum, required): Collaboration stageactivePersonaId(string, required): Currently active personasessionId(string, required): Unique session identifieriteration(integer, required): Current iteration numbernextContributionNeeded(boolean, required): Whether another contribution is needed
Usage Examples:
"Get multiple expert perspectives on this architecture decision"
"Simulate team discussion for this design problem"
"Apply collaborative reasoning to this complex issue"
Purpose: Structured decision analysis and rational choice Schema:
decisionStatement(string, required): Decision to analyzeoptions(array, required): Available optionscriteria(array, required): Evaluation criteriaanalysisType(enum, required): Analysis methodstage(enum, required): Current analysis stagedecisionId(string, required): Unique decision identifieriteration(integer, required): Current iterationnextStageNeeded(boolean, required): Whether another stage is needed
Usage Examples:
"Apply expected utility analysis to this investment decision"
"Use multi-criteria decision analysis for feature selection"
"Apply maximin strategy for risk management"
Purpose: Self-monitoring of knowledge and reasoning quality Schema:
task(string, required): Task being monitoredstage(enum, required): Current monitoring stageoverallConfidence(number, required): Overall confidence level (0-1)uncertaintyAreas(array, required): Areas of uncertaintyrecommendedApproach(string, required): Recommended next stepsmonitoringId(string, required): Unique monitoring session IDiteration(integer, required): Current iterationnextAssessmentNeeded(boolean, required): Whether further assessment is needed
Usage Examples:
"Monitor my confidence in this technical solution"
"Assess knowledge gaps in this domain"
"Track reasoning quality throughout this analysis"
Purpose: Formal scientific reasoning and hypothesis testing Schema:
stage(enum, required): Current scientific method stageinquiryId(string, required): Unique inquiry identifieriteration(integer, required): Current iterationnextStageNeeded(boolean, required): Whether another stage is needed
Usage Examples:
"Apply scientific method to test this performance hypothesis"
"Use hypothesis testing for this user behavior analysis"
"Apply experimental design to this feature validation"
Purpose: Dialectical reasoning and argument analysis Schema:
claim(string, required): Main claim to analyzepremises(array, required): Supporting premisesconclusion(string, required): Logical conclusionargumentType(enum, required): Type of argumentconfidence(number, required): Confidence in argument (0-1)nextArgumentNeeded(boolean, required): Whether another argument is needed
Usage Examples:
"Build structured argument for this architectural decision"
"Apply dialectical reasoning to this design debate"
"Analyze counterarguments for this proposed solution"
Purpose: Visual thinking, problem-solving, and communication Schema:
operation(enum, required): Visual operation to performdiagramId(string, required): Unique diagram identifierdiagramType(enum, required): Type of diagramiteration(integer, required): Current iterationnextOperationNeeded(boolean, required): Whether another operation is needed
Usage Examples:
"Create a flowchart for this complex process"
"Build a concept map for this system architecture"
"Transform this diagram to show alternative solutions"
"Show me examples of creating custom tools in Mastra"
"Get the latest changelog for @mastra/mcp package"
"Find documentation about MCP client configuration"
"Show me how to use RuntimeContext in tools"
"Create an MCP client for stock price and weather tools"
"Configure SSE transport for weather API"
"Set up stdio transport for local tools"
"Show me how to handle tool authentication"
- Sequential Processing: Use tools in logical sequence (vibe_check → lotuswisdom → clear-thought tools)
- Iterative Refinement: Call tools multiple times with different parameters for deeper analysis
- Context Preservation: Maintain conversation context across tool calls
- Error Recovery: Handle tool failures gracefully and provide fallback approaches
Vibe-Check Tools:
- Always include original user request for alignment checking
- Use thinking logs for comprehensive analysis
- Apply before major decisions or implementations
- Track patterns across multiple sessions
Lotus Wisdom:
- Use step-by-step process (open → engage → transform → express → OUTPUT)
- Include meditation pauses for complex problems
- Apply multiple wisdom techniques sequentially
- Set appropriate meditation durations (5-30 seconds)
Clear-Thought Tools:
- Choose appropriate tool for problem type (mentalmodel for analysis, debuggingapproach for issues)
- Use sequentialthinking for complex multi-step problems
- Apply metacognitivemonitoring for self-assessment
- Use collaborativereasoning for multi-perspective analysis
- Tool Chaining: Use output from one tool as input for another
- Parallel Processing: Run multiple tools simultaneously when appropriate
- Conditional Logic: Use tool results to determine next steps
- Result Synthesis: Combine insights from multiple tools for comprehensive solutions
- Timeout Management: Set appropriate timeouts for long-running operations
- Retry Logic: Implement intelligent retry mechanisms for failed operations
- Resource Monitoring: Track tool usage and performance metrics
- Fallback Mechanisms: Provide alternative approaches when tools fail
When a clear-thought tool returns nextStageNeeded: true or nextThoughtNeeded: true or nextAssessmentNeeded: true, you MUST continue iterating with the same tool using the next logical parameters.
NEVER SKIP ITERATION - This will result in:
- Incomplete analysis and missing insights
- Assumptions that lead to incorrect conclusions
- Gaps in understanding and documentation
- Suboptimal decision-making and problem-solving
Sequential Thinking:
- Start with
thoughtNumber: 1, totalThoughts: estimated_number - Continue incrementing
thoughtNumberuntilnextThoughtNeeded: false - Update
totalThoughtsas you progress if needed - Use
isRevision: trueandrevisesThought: Xwhen correcting previous thoughts
Scientific Method:
- Follow stages: observation → question → hypothesis → experiment → analysis → conclusion
- Each stage returns
nextStageNeeded: trueuntil conclusion - Use same
inquiryIdacross all iterations - Increment
iterationnumber for each call
Meta-Cognitive Monitoring:
- Continue with same
monitoringIdand incrementiteration - Stop only when
nextAssessmentNeeded: false - Use
suggestedAssessmentsfrom previous response for next iteration
Decision Framework:
- Progress through stages: evaluation → analysis → recommendation
- Each stage returns
nextStageNeeded: trueuntil recommendation complete - Use same
decisionIdand incrementiteration
- ❌ Stopping early when
nextXNeeded: true - ❌ Changing tool parameters incorrectly between iterations
- ❌ Not using the same session/decision/inquiry IDs
- ❌ Ignoring
suggestedNextTypesorsuggestedAssessments - ❌ Not incrementing iteration counters properly
- ✅ Always check the
nextXNeededflag in responses - ✅ Use consistent IDs across iterations (sessionId, monitoringId, decisionId, inquiryId)
- ✅ Increment iteration numbers appropriately
- ✅ Follow suggested next steps from tool responses
- ✅ Document each iteration's insights before moving to next
- ✅ Use tool results to inform subsequent tool usage
- Connection Issues: Check transport configuration (stdio vs SSE)
- Authentication Errors: Verify API keys and token formats
- Tool Not Found: Ensure server is running and tools are properly registered
- Type Errors: Update Zod schemas to match current API requirements
When working with this codebase:
- Understand the Architecture: This is a complex AI orchestration system with multiple specialized components
- Respect the Patterns: Follow established patterns for agents, workflows, tools, and memory processors
- Maintain Type Safety: All code must be fully typed with proper Zod validation
- Follow Research Ethics: Ensure responsible AI practices and proper attribution
- Optimize Performance: Consider token limits, caching, and resource usage
- Document Thoroughly: Provide comprehensive documentation for all new features
- Test Extensively: Ensure robust testing for AI-generated content and workflows
@/docs/GEMINI.md @/src/mastra/GEMINI.md @/src/mastra/agents/GEMINI.md @/src/mastra/tools/GEMINI.md @/src/mastra/workflows/GEMINI.md @/docs/ARCHITECTURE_DIAGRAMS.md @/docs/PROJECT_DOCUMENTATION.md
@README.md @package.json @.env.example @tsconfig.json @eslint.config.js @/templates/agent-file-template.md @/templates/plan-template.md @/templates/spec-template.md @/templates/task-template.md @/.gemini/commands/specify.toml @/.gemini/commands/plan.toml @/.gemini/commands/task.toml @/memory/constitution.md @/memory/constitution_update_checklist.md @/scripts/check-task-prerequisites.sh @/scripts/common.sh @/scripts/create-new-feature.sh @/scripts/get-feature-paths.sh @/scripts/setup-plan.sh @/scripts/update-agent-context.sh