Skip to content

Conversation

@ssdeanx
Copy link
Owner

@ssdeanx ssdeanx commented Dec 10, 2025

  • Updated ContentAgentContext to include user tier and additional parameters for content strategy.
  • Refactored CopywriterAgentContext to streamline imports and improve clarity.
  • Renamed KnowledgeIndexingContext to ExcalidrawValidatorRuntimeContext for better context representation.
  • Introduced ImageToCsvRuntimeContext with new output schema properties for enhanced image processing.
  • Updated ChartRuntimeContext to replace FinancialChartRuntimeContext for consistency across chart-related agents.
  • Modified pg-storage configuration to improve memory management and added new template for user profiles.
  • Adjusted imports in AuthenticationService and DocumentIndexingService for consistency in naming conventions.
  • Enhanced DocumentChunkingTool and PdfDataConversionTool for better performance and error handling.

- Updated `ContentAgentContext` to include user tier and additional parameters for content strategy.
- Refactored `CopywriterAgentContext` to streamline imports and improve clarity.
- Renamed `KnowledgeIndexingContext` to `ExcalidrawValidatorRuntimeContext` for better context representation.
- Introduced `ImageToCsvRuntimeContext` with new output schema properties for enhanced image processing.
- Updated `ChartRuntimeContext` to replace `FinancialChartRuntimeContext` for consistency across chart-related agents.
- Modified `pg-storage` configuration to improve memory management and added new template for user profiles.
- Adjusted imports in `AuthenticationService` and `DocumentIndexingService` for consistency in naming conventions.
- Enhanced `DocumentChunkingTool` and `PdfDataConversionTool` for better performance and error handling.
Copilot AI review requested due to automatic review settings December 10, 2025 17:48
Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry @ssdeanx, you have reached your weekly rate limit of 500000 diff characters.

Please try again later or upgrade to continue using Sourcery

@continue
Copy link

continue bot commented Dec 10, 2025

Keep this PR in a mergeable state →

Learn more

All Green is an AI agent that automatically:

✅ Addresses code review comments

✅ Fixes failing CI checks

✅ Resolves merge conflicts

@github-actions
Copy link

🤖 Hi @ssdeanx, I've received your request, and I'm working on it now! You can track my progress in the logs for more details.

@coderabbitai
Copy link

coderabbitai bot commented Dec 10, 2025

Summary by CodeRabbit

  • New Features

    • Added user tier support (free, pro, enterprise) across agents for personalized functionality.
    • Introduced language selection options (English, Spanish, Japanese, French) for multiple agents.
    • Added color scheme preferences (dark/light) for chart generation.
  • Improvements

    • Enhanced memory configuration with improved title generation and semantic recall indexing.
    • Refined document chunking strategies with updated section-based configuration.
    • Streamlined agent dependencies and scoring mechanisms across multiple agents.
  • Updates

    • Updated model sources and expanded chart context options for better customization.

✏️ Tip: You can customize this high-level summary in your review settings.

Walkthrough

This PR refactors agent runtime context types across multiple agents, introducing a UserTier-based capability system and standardizing context interfaces. It simplifies scorer dependencies, updates model configurations, adjusts chunking parameters and metadata handling, and expands public type exports.

Changes

Cohort / File(s) Change Summary
Agent Context Refactoring
src/mastra/agents/contentStrategistAgent.ts
Introduces new ContentAgentContext with user-tier: UserTier, strategy preferences (`'iceberg'
Agent Context Refactoring
src/mastra/agents/csv_to_excalidraw.ts, src/mastra/agents/image_to_csv.ts
Renames DaneContextCsvToExcalidrawRuntimeContext and KnowledgeIndexingContextImageToCsvRuntimeContext. Removes chunking-related fields and replaces with schema and language metadata.
Agent Context Refactoring
src/mastra/agents/excalidraw_validator.ts
Renames KnowledgeIndexingContextExcalidrawValidatorRuntimeContext. Removes chunking fields; adds user-tier: UserTier and language requirement in system prompt.
Agent Context Refactoring
src/mastra/agents/recharts.ts
Renames FinancialChartRuntimeContextChartRuntimeContext. Adds `colorScheme: 'dark'
Agent Context Refactoring
src/mastra/agents/index.ts
Expands public API with 15 new type exports for agent runtime contexts (EditorRuntimeContext, BusinessRuntimeContext, CodingRuntimeContext, ChartRuntimeContext, DataExportContext, DataIngestionContext, DataTransformationContext, KnowledgeIndexingContext, LearningExtractionAgentContext, DocumentProcessingContext, CsvToExcalidrawRuntimeContext, ExcalidrawValidatorRuntimeContext, ImageToCsvRuntimeContext, CalendarContext, ScriptWriterRuntimeContext).
Scorer Dependency Cleanup
src/mastra/agents/copywriterAgent.ts, src/mastra/agents/editorAgent.ts
Removes multiple scorer imports (creativityScorer, responseQualityScorer, toneConsistencyScorer, structureScorer). copywriterAgent now uses only structureScorer; editorAgent retains only summaryQualityScorer.
Model and Configuration Updates
src/mastra/agents/image.ts
Replaces imageGen model with googleAINanoBanana. Adds empty options, tools, scorers, workflows configuration objects.
Storage and Memory Configuration
src/mastra/config/pg-storage.ts
Adds generateTitle at top level of memory options. Extends semanticRecall.indexConfig with threshold and indexName. Changes WorkingMemory scope from 'thread' to 'resource', adds version: 'vnext', and introduces memory template string.
Tool Updates
src/mastra/tools/document-chunking.tool.ts
Refactors chunking parameter construction: replaces headers-based config with sections for markdown/html. Switches document reranker to use google('gemini-1.5-flash'). Updates embedding and metadata storage (chunkIndex, totalChunks, documentId, strategy).
Tool Updates
src/mastra/tools/pdf-data-conversion.tool.ts
Renames PdfParseFunction parameters from _buffer and _options to buffer and options. Minor whitespace cleanup.
Import Path Corrections
src/mastra/config/AuthenticationService.ts, src/mastra/config/DocumentIndexingService.ts
Updates RoleService import path from ./RoleService to ./role-service.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Areas requiring extra attention:

  • Type consistency across agent contexts: Verify all 5 context renames/modifications are correctly referenced throughout their respective agents and in the expanded index.ts exports. Watch for any missed usages of old interface names.
  • document-chunking.tool.ts logic refactoring: Review the chunk parameter construction (especially separators/sections config switch for markdown/html), embedding generation flow, and metadata field mappings (chunkIndex, totalChunks, documentId) to ensure correctness.
  • pg-storage.ts configuration changes: Validate that the shift of generateTitle to top-level, the new WorkingMemory scope/version/template structure, and semantic recall index config changes are compatible with downstream consumers.
  • Scorer dependency removal: Confirm that copywriterAgent and editorAgent function correctly with reduced scorer options and that no scoring configurations elsewhere depend on the removed scorers.
  • Model substitution in imageAgent: Verify googleAINanoBanana has compatible interface and capabilities as the replaced imageGen.

Possibly related PRs

Suggested reviewers

  • sourcery-ai

Poem

🐰 Hops with joy through context fields so new,
UserTiers bounce from free to enterprise true,
ChartRuntimeContext paints in colors bright,
While chunking parameters shimmy left and right!
A rabbit's refactoring, neat and spry,
Type exports bloom beneath the TypeScript sky!

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately captures the main changes: enhancing agent contexts with new runtime context types and improving functionality across multiple agent modules.
Description check ✅ Passed The description is directly related to the changeset, covering key modifications to agent contexts, refactoring, renames, and tool enhancements across the affected files.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch develop

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @ssdeanx, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly refactors and enhances various agent contexts and core functionalities across the application. The primary goal is to improve the flexibility and clarity of agent configurations, streamline dependencies, and optimize data handling processes. These changes aim to provide more granular control over agent behavior, improve system performance, and ensure consistency in service interactions.

Highlights

  • Agent Context Enhancements: The ContentAgentContext now includes user tier and advanced content strategy parameters, while ImageToCsvRuntimeContext gains new output schema properties, providing more granular control over agent behavior.
  • Context Renaming and Simplification: KnowledgeIndexingContext has been renamed to ExcalidrawValidatorRuntimeContext and its properties streamlined. Similarly, FinancialChartRuntimeContext is now ChartRuntimeContext for broader applicability and consistency across chart-related agents.
  • Import Optimization: Several agent files, including CopywriterAgentContext and EditorAgent, have had unused imports removed to improve clarity and reduce bundle size, leading to a cleaner codebase.
  • Configuration Updates: The pg-storage configuration has been refined for better memory management, including the addition of a new, detailed user profile template for working memory and adjustments to thread title generation.
  • Service Import Consistency: AuthenticationService and DocumentIndexingService now use a consistent naming convention for RoleService imports, improving code maintainability.
  • Tool Improvements: DocumentChunkingTool and PdfDataConversionTool received updates for better performance, clarity, and error handling, including a direct model specification for relevance scoring in the chunking tool.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@github-actions
Copy link

🤖 I'm sorry @ssdeanx, but I was unable to process your request. Please see the logs for more details.

@greptile-apps
Copy link

greptile-apps bot commented Dec 10, 2025

Greptile Overview

Greptile Summary

This PR enhances agent contexts and improves functionality across multiple agents, configuration services, and tools.

Key Changes:

  • Renamed and enhanced agent context interfaces for better clarity (ContentAgentContext, CsvToExcalidrawRuntimeContext, ExcalidrawValidatorRuntimeContext, ImageToCsvRuntimeContext, ChartRuntimeContext)
  • Added user tier-based parameters to ContentAgentContext for subscription-aware content strategy (user-tier, staggeredOutput, sectionCount, strategy, backupDataTools)
  • Updated image.ts agent to use googleAINanoBanana model for low-cost image generation
  • Improved memory configuration in pg-storage.ts with template-based working memory replacing schema-based approach
  • Standardized imports with kebab-case naming (role-service instead of RoleService)
  • Removed unused imports across multiple agent files for cleaner codebase
  • Added comprehensive type exports for 14 agent runtime contexts improving type safety
  • Enhanced document chunking tool with reordered imports and inline model specification

Impact:
The changes improve code organization, type safety, and enable tier-based feature differentiation for agents. Memory management is simplified with template-based user profiles.

Confidence Score: 4/5

  • PR is safe to merge with one minor concern about the googleAINanoBanana model change requiring verification of proper export
  • The PR contains well-structured refactoring with proper naming conventions and context enhancements. The main concern is ensuring googleAINanoBanana is properly exported from config (verified: it is exported). All other changes are safe refactorings and improvements.
  • src/mastra/agents/image.ts - verify the googleAINanoBanana model works correctly for image generation use cases

Important Files Changed

File Analysis

Filename Score Overview
src/mastra/agents/contentStrategistAgent.ts 4/5 renamed context interface from CopywriterAgentContext to ContentAgentContext with new tier-based parameters (user-tier, staggeredOutput, sectionCount, strategy, backupDataTools)
src/mastra/agents/excalidraw_validator.ts 4/5 renamed KnowledgeIndexingContext to ExcalidrawValidatorRuntimeContext, removed indexing-related parameters and added language support
src/mastra/agents/image.ts 2/5 replaced imageGen model with googleAINanoBanana - but this model import appears to be missing from config exports
src/mastra/agents/index.ts 5/5 added comprehensive type exports for all agent runtime contexts (14 new exports) improving type safety and developer experience
src/mastra/config/pg-storage.ts 4/5 improved memory configuration: moved generateTitle to options root, replaced schema-based working memory with template-based user profile, reorganized semantic recall config with threshold and indexName
src/mastra/tools/document-chunking.tool.ts 4/5 reordered imports for consistency, replaced googleAI import with inline google('gemini-1.5-flash') for reranking scorer

Sequence Diagram

sequenceDiagram
    participant Dev as Developer
    participant Agent as Agent Layer
    participant Context as Runtime Context
    participant Config as Config Layer
    participant Memory as Memory Storage
    
    Note over Dev,Memory: PR #32: Enhance agent contexts and improve functionality
    
    Dev->>Agent: Update contentStrategistAgent
    Agent->>Context: Rename CopywriterAgentContext → ContentAgentContext
    Context->>Context: Add user-tier, staggeredOutput, sectionCount, strategy
    Agent->>Config: Import webScraperTool, chartSupervisorTool
    
    Dev->>Agent: Update image.ts agent
    Agent->>Config: Replace imageGen → googleAINanoBanana
    Config-->>Agent: Return gemini-2.5-flash-image model
    
    Dev->>Agent: Update excalidraw_validator
    Agent->>Context: Rename KnowledgeIndexingContext → ExcalidrawValidatorRuntimeContext
    Context->>Context: Remove indexing params, add language support
    
    Dev->>Agent: Update image_to_csv
    Agent->>Context: Create ImageToCsvRuntimeContext
    Context->>Context: Add identityOutputSchema, chalkboardOutputSchema
    
    Dev->>Agent: Update recharts agents
    Agent->>Context: Rename FinancialChartRuntimeContext → ChartRuntimeContext
    
    Dev->>Config: Update pg-storage.ts
    Config->>Memory: Move generateTitle to options root
    Config->>Memory: Replace schema-based with template-based working memory
    Memory-->>Config: User Profile template configured
    
    Dev->>Config: Update AuthenticationService & DocumentIndexingService
    Config->>Config: Change RoleService → role-service imports
    
    Dev->>Agent: Export all runtime context types
    Agent-->>Dev: 14 new type exports for improved type safety
    
    Note over Dev,Memory: All changes maintain backward compatibility
Loading

Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

14 files reviewed, 1 comment

Edit Code Review Agent Settings | Greptile

import { Agent } from '@mastra/core/agent'
import type { RequestContext } from '@mastra/core/request-context'
import { imageGen, pgMemory } from '../config'
import { googleAINanoBanana, pgMemory } from '../config'
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

logic: model changed from imageGen to googleAINanoBanana but this model is not defined in the imported config

Suggested change
import { googleAINanoBanana, pgMemory } from '../config'
import { googleAINanoBanana, pgMemory } from '../config'
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/mastra/agents/image.ts
Line: 3:3

Comment:
**logic:** model changed from `imageGen` to `googleAINanoBanana` but this model is not defined in the imported config

```suggestion
import { googleAINanoBanana, pgMemory } from '../config'
```

How can I resolve this? If you propose a fix, please make it concise.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a series of enhancements and refactorings across multiple agents and configuration files. Key changes include updating agent contexts for more detailed control, renaming contexts for better clarity, and streamlining imports. The pg-storage configuration has been significantly modified to improve memory management and introduce a new template for user profiles. Naming conventions for file imports have also been standardized. The changes are mostly well-implemented and align with the goals of improving functionality and consistency. I've identified a couple of areas in the pg-storage configuration where the logic for environment variable handling could be made more intuitive.

options: {
// Message management
lastMessages: parseInt(process.env.MEMORY_LAST_MESSAGES ?? '500'),
generateTitle: process.env.THREAD_GENERATE_TITLE !== 'true',
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The logic for setting generateTitle from the environment variable THREAD_GENERATE_TITLE is counter-intuitive. Currently, generateTitle is false only when THREAD_GENERATE_TITLE is exactly 'true', and true otherwise (including when it's 'false' or undefined). This is confusing because the variable name suggests that setting it to 'true' should enable title generation, not disable it.

A clearer approach would be to check for 'true' to enable the feature, or if the intent is to default to true, check for 'false' to disable it. For example: process.env.THREAD_GENERATE_TITLE !== 'false'. This would make generateTitle false only when THREAD_GENERATE_TITLE is 'false', which is more intuitive.

        generateTitle: process.env.THREAD_GENERATE_TITLE !== 'false',

threads: {
generateTitle: process.env.THREAD_GENERATE_TITLE !== 'true',
},
generateTitle: process.env.THREAD_GENERATE_TITLE !== 'true',
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Similar to the other instance, the logic for generateTitle is counter-intuitive. It's disabled only when THREAD_GENERATE_TITLE is 'true'. Consider using process.env.THREAD_GENERATE_TITLE !== 'false' to make the behavior more explicit and align with the expectation that setting a variable to 'false' disables the feature.

        generateTitle: process.env.THREAD_GENERATE_TITLE !== 'false',

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR enhances agent contexts and improves functionality across multiple agents and configuration files. The changes focus on refining context interfaces, updating API integrations, improving memory management configuration, and standardizing naming conventions.

Key Changes:

  • Refactored agent context interfaces to be more specific and include additional configuration parameters (user tier, output schemas, content strategy options)
  • Updated memory configuration to use template-based working memory instead of schema-based, and adjusted scope from 'thread' to 'resource'
  • Standardized import paths for service files to use kebab-case convention

Reviewed changes

Copilot reviewed 14 out of 14 changed files in this pull request and generated 8 comments.

Show a summary per file
File Description
src/mastra/tools/pdf-data-conversion.tool.ts Removed underscores from parameter names and cleaned up whitespace/indentation for better code consistency
src/mastra/tools/document-chunking.tool.ts Reordered imports, removed unused googleAI import, updated MastraAgentRelevanceScorer to use direct model instantiation
src/mastra/config/pg-storage.ts Major refactoring of memory configuration: moved generateTitle to top-level, replaced workingMemory.schema with template, changed scope from 'thread' to 'resource', and restructured thread management
src/mastra/config/DocumentIndexingService.ts Updated import path from './RoleService' to './role-service' for naming consistency
src/mastra/config/AuthenticationService.ts Updated import path from './RoleService' to './role-service' for naming consistency
src/mastra/agents/recharts.ts Renamed FinancialChartRuntimeContext to ChartRuntimeContext for broader applicability
src/mastra/agents/index.ts Added exports for multiple new context types including ChartRuntimeContext, ImageToCsvRuntimeContext, ExcalidrawValidatorRuntimeContext, and others
src/mastra/agents/image_to_csv.ts Renamed KnowledgeIndexingContext to ImageToCsvRuntimeContext and added new output schema properties
src/mastra/agents/image.ts Changed model from imageGen to googleAINanoBanana and added empty configuration objects
src/mastra/agents/excalidraw_validator.ts Renamed KnowledgeIndexingContext to ExcalidrawValidatorRuntimeContext and updated context properties
src/mastra/agents/editorAgent.ts Removed unused scorer imports (responseQualityScorer, structureScorer, toneConsistencyScorer)
src/mastra/agents/csv_to_excalidraw.ts Renamed DaneContext to CsvToExcalidrawRuntimeContext for clarity
src/mastra/agents/copywriterAgent.ts Removed unused imports (googleAI, creativityScorer, responseQualityScorer, toneConsistencyScorer)
src/mastra/agents/contentStrategistAgent.ts Renamed CopywriterAgentContext to ContentAgentContext and added extensive new properties for content strategy configuration
Comments suppressed due to low confidence (1)

src/mastra/config/DocumentIndexingService.ts:13

  • Unused import RoleService.
import { RoleService } from './role-service'

}),
),
}),
scope: 'resource', // 'resource' | 'thread'
Copy link

Copilot AI Dec 10, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The workingMemory.scope value has changed from 'thread' to 'resource'. This is a significant behavioral change that affects how working memory is scoped and managed. Ensure this change is intentional and that all dependent code and configurations are updated accordingly. This could impact how memory is shared across different contexts.

Suggested change
scope: 'resource', // 'resource' | 'thread'
scope: 'thread', // 'resource' | 'thread'

Copilot uses AI. Check for mistakes.
options: {
// Message management
lastMessages: parseInt(process.env.MEMORY_LAST_MESSAGES ?? '500'),
generateTitle: process.env.THREAD_GENERATE_TITLE !== 'true',
Copy link

Copilot AI Dec 10, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The logic for generateTitle appears to be inverted. The setting process.env.THREAD_GENERATE_TITLE !== 'true' will set generateTitle to true when the environment variable is 'false' or missing, and false when it's 'true'. This is counterintuitive. Consider using process.env.THREAD_GENERATE_TITLE === 'true' instead to match the expected behavior where the environment variable directly controls the feature.

Suggested change
generateTitle: process.env.THREAD_GENERATE_TITLE !== 'true',
generateTitle: process.env.THREAD_GENERATE_TITLE === 'true',

Copilot uses AI. Check for mistakes.
threads: {
generateTitle: process.env.THREAD_GENERATE_TITLE !== 'true',
},
generateTitle: process.env.THREAD_GENERATE_TITLE !== 'true',
Copy link

Copilot AI Dec 10, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The same inverted logic issue exists here. process.env.THREAD_GENERATE_TITLE !== 'true' will enable title generation when the environment variable is not 'true', which is counterintuitive. This should be process.env.THREAD_GENERATE_TITLE === 'true' to ensure the environment variable directly controls the feature as expected.

Suggested change
generateTitle: process.env.THREAD_GENERATE_TITLE !== 'true',
generateTitle: process.env.THREAD_GENERATE_TITLE === 'true',

Copilot uses AI. Check for mistakes.
role: 'system',
content: `You are an expert at validating and fixing Excalidraw JSON for Excalidraw diagrams.
user: ${userId}
Copy link

Copilot AI Dec 10, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nitpick] Inconsistent capitalization in template headers. Line 25 starts with lowercase "user:" while other similar labels use Title Case (e.g., "User:" at line 32 in image_to_csv.ts, line 34 in contentStrategistAgent.ts). For consistency, this should be "User:" with a capital 'U'.

Suggested change
user: ${userId}
User: ${userId}

Copilot uses AI. Check for mistakes.
Comment on lines +58 to +61
options: {},
tools: {},
scorers: {},
workflows: {},
Copy link

Copilot AI Dec 10, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nitpick] Adding empty objects for options, tools, scorers, and workflows appears unnecessary. If these properties are optional in the Agent configuration and have no values to provide, they should be omitted entirely to keep the code clean and follow the principle of not adding unnecessary code.

Suggested change
options: {},
tools: {},
scorers: {},
workflows: {},

Copilot uses AI. Check for mistakes.

export interface CopywriterAgentContext {
export type UserTier = 'free' | 'pro' | 'enterprise'
export interface ContentAgentContext {
Copy link

Copilot AI Dec 10, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The interface has been renamed from CopywriterAgentContext to ContentAgentContext, but it's being used in the contentStrategistAgent. This naming mismatch creates confusion - the context should be named ContentStrategistAgentContext or similar to clearly indicate it's for the content strategist agent, not a generic "content agent".

Copilot uses AI. Check for mistakes.

export interface CopywriterAgentContext {
export type UserTier = 'free' | 'pro' | 'enterprise'
export interface ContentAgentContext {
Copy link

Copilot AI Dec 10, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new ContentAgentContext interface is not exported from the index file. Since other similar context interfaces are being exported (like ChartRuntimeContext, ImageToCsvRuntimeContext, etc.), this new interface should also be exported for consistency and to allow external usage.

Copilot uses AI. Check for mistakes.
import type { StorageResult } from './VectorStorageService'
import { VectorStorageService } from './VectorStorageService'
import { RoleService } from './RoleService'
import { RoleService } from './role-service'
Copy link

Copilot AI Dec 10, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

'RoleService' is defined but never used.

Suggested change
import { RoleService } from './role-service'

Copilot uses AI. Check for mistakes.
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (7)
src/mastra/agents/copywriterAgent.ts (1)

18-22: Unused contentType field in context interface.

The contentType property is defined in CopywriterAgentContext but is never retrieved or used in the instructions function (only userId is accessed at line 32). Consider either utilizing this field in the instructions template or removing it if it's not needed.

src/mastra/agents/image.ts (3)

17-17: Correct the log message.

The log message says "Initializing Financial Chart Agents..." but this file defines an Image Generator agent. This appears to be a copy-paste error.

Apply this diff:

-log.info('Initializing Financial Chart Agents...')
+log.info('Initializing Image Generator Agent...')

46-54: Fix provider options to use runtime context values.

The provider options use hardcoded constants (aspectRatio and resolution) instead of the runtime context values (aspectratioX and resolutionY) extracted on lines 34 and 37. This means user preferences for aspect ratio and resolution are completely ignored during image generation.

The fallback logic aspectRatio || AspectRatio2K doesn't work as intended because aspectRatio is always the truthy string '16:9'.

Apply this diff to use the runtime context values with proper fallbacks:

       providerOptions: {
         google: {
           imageConfig: {
-          aspectRatio: aspectRatio || AspectRatio2K,
-          imageSize: resolution || resolution1K,
+          aspectRatio: aspectratioX === '16:9' ? '16:9' : '4:3',
+          imageSize: resolutionY === '2K' ? '2K' : '1K',
           },
         } satisfies GoogleGenerativeAIProviderOptions,
       }

19-22: Remove unused constants.

After fixing the provider options logic, these constants are no longer needed. The aspect ratio and resolution values should come from the runtime context, not hardcoded constants.

Apply this diff:

-const aspectRatio = '16:9';
-const AspectRatio2K = '4:3';
-const resolution = '2K';
-const resolution1K = '1K';
-
src/mastra/tools/document-chunking.tool.ts (3)

519-523: Missing baseParams in semantic-markdown strategy.

The semantic-markdown case in mdocumentChunker doesn't spread baseParams, meaning maxSize and overlap won't be applied. Compare with mastraChunker which includes ...baseParams.

 case 'semantic-markdown':
   return {
     strategy: 'semantic-markdown' as const,
+    ...baseParams,
     joinThreshold: 500,
   }

165-167: Remove duplicate comments.

There are duplicate comments throughout the file (e.g., "// Create a span for tracing" appears twice consecutively on lines 165-166, similarly at lines 342-343, 359-360, 421-422, 633-634, 651-652).

-    // Create a span for tracing
     // Create a span for tracing
     const tracer = trace.getTracer('document-chunking');

As per coding guidelines, avoid redundant comments that repeat what the code does.


229-244: Inconsistent property naming between mastraChunker and mdocumentChunker for markdown/html strategies.

The mastraChunker uses headers (lines 231, 240), while mdocumentChunker uses sections (lines 483, 492). Both tools call the same document.chunk() method, so they must use compatible parameter structures. This inconsistency will cause runtime failures in whichever implementation uses the incorrect property name.

Align the property names to match the expected API contract. If sections is the correct property name (suggested by the more recent mdocumentChunker implementation), update mastraChunker accordingly.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a933a32 and a418daf.

📒 Files selected for processing (14)
  • src/mastra/agents/contentStrategistAgent.ts (1 hunks)
  • src/mastra/agents/copywriterAgent.ts (1 hunks)
  • src/mastra/agents/csv_to_excalidraw.ts (1 hunks)
  • src/mastra/agents/editorAgent.ts (1 hunks)
  • src/mastra/agents/excalidraw_validator.ts (2 hunks)
  • src/mastra/agents/image.ts (2 hunks)
  • src/mastra/agents/image_to_csv.ts (1 hunks)
  • src/mastra/agents/index.ts (2 hunks)
  • src/mastra/agents/recharts.ts (5 hunks)
  • src/mastra/config/AuthenticationService.ts (1 hunks)
  • src/mastra/config/DocumentIndexingService.ts (1 hunks)
  • src/mastra/config/pg-storage.ts (3 hunks)
  • src/mastra/tools/document-chunking.tool.ts (2 hunks)
  • src/mastra/tools/pdf-data-conversion.tool.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (15)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.github/instructions/next-js.instructions.md)

**/*.{js,jsx,ts,tsx}: Use next/dynamic for dynamic imports to load components only when needed, improving initial load time.
Use next/image component for automatic image optimization, including lazy loading and responsive images.
Use React.memo to prevent unnecessary re-renders of components.
Use the <Link prefetch> tag to prefetch pages that are likely to be visited.
Use getServerSideProps, getStaticProps, or server components for fetching data on the server-side.
Use SWR or React Query for client-side data fetching and caching.
Use CSS Modules, Styled Components, or Tailwind CSS for component-level styling. Prefer Tailwind CSS for rapid development.
Use React Context, Zustand, Jotai, or Recoil for managing global state. Avoid Redux unless necessary.
Use react-hook-form for managing forms and validation.
Only fetch the data that is needed by the component to avoid over-fetching.
Avoid long-running synchronous operations in the main thread to prevent blocking.
Always use setState or hooks to update state instead of mutating state directly.
Include a complete dependency array in useEffect hooks to prevent unexpected behavior.
Avoid writing server-side code in client components to prevent exposing secrets or causing unexpected behavior.
Use try...catch blocks for handling errors in asynchronous operations.
Implement error boundary components using getDerivedStateFromError or componentDidCatch lifecycle methods.
Sanitize user input to prevent Cross-Site Scripting (XSS) attacks. Be especially careful when rendering HTML directly from user input.
Store authentication tokens in HTTP-only cookies or local storage securely.
Implement role-based access control to restrict access to sensitive resources.
Clean up event listeners and timers in useEffect hooks to avoid memory leaks.
Only update state when necessary to reduce the number of re-renders and improve performance.
Use immutable data structures and avoid mutating data directly to prevent unexpected...

Files:

  • src/mastra/agents/copywriterAgent.ts
  • src/mastra/agents/image_to_csv.ts
  • src/mastra/agents/csv_to_excalidraw.ts
  • src/mastra/tools/pdf-data-conversion.tool.ts
  • src/mastra/agents/image.ts
  • src/mastra/agents/excalidraw_validator.ts
  • src/mastra/config/AuthenticationService.ts
  • src/mastra/config/DocumentIndexingService.ts
  • src/mastra/agents/recharts.ts
  • src/mastra/agents/index.ts
  • src/mastra/agents/contentStrategistAgent.ts
  • src/mastra/config/pg-storage.ts
  • src/mastra/agents/editorAgent.ts
  • src/mastra/tools/document-chunking.tool.ts
**/*.{js,ts}

📄 CodeRabbit inference engine (.github/instructions/next-js.instructions.md)

Use parameterized queries or an ORM to prevent SQL injection attacks.

Files:

  • src/mastra/agents/copywriterAgent.ts
  • src/mastra/agents/image_to_csv.ts
  • src/mastra/agents/csv_to_excalidraw.ts
  • src/mastra/tools/pdf-data-conversion.tool.ts
  • src/mastra/agents/image.ts
  • src/mastra/agents/excalidraw_validator.ts
  • src/mastra/config/AuthenticationService.ts
  • src/mastra/config/DocumentIndexingService.ts
  • src/mastra/agents/recharts.ts
  • src/mastra/agents/index.ts
  • src/mastra/agents/contentStrategistAgent.ts
  • src/mastra/config/pg-storage.ts
  • src/mastra/agents/editorAgent.ts
  • src/mastra/tools/document-chunking.tool.ts
src/mastra/agents/**/*.ts

📄 CodeRabbit inference engine (src/mastra/AGENTS.md)

Add new agent definitions under src/mastra/agents that wire tools together into higher-level behaviors

Files:

  • src/mastra/agents/copywriterAgent.ts
  • src/mastra/agents/image_to_csv.ts
  • src/mastra/agents/csv_to_excalidraw.ts
  • src/mastra/agents/image.ts
  • src/mastra/agents/excalidraw_validator.ts
  • src/mastra/agents/recharts.ts
  • src/mastra/agents/index.ts
  • src/mastra/agents/contentStrategistAgent.ts
  • src/mastra/agents/editorAgent.ts
src/mastra/agents/*.ts

📄 CodeRabbit inference engine (src/mastra/agents/AGENTS.md)

src/mastra/agents/*.ts: Agent file naming convention: Create agent files using kebab-case with .ts extension in /src/mastra/agents/ directory (e.g., your-agent-name.ts)
Each agent must follow the pattern: export agent as const yourAgent = new Agent({ id: 'your-agent-id', name: 'Your Agent Name', description: '...' })

Files:

  • src/mastra/agents/copywriterAgent.ts
  • src/mastra/agents/image_to_csv.ts
  • src/mastra/agents/csv_to_excalidraw.ts
  • src/mastra/agents/image.ts
  • src/mastra/agents/excalidraw_validator.ts
  • src/mastra/agents/recharts.ts
  • src/mastra/agents/index.ts
  • src/mastra/agents/contentStrategistAgent.ts
  • src/mastra/agents/editorAgent.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Never commit API keys or secrets to the repository; use maskSensitiveMessageData() helper from src/mastra/config/pg-storage.ts when logging

**/*.{ts,tsx}: Document interface and type definitions with TSDoc comments explaining their purpose and usage context
Document interface properties with /** */ comments explaining each field's purpose and constraints
Document generic type parameters with @template tags explaining what each type parameter represents
Use type guards with comments explaining the runtime validation logic being performed
Document advanced/complex TypeScript types with explanatory comments about their purpose and use cases

Files:

  • src/mastra/agents/copywriterAgent.ts
  • src/mastra/agents/image_to_csv.ts
  • src/mastra/agents/csv_to_excalidraw.ts
  • src/mastra/tools/pdf-data-conversion.tool.ts
  • src/mastra/agents/image.ts
  • src/mastra/agents/excalidraw_validator.ts
  • src/mastra/config/AuthenticationService.ts
  • src/mastra/config/DocumentIndexingService.ts
  • src/mastra/agents/recharts.ts
  • src/mastra/agents/index.ts
  • src/mastra/agents/contentStrategistAgent.ts
  • src/mastra/config/pg-storage.ts
  • src/mastra/agents/editorAgent.ts
  • src/mastra/tools/document-chunking.tool.ts
src/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Run eslint with --max-warnings=0 on src/**/*.{ts,tsx} to enforce linting standards

Files:

  • src/mastra/agents/copywriterAgent.ts
  • src/mastra/agents/image_to_csv.ts
  • src/mastra/agents/csv_to_excalidraw.ts
  • src/mastra/tools/pdf-data-conversion.tool.ts
  • src/mastra/agents/image.ts
  • src/mastra/agents/excalidraw_validator.ts
  • src/mastra/config/AuthenticationService.ts
  • src/mastra/config/DocumentIndexingService.ts
  • src/mastra/agents/recharts.ts
  • src/mastra/agents/index.ts
  • src/mastra/agents/contentStrategistAgent.ts
  • src/mastra/config/pg-storage.ts
  • src/mastra/agents/editorAgent.ts
  • src/mastra/tools/document-chunking.tool.ts
**/*.{ts,tsx,js,jsx,py,java,cs,rb,go,rs,cpp,c,h,hpp,swift,kotlin,php,scala,clj,groovy,lua,sh,bash}

📄 CodeRabbit inference engine (.github/instructions/self-explanatory-code-commenting.instructions.md)

**/*.{ts,tsx,js,jsx,py,java,cs,rb,go,rs,cpp,c,h,hpp,swift,kotlin,php,scala,clj,groovy,lua,sh,bash}: Write code that speaks for itself. Comment only when necessary to explain WHY, not WHAT. Avoid obvious comments that state what the code literally does.
Avoid redundant comments that simply repeat what the code is doing
Keep comments accurate and up-to-date with code changes. Remove or update outdated comments that no longer match the implementation.
Write comments for complex business logic that explain the WHY behind specific calculations or business rules
Document non-obvious algorithms with comments explaining the algorithm choice and its reasoning
Add comments explaining what regex patterns match, especially for complex patterns
Document API constraints, rate limits, gotchas, and external dependencies with explanatory comments
Avoid commenting out dead code. Use version control instead of maintaining commented code blocks.
Do not maintain code change history or modification logs as comments. Rely on git history and commit messages instead.
Avoid decorative divider comments (e.g., lines of equals signs or asterisks) for section separation
Ensure comments are placed appropriately above or adjacent to the code they describe
Write comments using proper grammar, spelling, and professional language
Prefer self-documenting code with clear variable/function names over adding comments to explain unclear code

Files:

  • src/mastra/agents/copywriterAgent.ts
  • src/mastra/agents/image_to_csv.ts
  • src/mastra/agents/csv_to_excalidraw.ts
  • src/mastra/tools/pdf-data-conversion.tool.ts
  • src/mastra/agents/image.ts
  • src/mastra/agents/excalidraw_validator.ts
  • src/mastra/config/AuthenticationService.ts
  • src/mastra/config/DocumentIndexingService.ts
  • src/mastra/agents/recharts.ts
  • src/mastra/agents/index.ts
  • src/mastra/agents/contentStrategistAgent.ts
  • src/mastra/config/pg-storage.ts
  • src/mastra/agents/editorAgent.ts
  • src/mastra/tools/document-chunking.tool.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/instructions/self-explanatory-code-commenting.instructions.md)

**/*.{ts,tsx,js,jsx}: Document public APIs with TSDoc/JSDoc comments including parameter descriptions, return types, examples, and thrown exceptions
Add TSDoc comments to configuration constants and environment variables explaining their source, reasoning, or constraints
Use TSDoc annotation tags (TODO, FIXME, HACK, NOTE, WARNING, PERF, SECURITY, BUG, REFACTOR, DEPRECATED) to mark special comments
Include file headers with @fileoverview, @author, @copyright, and @license tags to document file purpose and ownership
Document function parameters with @param tags, return values with @returns tags, and exceptions with @throws tags in TSDoc comments
Use @see tags in TSDoc comments to reference related functions, methods, or documentation
Include @example tags in public API documentation with code examples showing typical usage

Files:

  • src/mastra/agents/copywriterAgent.ts
  • src/mastra/agents/image_to_csv.ts
  • src/mastra/agents/csv_to_excalidraw.ts
  • src/mastra/tools/pdf-data-conversion.tool.ts
  • src/mastra/agents/image.ts
  • src/mastra/agents/excalidraw_validator.ts
  • src/mastra/config/AuthenticationService.ts
  • src/mastra/config/DocumentIndexingService.ts
  • src/mastra/agents/recharts.ts
  • src/mastra/agents/index.ts
  • src/mastra/agents/contentStrategistAgent.ts
  • src/mastra/config/pg-storage.ts
  • src/mastra/agents/editorAgent.ts
  • src/mastra/tools/document-chunking.tool.ts
src/mastra/**/*

📄 CodeRabbit inference engine (src/AGENTS.md)

mastra modules can import from utils, but must not import from app or cli (except types)

Files:

  • src/mastra/agents/copywriterAgent.ts
  • src/mastra/agents/image_to_csv.ts
  • src/mastra/agents/csv_to_excalidraw.ts
  • src/mastra/tools/pdf-data-conversion.tool.ts
  • src/mastra/agents/image.ts
  • src/mastra/agents/excalidraw_validator.ts
  • src/mastra/config/AuthenticationService.ts
  • src/mastra/config/DocumentIndexingService.ts
  • src/mastra/agents/recharts.ts
  • src/mastra/agents/index.ts
  • src/mastra/agents/contentStrategistAgent.ts
  • src/mastra/config/pg-storage.ts
  • src/mastra/agents/editorAgent.ts
  • src/mastra/tools/document-chunking.tool.ts
src/mastra/tools/**/*.ts

📄 CodeRabbit inference engine (src/mastra/AGENTS.md)

src/mastra/tools/**/*.ts: Use the createTool pattern with Zod schemas when adding new tools under src/mastra/tools
Use explicit Zod schemas for every tool input/output

src/mastra/tools/**/*.ts: Use Zod schemas for strict validation of tool inputs and outputs in all Mastra tools
Implement tools using the createTool({ id, inputSchema, outputSchema, execute }) pattern
Organize tools into categories: Financial (Polygon, Finnhub, AlphaVantage), Research (SerpAPI, ArXiv), Data (CSV, JSON), RAG (chunking, embeddings)

Files:

  • src/mastra/tools/pdf-data-conversion.tool.ts
  • src/mastra/tools/document-chunking.tool.ts
src/mastra/{tools,workflows}/**/*.ts

📄 CodeRabbit inference engine (src/mastra/AGENTS.md)

Use RuntimeContext to enforce access control in tools and workflows

Files:

  • src/mastra/tools/pdf-data-conversion.tool.ts
  • src/mastra/tools/document-chunking.tool.ts
src/mastra/tools/**/*.tool.ts

📄 CodeRabbit inference engine (src/mastra/tools/AGENTS.md)

src/mastra/tools/**/*.tool.ts: Define Zod schema for inputs and outputs when creating tools
Tool IDs should follow the 'namespace:toolName' format (e.g., 'alpha-vantage:stockTool')

Files:

  • src/mastra/tools/pdf-data-conversion.tool.ts
  • src/mastra/tools/document-chunking.tool.ts
src/mastra/tools/**/*.{ts,tsx}

📄 CodeRabbit inference engine (src/mastra/tools/AGENTS.md)

src/mastra/tools/**/*.{ts,tsx}: All tools must include comprehensive error handling with try-catch blocks, clear error messages, and retry logic for API calls
Sanitize inputs, mask secrets in logs, and implement rate-limiting in tools
Implement caching, stream large data, and set timeouts for external API calls in tools
Add Arize spans on all tool execute functions for observability

Files:

  • src/mastra/tools/pdf-data-conversion.tool.ts
  • src/mastra/tools/document-chunking.tool.ts
src/mastra/config/**/*.ts

📄 CodeRabbit inference engine (AGENTS.md)

src/mastra/config/**/*.ts: Centralize provider clients (Google, OpenAI, Anthropic, OpenRouter) and storage configuration in src/mastra/config
Use pg-storage with PgVector for vector store functionality in the configuration
Use src/mastra/config for role hierarchy and provider client configuration

Files:

  • src/mastra/config/AuthenticationService.ts
  • src/mastra/config/DocumentIndexingService.ts
  • src/mastra/config/pg-storage.ts
src/mastra/config/pg-storage.ts

📄 CodeRabbit inference engine (src/mastra/config/AGENTS.md)

src/mastra/config/pg-storage.ts: PostgreSQL storage configuration must include PgVector support for embeddings, memory, and thread persistence
Database connection must use the SUPABASE environment variable with optional performance tuning via DB_MAX_CONNECTIONS, DB_IDLE_TIMEOUT, and DB_CONNECTION_TIMEOUT
Memory configuration must support MEMORY_LAST_MESSAGES, SEMANTIC_TOP_K, SEMANTIC_RANGE_BEFORE, SEMANTIC_RANGE_AFTER, and LISTS environment variables
RAG configuration must support GRAPH_THRESHOLD, GRAPH_RANDOM_WALK_STEPS, GRAPH_RESTART_PROB, PG_MIN_SCORE, and PG_EF environment variables

Files:

  • src/mastra/config/pg-storage.ts
🧬 Code graph analysis (5)
src/mastra/agents/image_to_csv.ts (1)
src/mastra/config/agent-schemas.ts (1)
  • identityOutputSchema (74-76)
src/mastra/agents/image.ts (2)
src/mastra/config/google.ts (1)
  • googleAINanoBanana (98-98)
src/mastra/config/pg-storage.ts (1)
  • pgMemory (87-151)
src/mastra/agents/excalidraw_validator.ts (1)
src/mastra/agents/index.ts (1)
  • ExcalidrawValidatorRuntimeContext (20-20)
src/mastra/agents/recharts.ts (1)
src/mastra/agents/index.ts (1)
  • ChartRuntimeContext (12-12)
src/mastra/tools/document-chunking.tool.ts (1)
src/mastra/config/google.ts (1)
  • google (42-44)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Agent
  • GitHub Check: Codacy Security Scan
🔇 Additional comments (20)
src/mastra/tools/pdf-data-conversion.tool.ts (2)

34-42: LGTM! Improved parameter naming clarity.

Removing the underscore prefix from buffer and options parameters improves code readability and follows TypeScript conventions. The underscore prefix is typically reserved for explicitly unused parameters, which doesn't apply here since these are part of the function type signature.


550-552: LGTM! Enhanced observability with tracing attributes.

Adding filePath and sizeBytes attributes to the read span improves debugging and performance monitoring capabilities. This aligns with the coding guideline to add Arize spans on all tool execute functions for observability.

src/mastra/agents/copywriterAgent.ts (1)

12-13: LGTM!

The import refactoring is clean and consistent with the actual usage in the file. The googleAIFlashLite model is correctly referenced at line 128, and the structureScorer is properly used in the scorers configuration at lines 139-144.

src/mastra/agents/contentStrategistAgent.ts (2)

24-30: LGTM!

The context retrieval pattern with nullish coalescing provides sensible defaults. The defensive defaults ensure the agent functions correctly even when context values are not provided.


35-48: LGTM!

The strategy and approach sections are well-structured with clear interpolation of context values. The numbered steps in the approach provide actionable guidance for the agent, and the backup tools contingency plan adds resilience.

src/mastra/agents/image.ts (2)

58-61: LGTM: Empty object initialization.

The explicit initialization of options, tools, scorers, and workflows as empty objects is consistent with standardizing the agent interface, as mentioned in the PR objectives. This makes the agent's structure more explicit and easier to extend in the future.


3-3: Model change from Imagen 4 to Gemini 2.5 Flash Image may impact output quality.

The agent switches from imageGen (Imagen 4 Standard—Google's purpose-built image generation model) to googleAINanoBanana (Gemini 2.5 Flash Image—a general-purpose multimodal model). While Gemini 2.5 Flash Image does support the required aspect ratios (1:1, 2:3, 3:2, 3:4, 4:3, 4:5, 5:4, 9:16, 16:9, 21:9) and resolution configuration via image_config, this represents a significant architectural downgrade. Imagen 4 is optimized specifically for image generation quality, whereas Gemini 2.5 Flash is a general-purpose model with image generation as a secondary capability. Verify this change is intentional and acceptable for your use case, particularly regarding image quality expectations and any API parameter compatibility issues between the two models.

src/mastra/config/pg-storage.ts (2)

113-147: Working memory template enhancement looks good.

The new workingMemory configuration with scope: 'resource', version: 'vnext', and the structured markdown template provides a comprehensive user profile schema. This aligns well with the PR objective of improving memory management.


104-111: Verify the indentation and schema for semanticRecall configuration properties.

The placement of threshold and indexName relative to the indexConfig block cannot be confirmed without access to the @mastra/memory type definitions. Ensure that lines 109-110 are correctly nested according to the expected schema — they should either be inside indexConfig or at the semanticRecall level, depending on the interface definition.

src/mastra/agents/editorAgent.ts (1)

8-8: LGTM!

The import cleanup correctly removes unused scorers (responseQualityScorer, structureScorer, toneConsistencyScorer) and retains only summaryQualityScorer, which matches the actual usage in the scorers configuration.

src/mastra/agents/csv_to_excalidraw.ts (2)

7-9: LGTM!

The interface rename from DaneContext to CsvToExcalidrawRuntimeContext improves clarity and aligns with the naming convention used across other agents in this PR.


15-15: Type update is consistent with the new context interface.

src/mastra/agents/image_to_csv.ts (2)

21-36: Context retrieval and prompt interpolation look correct.

The new context fields are properly retrieved with sensible defaults and interpolated into the system prompt. The type safety from RequestContext<ImageToCsvRuntimeContext> ensures valid values.


9-15: Remove the suggested rename—no naming conflict exists.

The fields identityOutputSchema and chalkboardOutputSchema in ImageToCsvRuntimeContext are locally scoped to this file and used appropriately as context fields that specify output format preferences. The search found no conflicting definitions in agent-schemas.ts or elsewhere. The naming is descriptive and clear: these fields indicate which schema format (excalidraw or CSV) should be used for each diagram type.

Likely an incorrect or invalid review comment.

src/mastra/agents/recharts.ts (2)

31-36: LGTM!

The ChartRuntimeContext interface provides appropriate fields for chart customization (chartStyle, colorScheme) alongside the common tier and language fields used across other agents.


48-52: Consistent context usage across chart agents.

All four chart agents (chartTypeAdvisorAgent, chartDataProcessorAgent, chartGeneratorAgent, chartSupervisorAgent) consistently use RequestContext<ChartRuntimeContext> and retrieve the same context fields with matching defaults.

src/mastra/tools/document-chunking.tool.ts (2)

8-8: LGTM!

The MastraAgentRelevanceScorer import is correctly grouped with other @mastra/rag imports.


792-792: LGTM!

The MastraAgentRelevanceScorer correctly uses google('gemini-1.5-flash') as the language model for semantic relevance scoring. This is distinct from the embedding model (google.textEmbedding('gemini-embedding-001')) used for vector generation.

src/mastra/agents/excalidraw_validator.ts (1)

17-27: Instruction handler typing and prompt wiring look correct

Using RequestContext<ExcalidrawValidatorRuntimeContext> and retrieving userId, 'user-tier', and language by key is consistent with the new context shape, and the injected user, tier, and language lines in the system prompt should give the model enough metadata to adapt behavior per user/tier. No functional issues from the changes here.

src/mastra/agents/index.ts (1)

1-23: Expanded runtime-context exports are coherent and improve discoverability

The added *RuntimeContext/*Context type re-exports are consistent with the agent modules they come from and make the public API surface more convenient for consumers that need to type their RequestContexts. No issues from this aggregation change.

Comment on lines +10 to 18
export type UserTier = 'free' | 'pro' | 'enterprise'
export interface ContentAgentContext {
userId?: string
'user-tier': UserTier
staggeredOutput?: boolean
sectionCount?: number
strategy?: 'iceberg' | 'blue-ocean' | 'structured' | 'hybrid' | 'custom'
backupDataTools?: string[]
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

Add TSDoc documentation for exported types.

Per coding guidelines, exported interface and type definitions should include TSDoc comments explaining their purpose and usage context.

+/**
+ * User subscription tier determining available features and capabilities.
+ */
 export type UserTier = 'free' | 'pro' | 'enterprise'
+
+/**
+ * Runtime context for the Content Strategist agent.
+ * @property userId - Optional identifier for the requesting user
+ * @property userTier - User's subscription tier (defaults to 'free')
+ * @property staggeredOutput - Whether to stagger content output
+ * @property sectionCount - Number of sections to generate
+ * @property strategy - Content strategy approach to use
+ * @property backupDataTools - Fallback tools for data retrieval
+ */
 export interface ContentAgentContext {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export type UserTier = 'free' | 'pro' | 'enterprise'
export interface ContentAgentContext {
userId?: string
'user-tier': UserTier
staggeredOutput?: boolean
sectionCount?: number
strategy?: 'iceberg' | 'blue-ocean' | 'structured' | 'hybrid' | 'custom'
backupDataTools?: string[]
}
/**
* User subscription tier determining available features and capabilities.
*/
export type UserTier = 'free' | 'pro' | 'enterprise'
/**
* Runtime context for the Content Strategist agent.
* @property userId - Optional identifier for the requesting user
* @property user-tier - User's subscription tier (defaults to 'free')
* @property staggeredOutput - Whether to stagger content output
* @property sectionCount - Number of sections to generate
* @property strategy - Content strategy approach to use
* @property backupDataTools - Fallback tools for data retrieval
*/
export interface ContentAgentContext {
userId?: string
'user-tier': UserTier
staggeredOutput?: boolean
sectionCount?: number
strategy?: 'iceberg' | 'blue-ocean' | 'structured' | 'hybrid' | 'custom'
backupDataTools?: string[]
}

⚠️ Potential issue | 🟡 Minor

Type inconsistency: required field with runtime fallback.

The 'user-tier' field is defined as required (no ?), but line 26 uses a fallback (?? 'free'), implying it may be undefined at runtime. Either:

  1. Make the field optional ('user-tier'?: UserTier) to match the runtime behavior, or
  2. Remove the fallback if callers are expected to always provide this value.

Additionally, consider using camelCase (userTier) instead of a hyphenated key for idiomatic TypeScript property access.

 export type UserTier = 'free' | 'pro' | 'enterprise'
 export interface ContentAgentContext {
     userId?: string
-    'user-tier': UserTier
+    userTier?: UserTier
     staggeredOutput?: boolean
     sectionCount?: number
     strategy?: 'iceberg' | 'blue-ocean' | 'structured' | 'hybrid' | 'custom'
     backupDataTools?: string[]
 }

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In src/mastra/agents/contentStrategistAgent.ts around lines 10 to 18, the
interface declares 'user-tier' as required but code uses a runtime fallback (??
'free'), creating a type/runtime mismatch; update the interface so the field is
optional ('user-tier'?: UserTier) to reflect that it may be undefined at runtime
or, alternatively, remove the fallback where the value is assumed present; also
refactor the property name to camelCase (userTier) throughout the file and call
sites to follow TypeScript conventions, updating types, destructuring, and any
indexed accesses accordingly.

Comment on lines 6 to 11
export type UserTier = 'free' | 'pro' | 'enterprise'
export interface KnowledgeIndexingContext {
export interface ExcalidrawValidatorRuntimeContext {
userId?: string
indexName?: string
chunkSize?: number
chunkOverlap?: number
chunkingStrategy?: string
'user-tier': UserTier
language: 'en' | 'es' | 'ja' | 'fr'
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

Align runtime-context typings with actual defaults and add brief TSDoc

ExcalidrawValidatorRuntimeContext marks 'user-tier' and language as required, but the instructions handler also supplies sane defaults when they’re absent. Consider either:

  • Making 'user-tier' and language optional in the interface, or
  • Treating them as truly required and dropping the ?? 'free' / ?? 'en' defaults.

Aligning the type with the actual expectations will make callers clearer. Also, since this is a public runtime-context type, adding a short TSDoc comment on the interface and each field (what user-tier controls, supported languages, etc.) would help other agent authors.

🤖 Prompt for AI Agents
In src/mastra/agents/excalidraw_validator.ts around lines 6 to 11, the
ExcalidrawValidatorRuntimeContext interface marks 'user-tier' and language as
required even though the handler supplies defaults; make 'user-tier' and
language optional (user-tier?: UserTier; language?: 'en' | 'es' | 'ja' | 'fr')
so the type matches runtime behavior, and add short TSDoc comments on the
interface and each field describing purpose, default behavior (e.g., default
'free' and 'en' when absent), and supported values to help other authors.


import { ValidationService } from './ValidationService'
import { RoleService } from './RoleService'
import { RoleService } from './role-service'
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check for RoleService files in src/mastra/config with any casing
fd -i 'role.?service' src/mastra/config/ || echo "No role-service variants found"
echo "---"
# Also check the exact import target
ls -la src/mastra/config/ | grep -i role || echo "No role-related files found via ls"

Repository: ssdeanx/AgentStack

Length of output: 180


🌐 Web query:

ssdeanx/AgentStack repository src/mastra/config RoleService file naming

💡 Result:

Do you want me to (A) look up the actual RoleService file name in that repo on GitHub, or (B) recommend a naming convention (e.g., RoleService.ts vs role.service.ts)? Which one?


🌐 Web query:

site:github.com ssdeanx/AgentStack src/mastra/config RoleService.ts OR role-service.ts

💡 Result:

I couldn't find a file named RoleService.ts or role-service.ts under src/mastra/config in the ssdeanx/AgentStack repository. The repository and its src/mastra/config folder listing (where such a file would live) are here for inspection: [1], [2].

Sources:

  • ssdeanx/AgentStack repository root. [1]
  • src/mastra/config folder in ssdeanx/AgentStack. [2]

🌐 Web query:

site:github.com ssdeanx/AgentStack RoleService OR role-service filetype:ts

💡 Result:

I searched GitHub for that query.

  • The AgentStack repository (ssdeanx/AgentStack) exists — README and codebase. [1]
  • I did not find a TypeScript file named RoleService or role-service in ssdeanx/AgentStack from the search results; however a related repo (secure-rag-multi-agent / governed-rag-ai) documents a "Role Service" in its service list. [2]

If you want, I can (A) search the AgentStack repo contents more deeply (file-by-file) for "role" or "RoleService" and return matching file paths, or (B) open the specific repos and inspect likely auth/RBAC files. Which would you prefer?

Sources:
[1] ssdeanx/AgentStack (GitHub).
[2] ssdeanx secure-rag-multi-agent / governed-rag-ai (GitHub).


🌐 Web query:

site:github.com/ssdeanx/AgentStack "RoleService" OR "role-service" file path

💡 Result:

I searched the AgentStack repository and found no files or paths matching "RoleService" or "role-service". [1]

For comparison, a different ssdeanx repo (secure-rag-multi-agent) does list a "Role Service" in its services overview. [2]

Sources:

  • AgentStack repository file listing. [1]
  • secure-rag-multi-agent repository (mentions Role Service). [2]

Remove broken import or provide the missing RoleService module

The import './role-service' references a file that does not exist in src/mastra/config/. This import will fail at runtime. Either:

  • Remove this import and its usage if RoleService is not needed, or
  • Provide the missing role-service.ts file in src/mastra/config/
🤖 Prompt for AI Agents
In src/mastra/config/AuthenticationService.ts around line 4, the import "import
{ RoleService } from './role-service'" points to a non-existent module; remove
the broken import and any usage of RoleService if it's not required, or add a
new src/mastra/config/role-service.ts implementing the exported RoleService
interface/class used by AuthenticationService. If removing, search the file for
RoleService references and delete or refactor those lines to use existing
services or mocks; if adding, create the role-service.ts that exports the
expected symbol with the methods/properties AuthenticationService calls, and
update any type imports accordingly.

options: {
// Message management
lastMessages: parseInt(process.env.MEMORY_LAST_MESSAGES ?? '500'),
generateTitle: process.env.THREAD_GENERATE_TITLE !== 'true',
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

cat -n src/mastra/config/pg-storage.ts | head -120 | tail -40

Repository: ssdeanx/AgentStack

Length of output: 2314


🏁 Script executed:

rg "THREAD_GENERATE_TITLE" -i --no-heading

Repository: ssdeanx/AgentStack

Length of output: 693


🏁 Script executed:

rg "generateTitle" -A 3 -B 3

Repository: ssdeanx/AgentStack

Length of output: 7004


🏁 Script executed:

rg "THREAD_GENERATE_TITLE" -B 5 -A 2 --no-heading

Repository: ssdeanx/AgentStack

Length of output: 3319


🏁 Script executed:

grep -r "generateTitle" app/docs/ docs/ --include="*.md*" -B 2 -A 2

Repository: ssdeanx/AgentStack

Length of output: 1150


Inverted boolean logic is inconsistent with other storage backends and documentation.

Line 94 uses process.env.THREAD_GENERATE_TITLE !== 'true', meaning generateTitle is true when the env var is NOT set to 'true'. This is counterintuitive—setting THREAD_GENERATE_TITLE=true should enable title generation, not disable it.

Additionally, this pattern is inconsistent with other storage backends:

  • lance.ts and cloudflare.ts use !== 'false' (opt-in with false as disable)
  • Documentation examples show generateTitle: true as the expected default behavior

To align with semantic intent and other backends:

-        generateTitle: process.env.THREAD_GENERATE_TITLE !== 'true',
+        generateTitle: process.env.THREAD_GENERATE_TITLE !== 'false',
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
generateTitle: process.env.THREAD_GENERATE_TITLE !== 'true',
generateTitle: process.env.THREAD_GENERATE_TITLE !== 'false',
🤖 Prompt for AI Agents
In src/mastra/config/pg-storage.ts around line 94, the boolean is inverted:
currently generateTitle is set using process.env.THREAD_GENERATE_TITLE !==
'true', which makes the feature enabled when the env var is not 'true'. Change
this to process.env.THREAD_GENERATE_TITLE !== 'false' so that
THREAD_GENERATE_TITLE=false will disable title generation, matching the pattern
used in lance.ts and cloudflare.ts and the documented default behavior.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants