Skip to content

Conversation

@ssdeanx
Copy link
Owner

@ssdeanx ssdeanx commented Dec 6, 2025

No description provided.

- Removed unnecessary whitespace in the dependencies section.
- Added "@mdx-js/loader" and "@tanstack/eslint-config" to devDependencies.
- Removed duplicate entry for "@mdx-js/loader" from devDependencies.
- Added "remark-frontmatter" and "remark-mdx-frontmatter" back to devDependencies.
- Created a new agent documentation file for TypeScript MCP Server Expert.
- Included detailed expertise areas such as TypeScript MCP SDK, schema validation with zod, and best practices for building robust MCP servers.
- Outlined guidelines for using ES modules, schema definitions, error handling, and testing strategies.

docs: Provide CI and testing guidance for Mastra v1 migration
- Added a comprehensive CI and testing guidance document for migrating to Mastra v1.
- Included commands for preflight checks, running global and per-area codemods, and CI checklist for PRs.
- Provided GitHub Actions snippet for CI configuration.

docs: Create context migration scratchpad for Mastra v1
- Documented decisions made during the migration planning phase.
- Listed blockers and open questions regarding the migration process.
- Outlined next steps for executing the migration.

docs: Develop design document for Mastra v1 migration
- Created a design document detailing the migration approach for Mastra v1.
- Highlighted breaking changes across various subsystems and proposed a structured migration plan.
- Included example code changes and testing strategies.

docs: Compile manual fixes and prioritized work items for migration
- Documented manual fixes required after automated codemods for Mastra v1 migration.
- Organized tasks by scope, representative files, and acceptance criteria for each change.

docs: Outline PRD for upgrading to Mastra v1
- Drafted a Product Requirements Document (PRD) for the upgrade to Mastra v1.
- Defined the problem, goals, success criteria, stakeholders, timeline, risks, and rollback plans.

docs: Conduct scan results audit for memory API migration
- Compiled scan results documenting occurrences of the old Mastra v0.x API surface.
- Identified high-risk areas and provided actionable work items for migration.

docs: Create tasks worklist for full Mastra v1 migration
- Developed a detailed tasks document outlining the full migration worklist.
- Included pre-flight checks, manual replacements, testing, documentation updates, and CI verification steps.
- Updated null checks in various components to use curly braces for consistency and clarity.
- Enhanced error handling in the NetworkAgents, NetworkChat, NetworkInfoPanel, NetworkRoutingPanel, and Workflow components to return null or handle errors gracefully when configurations are missing.

fix: resolve import issues in test setup
- Added a new test file for the POST handler in the chat API to ensure proper functionality.
- Mocked necessary dependencies for the tests to isolate the handler logic and validate responses.

style: clean up code formatting
- Removed unnecessary whitespace and ensured consistent formatting across multiple files.
- Adjusted code for better readability and maintainability.

test: add tests for chat API POST handler
- Implemented tests to check for missing messages and validate the use of nested data.agentId.
- Ensured that the tests cover both successful and error scenarios for the POST request.
Copilot AI review requested due to automatic review settings December 6, 2025 17:57
@continue
Copy link

continue bot commented Dec 6, 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

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, your pull request is larger than the review limit of 150000 diff characters

@coderabbitai
Copy link

coderabbitai bot commented Dec 6, 2025

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Summary by CodeRabbit

  • New Features

    • Added multiple agent configuration specifications for specialized AI personas
    • Added authentication module with email/password sign-in support
    • Introduced sensitive data masking utilities for enhanced privacy
    • Added CORS configuration for improved API accessibility
    • Enhanced API flexibility to support multiple request payload formats
  • Bug Fixes

    • Fixed test suite failures; all tests now passing
    • Improved component stability with better null/undefined handling
  • Performance

    • Switched vector indexing to HNSW for optimized search performance
  • Documentation

    • Added comprehensive Mastra v1 migration guides and planning resources

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

Walkthrough

Adds twelve new agent specification Markdown files, updates the chat API to accept nested or top-level payload shapes, shifts many UI components to nullish-coalescing and explicit guards, introduces explicit error paths for several unhandled statuses, updates Mastra configuration and storage initialization, and adds comprehensive Mastra v1 migration documentation.

Changes

Cohort / File(s) Summary
Agent Configuration Files
\.github/agents/4.1-Beast.agent.md, \.github/agents/Thinking-Beast-Mode.agent.md, \.github/agents/code-tour.agent.md, \.github/agents/custom-agent-foundry.agent.md, \.github/agents/expert-nextjs-developer.agent.md, \.github/agents/expert-react-frontend-engineer.agent.md, \.github/agents/gpt-5-beast-mode.agent.md, \.github/agents/prompt-builder.agent.md, \.github/agents/prompt-engineer.agent.md, \.github/agents/python-mcp-expert.agent.md, \.github/agents/search-ai-optimization-expert.agent.md, \.github/agents/typescript-mcp-expert.agent.md
Adds twelve new Markdown-based agent spec files defining personas, workflows, tool rules, and response formats (no runtime code changes).
Chat API
app/api/chat/r.ts
Extends ChatRequestBody to accept top-level fields and nested data object; adds fallback resolution for agentId, threadId, resourceId, and memory; adapts request shaping for downstream Mastra calls.
Chat UI Components
app/chat/components/* (e.g., agent-artifact.tsx, agent-plan.tsx, agent-web-preview.tsx, chat-header.tsx, chat-input.tsx, chat-messages.tsx, agent-tools.tsx, etc.)
Consistent stylistic and defensive changes: replace `
Chat Context & Helpers
app/chat/providers/chat-context.tsx, app/chat/helpers/tool-part-transform.ts
Restructures prepareSendMessagesRequest payload (nested body, memory/data fields), strengthens guards and optional chaining, and refactors tool-part normalization for safer type handling.
Network & Workflow Components
app/networks/*, app/workflows/*
Similar defensive and stylistic refactors across network and workflow UI/providers; several components now throw explicit "Not implemented" for statuses like pending, skipped, idle, paused.
Mastra Core & Config
src/mastra/index.ts, src/mastra/config/mongodb.ts, src/mastra/config/pg-storage.ts, src/mastra/tools/diff-review.tool.ts
Adds utility agents and expanded defaultOptions (memory/thread settings), introduces CORS config, stronger middleware guards; initializes Mongo vector index (HNSW) and enhances Postgres store with masking utilities, vector tools, embedding helper exports.
Migration Documentation
memory-bank/progress.md, memory-bank/upgrade-to-v1/*
Adds comprehensive Mastra v1 migration docs: PRD, design, scan-results, tasks, manual fixes, CI/testing guidance, and migration context.
Tests & Test Results
tests/api-chat-r.test.ts, tests/test-results/test-results.json
Adds unit tests for chat POST handler; updates test-results JSON to a passing state in the tracked file.
Build & Config
package.json, eslint.config.cjs, .env.example, lib/auth.ts
Bumps package version and several deps; reorganizes MDX-related packages; updates ESLint ignore globs; removes WorkOS env placeholders; adds new lib/auth.ts with Supabase sign-in sample.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Areas requiring extra attention:

  • app/api/chat/r.ts — Verify new ChatRequestBody shape and fallback logic against downstream Mastra expectations and clients.
  • app/chat/providers/chat-context.tsx — Confirm prepareSendMessagesRequest payload nesting (body/data/memory) aligns with server API and Mastra middleware.
  • src/mastra/config/pg-storage.ts & src/mastra/config/mongodb.ts — Review initialization side effects (await init(), createIndex) and HNSW index parameters for production safety.
  • Components that now throw on statuses (pending, skipped, idle, paused) — Ensure those statuses cannot appear in current data flows or that callers handle thrown errors.
  • Nullish-coalescing changes (?? vs ||) — Confirm behavior for empty string values where previous || would coerce to fallback.

Possibly related PRs

Poem

🐰 I hopped through code with careful paws,

Twelve agents stitched without a pause,
Nullish paths and guarded gates,
New indexes, docs, and tidy traits—
A little rabbit cheers the merge, hooray! 🥕✨

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings, 1 inconclusive)
Check name Status Explanation Resolution
Description check ⚠️ Warning No pull request description was provided by the author; the description field is completely empty. Add a clear pull request description that explains the changes, their purpose, and any relevant context for reviewers.
Docstring Coverage ⚠️ Warning Docstring coverage is 15.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Title check ❓ Inconclusive The title 'Develop' is vague and non-descriptive; it does not convey meaningful information about the changeset's purpose or primary changes. Use a descriptive title that summarizes the main change, such as 'Add agent configuration frameworks and upgrade Mastra dependencies' or 'Migrate to Mastra v1 with agent specs and tooling updates'.
✨ 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.

@github-actions
Copy link

github-actions bot commented Dec 6, 2025

🤖 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.

@github-actions
Copy link

github-actions bot commented Dec 6, 2025

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

@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 expands the system's AI capabilities by introducing a wide array of new agent definitions tailored for specialized tasks. Concurrently, it lays crucial groundwork for a major platform upgrade (Mastra v1) through detailed migration documentation and planning. The changes also encompass general code quality enhancements, dependency updates, and configuration refinements across the codebase, ensuring a more robust and maintainable application.

Highlights

  • New Agent Definitions: A significant number of new AI agent definitions have been added, expanding the system's capabilities across various specialized domains including coding, prompt engineering, Next.js, React, Python MCP, TypeScript MCP, and search optimization.
  • Mastra v1 Migration Planning: Comprehensive documentation for the Mastra v1 migration has been introduced, detailing CI/testing guidance, design considerations, manual fixes, product requirements, scan results, and a full worklist for the upgrade process.
  • Code Quality Improvements: Extensive refactoring has been performed across several frontend components and API routes, replacing logical OR (||) with the nullish coalescing operator (??) and explicitly casting boolean checks, enhancing code robustness and readability.
  • Dependency and Configuration Updates: The project's package.json has been updated to version 1.0.7, along with several dependency bumps. The eslint.config.cjs file has been refined with updated ignore patterns and removed deprecated rules, improving linting and code style enforcement.
  • API Route and Mastra Configuration Enhancements: The chat API route (app/api/chat/r.ts) now supports legacy nested data fields for agent selection and src/mastra/index.ts includes updated memory options and telemetry configurations for network routes, along with refined body.data access logic.
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.

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 represents a develop branch merge containing multiple categories of changes: dependency updates, new test coverage, style/formatting improvements, and comprehensive migration documentation for Mastra v1.

Key Changes:

  1. Version bump from 1.0.6 to 1.0.7
  2. Dependency updates including ai-sdk, lucide-react, and various Mastra packages, with reorganization between dependencies and devDependencies
  3. New test file (tests/api-chat-r.test.ts) providing coverage for the chat API endpoint
  4. Style/formatting changes across multiple files with brace placement adjustments and return statement formatting
  5. Migration documentation with comprehensive guides for upgrading to Mastra v1 in the memory-bank/upgrade-to-v1/ directory

Reviewed changes

Copilot reviewed 59 out of 60 changed files in this pull request and generated 6 comments.

Show a summary per file
File Description
tests/test-results/test-results.json Test results show improvement from 18 failed suites to 2 passing suites
tests/api-chat-r.test.ts New test file for POST /api/chat/r endpoint with basic validation tests
src/mastra/tools/diff-review.tool.ts Whitespace cleanup and brace formatting changes
src/mastra/index.ts Configuration updates including removal of includeTextStreamParts and addition of new options
package.json & package-lock.json Version bump and dependency updates with package reorganization
app/ (multiple files) Consistent formatting changes including brace placement and return statement style
memory-bank/upgrade-to-v1/ Comprehensive migration documentation including PRD, design, tasks, scan results, and CI/testing guides
eslint.config.cjs Updated ignore patterns for better linting coverage

Comment on lines +130 to +131
if (additions > 0) {parts.push(`${additions} addition${additions !== 1 ? 's' : ''}`)}
if (deletions > 0) {parts.push(`${deletions} deletion${deletions !== 1 ? 's' : ''}`)}
Copy link

Copilot AI Dec 6, 2025

Choose a reason for hiding this comment

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

[nitpick] Unnecessary braces around single statements reduce code readability. These single-statement if blocks should not have braces according to standard JavaScript/TypeScript style conventions. Consider removing the braces:

if (additions > 0) parts.push(`${additions} addition${additions !== 1 ? 's' : ''}`)
if (deletions > 0) parts.push(`${deletions} deletion${deletions !== 1 ? 's' : ''}`)

Copilot uses AI. Check for mistakes.
path: "/workflow",
workflow: "repoIngestionWorkflow",
includeTextStreamParts: true,

Copy link

Copilot AI Dec 6, 2025

Choose a reason for hiding this comment

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

[nitpick] The removal of includeTextStreamParts: true appears intentional but lacks context. If this is a breaking change or configuration update, consider adding a comment explaining why this parameter was removed.

Copilot uses AI. Check for mistakes.
Comment on lines +26 to +27
case "idle": { throw new Error('Not implemented yet: "idle" case') }
case "paused": { throw new Error('Not implemented yet: "paused" case') }
Copy link

Copilot AI Dec 6, 2025

Choose a reason for hiding this comment

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

Throwing errors with "Not implemented yet" messages for valid enum cases suggests incomplete implementation. These cases should either be properly implemented or, if they're truly unreachable in the current workflow, use TypeScript's exhaustiveness checking pattern instead:

const _exhaustiveCheck: never = status;
throw new Error(`Unhandled status: ${_exhaustiveCheck}`);

This applies to lines 26-27 and line 43.

Copilot uses AI. Check for mistakes.
Comment on lines +97 to +99
if ((Boolean(rawState.includes("stream"))) || (Boolean(rawState.includes("pending")))) {state = "input-streaming"}
else if ((Boolean(rawState.includes("success"))) || (Boolean(rawState.includes("done"))) || (Boolean(rawState.includes("completed"))) || (Boolean(output))) {state = "output-available"}
else if ((Boolean(rawState.includes("error"))) || (Boolean(rawState.includes("failed")))) {state = "output-error"}
Copy link

Copilot AI Dec 6, 2025

Choose a reason for hiding this comment

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

[nitpick] Wrapping conditions in Boolean() is unnecessary and reduces readability. JavaScript's || and other boolean operators already handle truthiness correctly:

if (rawState.includes("stream") || rawState.includes("pending")) state = "input-streaming"
else if (rawState.includes("success") || rawState.includes("done") || rawState.includes("completed") || output) state = "output-available"
else if (rawState.includes("error") || rawState.includes("failed")) state = "output-error"

The Boolean() wrapper adds no value and makes the code harder to read.

Copilot uses AI. Check for mistakes.

import { ModelProvider, ModelCapability, ModelConfig, ProviderConfig } from './models';
import type { ModelConfig, ProviderConfig } from './models';
import { ModelProvider, ModelCapability } from './models';
Copy link

Copilot AI Dec 6, 2025

Choose a reason for hiding this comment

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

Unused imports ModelCapability, ModelProvider.

Suggested change
import { ModelProvider, ModelCapability } from './models';

Copilot uses AI. Check for mistakes.
@@ -0,0 +1,37 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
Copy link

Copilot AI Dec 6, 2025

Choose a reason for hiding this comment

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

Unused import beforeEach.

Copilot uses AI. Check for mistakes.
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 large number of changes, including adding many new agent definitions, updating dependencies, refactoring UI components for better code style and robustness, and improving API compatibility. Several new markdown files have been added to plan and track a migration to "Mastra v1". The code changes largely focus on improving code quality by using nullish coalescing operators (??) instead of logical OR (||), adding braces to single-line if statements for clarity and safety, and making code more robust against unexpected data shapes.

I've found a few minor issues in the new agent definition files and a potential type error in one of the React components. Overall, the changes are positive and move the codebase in a good direction.

const toolName = t.toolName || "unknown"
const toolType = `tool-${toolName}` as ToolUIPart["type"]
const toolState = t.state as ToolState
const toolType = `tool-${toolName}`
Copy link
Contributor

Choose a reason for hiding this comment

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

high

The type cast as ToolUIPart["type"] was removed from toolType, but it seems necessary for the ToolHeader component. Other files in this PR, like app/networks/components/network-chat.tsx, still perform this cast. This change might introduce a type error. Please consider re-adding the cast to ensure type compatibility.

Suggested change
const toolType = `tool-${toolName}`
const toolType = `tool-${toolName}` as ToolUIPart["type"]


THE PROBLEM CAN NOT BE SOLVED WITHOUT EXTENSIVE INTERNET RESEARCH.

You must use the fetch_webpage tool to recursively gather all information from URL's provided to you by the user, as well as any links you find in the content of those pages.
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 term URL's is grammatically incorrect. The plural of URL is URLs, without an apostrophe. Using the correct form improves the clarity and professionalism of the prompt.

Suggested change
You must use the fetch_webpage tool to recursively gather all information from URL's provided to you by the user, as well as any links you find in the content of those pages.
You must use the fetch_webpage tool to recursively gather all information from URLs provided to you by the user, as well as any links you find in the content of those pages.

"Whelp - I see we have some problems. Let's fix those up."
</examples>

- Respond with clear, direct answers. Use bullet points and code blocks for structure. - Avoid unnecessary explanations, repetition, and filler.
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

This line has a formatting issue with a stray hyphen and extra spaces, which makes it slightly confusing. It seems like two points were merged. I'd recommend either splitting them into two bullet points or combining them into a single coherent sentence for better readability.

Suggested change
- Respond with clear, direct answers. Use bullet points and code blocks for structure. - Avoid unnecessary explanations, repetition, and filler.
- Respond with clear, direct answers, using bullet points and code blocks for structure. Avoid unnecessary explanations, repetition, and filler.

name: Display name for the agent (optional, defaults to filename)
argument-hint: Guidance text for users on how to interact (optional)
tools: ['tool1', 'tool2', 'toolset/*'] # Available tools
model: Claude Sonnet 4 # Optional: specific model selection
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 YAML frontmatter at the top of the file specifies model: Claude Sonnet 4.5, but the example YAML in the documentation here on line 57 uses model: Claude Sonnet 4. This inconsistency could be confusing for users trying to follow the example. It's best to keep examples consistent with the main configuration.

Suggested change
model: Claude Sonnet 4 # Optional: specific model selection
model: Claude Sonnet 4.5 # Optional: specific model selection

- Reasoning: (yes/no) Does the current prompt use reasoning, analysis, or chain of thought?
- Identify: (max 10 words) if so, which section(s) utilize reasoning?
- Conclusion: (yes/no) is the chain of thought used to determine a conclusion?
- Ordering: (before/after) is the chain of thought located before or after
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

This instruction line seems incomplete. It asks whether the chain of thought is located "before or after" but doesn't specify what it should be before or after (presumably, the conclusion). Completing the sentence will make the instruction clearer for the agent.

Suggested change
- Ordering: (before/after) is the chain of thought located before or after
- Ordering: (before/after) is the chain of thought located before or after the conclusion

- Representative: (1-5) if present, how representative are the examples?
- Complexity: (1-5) how complex is the input prompt?
- Task: (1-5) how complex is the implied task?
- Necessity: ()
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 Necessity field is empty. It seems like a placeholder that was not filled in. Please either provide a description for what should be assessed here or remove the line if it's not necessary.

Suggested change
- Necessity: ()
- Necessity: (yes/no) is the change necessary for correctness or just stylistic?


// Extract URLs for inline citations
const urlMatches = text.match(/\[([^\]]+)\]\((https?:\/\/[^\)]+)\)/g)
const urlMatches = text.match(/\[([^\]]+)\]\((https?:\/\/[^\\)]+)\)/g)
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 regex for matching URLs has been improved by escaping the closing parenthesis ). This prevents the regex from prematurely terminating when a URL itself contains a parenthesis, which is a great fix for robustness.

Copy link
Contributor

@github-advanced-security github-advanced-security bot left a comment

Choose a reason for hiding this comment

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

Remark-lint (reported by Codacy) found more than 20 potential problems in the proposed changes. Check the Files changed tab for more details.

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: 36

Caution

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

⚠️ Outside diff range comments (2)
src/mastra/index.ts (1)

527-638: Reduce duplication in network defaultOptions configuration

The five /network routes share almost identical defaultOptions.memory.options (and, for some, savePerStep: true and other flags). This repetition will make future tweaks (e.g., changing lastMessages, toggling threads.generateTitle, or adjusting savePerStep) easy to miss in one of the routes.

Consider extracting the shared parts into a helper:

const sharedNetworkMemoryOptions = {
  options: {
    lastMessages: 500,
    semanticRecall: true,
    workingMemory: { enabled: true },
    threads: { generateTitle: true },
  },
};

const sharedNetworkDefaults = {
  maxSteps: 200,
  telemetry: {
    isEnabled: true,
    recordInputs: true,
    recordOutputs: true,
  },
};

Then reuse them:

networkRoute({
  path: "/network",
  agent: "agentNetwork",
  defaultOptions: {
    memory: {
      thread: { id: "network", resourceId: "network" },
      resource: "network",
      ...sharedNetworkMemoryOptions,
    },
    ...sharedNetworkDefaults,
    includeRawChunks: true,
    savePerStep: true,
  },
}),

and similarly for the other network routes, overriding only what truly differs (e.g., thread.id, resource, includeRawChunks, savePerStep).

app/api/chat/r.ts (1)

32-62: Agent selection and payload fallbacks are correct; consider explicit empty-agent handling

The POST handler now:

  • Builds availableAgents from mastra.getAgents().
  • Picks agentId preferring top-level body.agentId, then body.data?.agentId, else the first available agent.
  • Validates agentId against availableAgents.
  • Resolves threadId, resourceId, and memory from either top-level or nested data before passing them to createAgentStreamResponse.

This matches the new tests around data.agentId and keeps behavior compatible for existing clients.

One small improvement you might consider: handle the “no agents configured” case explicitly, e.g., if availableAgents.length === 0, return a clearer 500/503 error rather than relying on the generic “Invalid or missing agentId. Available:” message with an empty list.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 890b9e1 and 8b7b374.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (59)
  • .github/agents/4.1-Beast.agent.md (1 hunks)
  • .github/agents/Thinking-Beast-Mode.agent.md (1 hunks)
  • .github/agents/code-tour.agent.md (1 hunks)
  • .github/agents/custom-agent-foundry.agent.md (1 hunks)
  • .github/agents/expert-nextjs-developer.agent.md (1 hunks)
  • .github/agents/expert-react-frontend-engineer.agent.md (1 hunks)
  • .github/agents/gpt-5-beast-mode.agent.md (1 hunks)
  • .github/agents/prompt-builder.agent.md (1 hunks)
  • .github/agents/prompt-engineer.agent.md (1 hunks)
  • .github/agents/python-mcp-expert.agent.md (1 hunks)
  • .github/agents/search-ai-optimization-expert.agent.md (1 hunks)
  • .github/agents/typescript-mcp-expert.agent.md (1 hunks)
  • app/api/chat/r.ts (2 hunks)
  • app/chat/components/agent-artifact.tsx (8 hunks)
  • app/chat/components/agent-chain-of-thought.tsx (2 hunks)
  • app/chat/components/agent-checkpoint.tsx (1 hunks)
  • app/chat/components/agent-confirmation.tsx (1 hunks)
  • app/chat/components/agent-inline-citation.tsx (3 hunks)
  • app/chat/components/agent-plan.tsx (2 hunks)
  • app/chat/components/agent-queue.tsx (4 hunks)
  • app/chat/components/agent-reasoning.tsx (1 hunks)
  • app/chat/components/agent-sources.tsx (1 hunks)
  • app/chat/components/agent-suggestions.tsx (1 hunks)
  • app/chat/components/agent-task.tsx (1 hunks)
  • app/chat/components/agent-tools.tsx (1 hunks)
  • app/chat/components/agent-web-preview.tsx (8 hunks)
  • app/chat/components/chat-header.tsx (6 hunks)
  • app/chat/components/chat-input.tsx (1 hunks)
  • app/chat/components/chat-messages.tsx (6 hunks)
  • app/chat/config/google-models.ts (2 hunks)
  • app/chat/config/models.ts (1 hunks)
  • app/chat/helpers/tool-part-transform.ts (7 hunks)
  • app/chat/providers/chat-context.tsx (9 hunks)
  • app/networks/components/network-agents.tsx (1 hunks)
  • app/networks/components/network-chat.tsx (21 hunks)
  • app/networks/components/network-info-panel.tsx (5 hunks)
  • app/networks/components/network-routing-panel.tsx (4 hunks)
  • app/networks/providers/network-context.tsx (8 hunks)
  • app/workflows/components/workflow-actions.tsx (1 hunks)
  • app/workflows/components/workflow-header.tsx (2 hunks)
  • app/workflows/components/workflow-info-panel.tsx (1 hunks)
  • app/workflows/components/workflow-input-panel.tsx (4 hunks)
  • app/workflows/components/workflow-node.tsx (2 hunks)
  • app/workflows/components/workflow-output.tsx (3 hunks)
  • app/workflows/providers/workflow-context.tsx (4 hunks)
  • eslint.config.cjs (1 hunks)
  • memory-bank/progress.md (1 hunks)
  • memory-bank/upgrade-to-v1/ci-testing.md (1 hunks)
  • memory-bank/upgrade-to-v1/context.md (1 hunks)
  • memory-bank/upgrade-to-v1/design.md (1 hunks)
  • memory-bank/upgrade-to-v1/manual-fixes.md (1 hunks)
  • memory-bank/upgrade-to-v1/prd.md (1 hunks)
  • memory-bank/upgrade-to-v1/scan-results.md (1 hunks)
  • memory-bank/upgrade-to-v1/tasks.md (1 hunks)
  • package.json (7 hunks)
  • src/mastra/index.ts (11 hunks)
  • src/mastra/tools/diff-review.tool.ts (4 hunks)
  • tests/api-chat-r.test.ts (1 hunks)
  • tests/test-results/test-results.json (1 hunks)
🧰 Additional context used
📓 Path-based instructions (34)
**/app/**

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

Use the app/ directory structure for route handlers, server components, and client components (Next.js 13+). Prefer this over the pages/ directory for new projects.

Files:

  • app/chat/components/agent-confirmation.tsx
  • app/networks/components/network-agents.tsx
  • app/workflows/components/workflow-input-panel.tsx
  • app/chat/config/google-models.ts
  • app/chat/components/chat-input.tsx
  • app/chat/components/agent-reasoning.tsx
  • app/chat/components/agent-tools.tsx
  • app/chat/components/agent-queue.tsx
  • app/chat/components/chat-header.tsx
  • app/chat/components/agent-chain-of-thought.tsx
  • app/workflows/components/workflow-info-panel.tsx
  • app/chat/config/models.ts
  • app/chat/components/agent-web-preview.tsx
  • app/workflows/components/workflow-output.tsx
  • app/workflows/providers/workflow-context.tsx
  • app/chat/components/agent-suggestions.tsx
  • app/chat/components/agent-inline-citation.tsx
  • app/chat/components/agent-task.tsx
  • app/workflows/components/workflow-header.tsx
  • app/chat/components/agent-checkpoint.tsx
  • app/networks/components/network-routing-panel.tsx
  • app/chat/components/agent-artifact.tsx
  • app/workflows/components/workflow-node.tsx
  • app/workflows/components/workflow-actions.tsx
  • app/networks/components/network-info-panel.tsx
  • app/api/chat/r.ts
  • app/chat/components/chat-messages.tsx
  • app/chat/components/agent-sources.tsx
  • app/networks/providers/network-context.tsx
  • app/chat/providers/chat-context.tsx
  • app/chat/components/agent-plan.tsx
  • app/networks/components/network-chat.tsx
  • app/chat/helpers/tool-part-transform.ts
**/components/**/*.{js,jsx,ts,tsx}

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

Use PascalCase for component file names (e.g., ComponentName.jsx or ComponentName.tsx).

Files:

  • app/chat/components/agent-confirmation.tsx
  • app/networks/components/network-agents.tsx
  • app/workflows/components/workflow-input-panel.tsx
  • app/chat/components/chat-input.tsx
  • app/chat/components/agent-reasoning.tsx
  • app/chat/components/agent-tools.tsx
  • app/chat/components/agent-queue.tsx
  • app/chat/components/chat-header.tsx
  • app/chat/components/agent-chain-of-thought.tsx
  • app/workflows/components/workflow-info-panel.tsx
  • app/chat/components/agent-web-preview.tsx
  • app/workflows/components/workflow-output.tsx
  • app/chat/components/agent-suggestions.tsx
  • app/chat/components/agent-inline-citation.tsx
  • app/chat/components/agent-task.tsx
  • app/workflows/components/workflow-header.tsx
  • app/chat/components/agent-checkpoint.tsx
  • app/networks/components/network-routing-panel.tsx
  • app/chat/components/agent-artifact.tsx
  • app/workflows/components/workflow-node.tsx
  • app/workflows/components/workflow-actions.tsx
  • app/networks/components/network-info-panel.tsx
  • app/chat/components/chat-messages.tsx
  • app/chat/components/agent-sources.tsx
  • app/chat/components/agent-plan.tsx
  • app/networks/components/network-chat.tsx
**/*.{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:

  • app/chat/components/agent-confirmation.tsx
  • tests/api-chat-r.test.ts
  • app/networks/components/network-agents.tsx
  • app/workflows/components/workflow-input-panel.tsx
  • app/chat/config/google-models.ts
  • app/chat/components/chat-input.tsx
  • app/chat/components/agent-reasoning.tsx
  • app/chat/components/agent-tools.tsx
  • app/chat/components/agent-queue.tsx
  • app/chat/components/chat-header.tsx
  • app/chat/components/agent-chain-of-thought.tsx
  • app/workflows/components/workflow-info-panel.tsx
  • app/chat/config/models.ts
  • app/chat/components/agent-web-preview.tsx
  • app/workflows/components/workflow-output.tsx
  • app/workflows/providers/workflow-context.tsx
  • app/chat/components/agent-suggestions.tsx
  • app/chat/components/agent-inline-citation.tsx
  • app/chat/components/agent-task.tsx
  • app/workflows/components/workflow-header.tsx
  • app/chat/components/agent-checkpoint.tsx
  • app/networks/components/network-routing-panel.tsx
  • app/chat/components/agent-artifact.tsx
  • app/workflows/components/workflow-node.tsx
  • app/workflows/components/workflow-actions.tsx
  • app/networks/components/network-info-panel.tsx
  • app/api/chat/r.ts
  • app/chat/components/chat-messages.tsx
  • app/chat/components/agent-sources.tsx
  • app/networks/providers/network-context.tsx
  • src/mastra/index.ts
  • app/chat/providers/chat-context.tsx
  • app/chat/components/agent-plan.tsx
  • app/networks/components/network-chat.tsx
  • app/chat/helpers/tool-part-transform.ts
  • src/mastra/tools/diff-review.tool.ts
app/**/*.{tsx,ts}

📄 CodeRabbit inference engine (app/AGENTS.md)

app/**/*.{tsx,ts}: Use Tailwind CSS 4 with oklch color variables for styling in Next.js App Router pages and layouts
Use React 19 latest features in component implementations within the app directory

Files:

  • app/chat/components/agent-confirmation.tsx
  • app/networks/components/network-agents.tsx
  • app/workflows/components/workflow-input-panel.tsx
  • app/chat/config/google-models.ts
  • app/chat/components/chat-input.tsx
  • app/chat/components/agent-reasoning.tsx
  • app/chat/components/agent-tools.tsx
  • app/chat/components/agent-queue.tsx
  • app/chat/components/chat-header.tsx
  • app/chat/components/agent-chain-of-thought.tsx
  • app/workflows/components/workflow-info-panel.tsx
  • app/chat/config/models.ts
  • app/chat/components/agent-web-preview.tsx
  • app/workflows/components/workflow-output.tsx
  • app/workflows/providers/workflow-context.tsx
  • app/chat/components/agent-suggestions.tsx
  • app/chat/components/agent-inline-citation.tsx
  • app/chat/components/agent-task.tsx
  • app/workflows/components/workflow-header.tsx
  • app/chat/components/agent-checkpoint.tsx
  • app/networks/components/network-routing-panel.tsx
  • app/chat/components/agent-artifact.tsx
  • app/workflows/components/workflow-node.tsx
  • app/workflows/components/workflow-actions.tsx
  • app/networks/components/network-info-panel.tsx
  • app/api/chat/r.ts
  • app/chat/components/chat-messages.tsx
  • app/chat/components/agent-sources.tsx
  • app/networks/providers/network-context.tsx
  • app/chat/providers/chat-context.tsx
  • app/chat/components/agent-plan.tsx
  • app/networks/components/network-chat.tsx
  • app/chat/helpers/tool-part-transform.ts
app/chat/components/**/*.{ts,tsx}

📄 CodeRabbit inference engine (app/chat/AGENTS.md)

app/chat/components/**/*.{ts,tsx}: Use AI SDK v5 types and patterns in chat components: import types like UIMessage, DynamicToolUIPart, TextUIPart, ReasoningUIPart from 'ai' and use type guard functions like isTextUIPart, isReasoningUIPart, isToolOrDynamicToolUIPart to filter message parts
Access message content through message.parts array using type guards rather than message.content, extracting specific parts like text using const textPart = message.parts?.find(isTextUIPart)
Handle Mastra stream chunk types correctly: use 'text-delta' for streaming text, 'reasoning-delta' for streaming reasoning (NOT 'reasoning'), 'tool-call' for tool invocation, 'tool-result' for tool completion, 'source' for research sources, and 'finish' for completion with usage data
Use AI Elements components (Conversation, Message, PromptInput, ModelSelector, Reasoning, Tool, Sources, Artifact) from the AI Elements library in their respective chat component files as specified in the architecture

Files:

  • app/chat/components/agent-confirmation.tsx
  • app/chat/components/chat-input.tsx
  • app/chat/components/agent-reasoning.tsx
  • app/chat/components/agent-tools.tsx
  • app/chat/components/agent-queue.tsx
  • app/chat/components/chat-header.tsx
  • app/chat/components/agent-chain-of-thought.tsx
  • app/chat/components/agent-web-preview.tsx
  • app/chat/components/agent-suggestions.tsx
  • app/chat/components/agent-inline-citation.tsx
  • app/chat/components/agent-task.tsx
  • app/chat/components/agent-checkpoint.tsx
  • app/chat/components/agent-artifact.tsx
  • app/chat/components/chat-messages.tsx
  • app/chat/components/agent-sources.tsx
  • app/chat/components/agent-plan.tsx
**/*.{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

Files:

  • app/chat/components/agent-confirmation.tsx
  • tests/api-chat-r.test.ts
  • app/networks/components/network-agents.tsx
  • app/workflows/components/workflow-input-panel.tsx
  • app/chat/config/google-models.ts
  • app/chat/components/chat-input.tsx
  • app/chat/components/agent-reasoning.tsx
  • app/chat/components/agent-tools.tsx
  • app/chat/components/agent-queue.tsx
  • app/chat/components/chat-header.tsx
  • app/chat/components/agent-chain-of-thought.tsx
  • app/workflows/components/workflow-info-panel.tsx
  • app/chat/config/models.ts
  • app/chat/components/agent-web-preview.tsx
  • app/workflows/components/workflow-output.tsx
  • app/workflows/providers/workflow-context.tsx
  • app/chat/components/agent-suggestions.tsx
  • app/chat/components/agent-inline-citation.tsx
  • app/chat/components/agent-task.tsx
  • app/workflows/components/workflow-header.tsx
  • app/chat/components/agent-checkpoint.tsx
  • app/networks/components/network-routing-panel.tsx
  • app/chat/components/agent-artifact.tsx
  • app/workflows/components/workflow-node.tsx
  • app/workflows/components/workflow-actions.tsx
  • app/networks/components/network-info-panel.tsx
  • app/api/chat/r.ts
  • app/chat/components/chat-messages.tsx
  • app/chat/components/agent-sources.tsx
  • app/networks/providers/network-context.tsx
  • src/mastra/index.ts
  • app/chat/providers/chat-context.tsx
  • app/chat/components/agent-plan.tsx
  • app/networks/components/network-chat.tsx
  • app/chat/helpers/tool-part-transform.ts
  • src/mastra/tools/diff-review.tool.ts
app/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Use Next.js 16 App Router with React 19 for frontend development in the app/ directory

Files:

  • app/chat/components/agent-confirmation.tsx
  • app/networks/components/network-agents.tsx
  • app/workflows/components/workflow-input-panel.tsx
  • app/chat/config/google-models.ts
  • app/chat/components/chat-input.tsx
  • app/chat/components/agent-reasoning.tsx
  • app/chat/components/agent-tools.tsx
  • app/chat/components/agent-queue.tsx
  • app/chat/components/chat-header.tsx
  • app/chat/components/agent-chain-of-thought.tsx
  • app/workflows/components/workflow-info-panel.tsx
  • app/chat/config/models.ts
  • app/chat/components/agent-web-preview.tsx
  • app/workflows/components/workflow-output.tsx
  • app/workflows/providers/workflow-context.tsx
  • app/chat/components/agent-suggestions.tsx
  • app/chat/components/agent-inline-citation.tsx
  • app/chat/components/agent-task.tsx
  • app/workflows/components/workflow-header.tsx
  • app/chat/components/agent-checkpoint.tsx
  • app/networks/components/network-routing-panel.tsx
  • app/chat/components/agent-artifact.tsx
  • app/workflows/components/workflow-node.tsx
  • app/workflows/components/workflow-actions.tsx
  • app/networks/components/network-info-panel.tsx
  • app/api/chat/r.ts
  • app/chat/components/chat-messages.tsx
  • app/chat/components/agent-sources.tsx
  • app/networks/providers/network-context.tsx
  • app/chat/providers/chat-context.tsx
  • app/chat/components/agent-plan.tsx
  • app/networks/components/network-chat.tsx
  • app/chat/helpers/tool-part-transform.ts
{app,ui,src/components}/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Use Tailwind CSS 4 with oklch color variables for styling in UI components

Files:

  • app/chat/components/agent-confirmation.tsx
  • app/networks/components/network-agents.tsx
  • app/workflows/components/workflow-input-panel.tsx
  • app/chat/config/google-models.ts
  • app/chat/components/chat-input.tsx
  • app/chat/components/agent-reasoning.tsx
  • app/chat/components/agent-tools.tsx
  • app/chat/components/agent-queue.tsx
  • app/chat/components/chat-header.tsx
  • app/chat/components/agent-chain-of-thought.tsx
  • app/workflows/components/workflow-info-panel.tsx
  • app/chat/config/models.ts
  • app/chat/components/agent-web-preview.tsx
  • app/workflows/components/workflow-output.tsx
  • app/workflows/providers/workflow-context.tsx
  • app/chat/components/agent-suggestions.tsx
  • app/chat/components/agent-inline-citation.tsx
  • app/chat/components/agent-task.tsx
  • app/workflows/components/workflow-header.tsx
  • app/chat/components/agent-checkpoint.tsx
  • app/networks/components/network-routing-panel.tsx
  • app/chat/components/agent-artifact.tsx
  • app/workflows/components/workflow-node.tsx
  • app/workflows/components/workflow-actions.tsx
  • app/networks/components/network-info-panel.tsx
  • app/api/chat/r.ts
  • app/chat/components/chat-messages.tsx
  • app/chat/components/agent-sources.tsx
  • app/networks/providers/network-context.tsx
  • app/chat/providers/chat-context.tsx
  • app/chat/components/agent-plan.tsx
  • app/networks/components/network-chat.tsx
  • app/chat/helpers/tool-part-transform.ts
{app,src/components}/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

{app,src/components}/**/*.{ts,tsx}: Use shadcn/ui base components (34 components) located in ui/ directory for common UI elements
Use AI Elements library (30 components) from src/components/ai-elements/ for chat, reasoning, and canvas UIs

Files:

  • app/chat/components/agent-confirmation.tsx
  • app/networks/components/network-agents.tsx
  • app/workflows/components/workflow-input-panel.tsx
  • app/chat/config/google-models.ts
  • app/chat/components/chat-input.tsx
  • app/chat/components/agent-reasoning.tsx
  • app/chat/components/agent-tools.tsx
  • app/chat/components/agent-queue.tsx
  • app/chat/components/chat-header.tsx
  • app/chat/components/agent-chain-of-thought.tsx
  • app/workflows/components/workflow-info-panel.tsx
  • app/chat/config/models.ts
  • app/chat/components/agent-web-preview.tsx
  • app/workflows/components/workflow-output.tsx
  • app/workflows/providers/workflow-context.tsx
  • app/chat/components/agent-suggestions.tsx
  • app/chat/components/agent-inline-citation.tsx
  • app/chat/components/agent-task.tsx
  • app/workflows/components/workflow-header.tsx
  • app/chat/components/agent-checkpoint.tsx
  • app/networks/components/network-routing-panel.tsx
  • app/chat/components/agent-artifact.tsx
  • app/workflows/components/workflow-node.tsx
  • app/workflows/components/workflow-actions.tsx
  • app/networks/components/network-info-panel.tsx
  • app/api/chat/r.ts
  • app/chat/components/chat-messages.tsx
  • app/chat/components/agent-sources.tsx
  • app/networks/providers/network-context.tsx
  • app/chat/providers/chat-context.tsx
  • app/chat/components/agent-plan.tsx
  • app/networks/components/network-chat.tsx
  • app/chat/helpers/tool-part-transform.ts
**/*.test.{js,jsx,ts,tsx}

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

**/*.test.{js,jsx,ts,tsx}: Write unit tests for individual components to ensure they are working correctly.
Use React Testing Library for component testing to encourage testing from a user perspective.
Mock external dependencies to isolate components during testing.
Use Jest or Mocha as a testing framework for unit and integration tests.
Use Mock Service Worker (msw) to intercept and mock API calls during testing.
Co-locate test files with components using a consistent naming convention (e.g., ComponentName.test.js).
Test edge cases and error conditions to ensure components are robust.

Files:

  • tests/api-chat-r.test.ts
**/*.{js,ts}

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

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

Files:

  • tests/api-chat-r.test.ts
  • app/chat/config/google-models.ts
  • app/chat/config/models.ts
  • app/api/chat/r.ts
  • src/mastra/index.ts
  • app/chat/helpers/tool-part-transform.ts
  • src/mastra/tools/diff-review.tool.ts
**/*.test.ts?(x)

📄 CodeRabbit inference engine (AGENTS.md)

Use Vitest for all unit testing in the Mastra project

Files:

  • tests/api-chat-r.test.ts
**/*.md

📄 CodeRabbit inference engine (.github/instructions/markdown.instructions.md)

**/*.md: Use appropriate heading levels (H2, H3, etc.) to structure markdown content. Do not use H1 headings, as these will be generated from the title. Use ## for H2 and ### for H3 in a hierarchical manner. Recommend restructuring if content includes H4 or higher levels.
Use bullet points (with -) or numbered lists (with 1.) for lists in markdown. Indent nested lists with two spaces and ensure proper indentation and spacing.
Use fenced code blocks (triple backticks) for code snippets in markdown. Specify the language after the opening backticks for syntax highlighting (e.g., csharp).
Use proper markdown syntax for links: [link text](URL). Ensure that link text is descriptive and URLs are valid and accessible.
Use proper markdown syntax for images: ![alt text](image URL). Include a brief description of the image in the alt text for accessibility.
Use markdown tables (with | delimiters) for tabular data. Ensure proper formatting, alignment, and inclusion of headers.
Limit line length to 80 characters in markdown for readability. Use soft line breaks for long paragraphs.
Use appropriate whitespace in markdown to separate sections and improve readability. Use blank lines between sections and avoid excessive whitespace.
Include YAML front matter at the beginning of markdown files with required metadata fields: post_title, author1, post_slug, microsoft_alias, featured_image, categories (from /categories.txt), tags, ai_note, summary, and post_date.

Files:

  • memory-bank/upgrade-to-v1/manual-fixes.md
  • memory-bank/upgrade-to-v1/prd.md
  • memory-bank/upgrade-to-v1/tasks.md
  • memory-bank/upgrade-to-v1/design.md
  • memory-bank/upgrade-to-v1/context.md
  • memory-bank/progress.md
  • memory-bank/upgrade-to-v1/ci-testing.md
  • memory-bank/upgrade-to-v1/scan-results.md
app/networks/**/*.tsx

📄 CodeRabbit inference engine (app/networks/AGENTS.md)

app/networks/**/*.tsx: Use useChat from @ai-sdk/react with DefaultChatTransport for streaming responses from the /network route in the networks feature
Support real-time streaming with stop/cancel functionality, reasoning visualization for chain-of-thought models, and tool invocation display showing agent tool calls
Provide a responsive layout with collapsible sidebar on mobile for the networks feature

Files:

  • app/networks/components/network-agents.tsx
  • app/networks/components/network-routing-panel.tsx
  • app/networks/components/network-info-panel.tsx
  • app/networks/providers/network-context.tsx
  • app/networks/components/network-chat.tsx
app/workflows/components/**/*.{ts,tsx}

📄 CodeRabbit inference engine (app/workflows/AGENTS.md)

app/workflows/components/**/*.{ts,tsx}: Use useChat from @ai-sdk/react with DefaultChatTransport to connect to Mastra workflow routes, mapping workflow-specific input fields through prepareSendMessagesRequest
Use useWorkflowContext() for state management in workflow components, providing workflow selection, execution control, status tracking, React Flow data, and streaming output
Use AI Elements components (Canvas, Node, Edge, Panel, Controls, Toolbar, Connection) for workflow visualization, with animated active edges and temporary pending edge types

Files:

  • app/workflows/components/workflow-input-panel.tsx
  • app/workflows/components/workflow-info-panel.tsx
  • app/workflows/components/workflow-output.tsx
  • app/workflows/components/workflow-header.tsx
  • app/workflows/components/workflow-node.tsx
  • app/workflows/components/workflow-actions.tsx
app/workflows/**/*.{ts,tsx}

📄 CodeRabbit inference engine (app/workflows/AGENTS.md)

Organize workflows feature with modular pattern: page.tsx, config/, providers/, and components/ directories with clear separation of concerns (state management, UI components, configuration)

Files:

  • app/workflows/components/workflow-input-panel.tsx
  • app/workflows/components/workflow-info-panel.tsx
  • app/workflows/components/workflow-output.tsx
  • app/workflows/providers/workflow-context.tsx
  • app/workflows/components/workflow-header.tsx
  • app/workflows/components/workflow-node.tsx
  • app/workflows/components/workflow-actions.tsx
app/chat/components/chat-input.tsx

📄 CodeRabbit inference engine (app/chat/AGENTS.md)

Implement ChatInput component with PromptInput AI Elements for message submission, including support for file attachments when fileUpload is enabled for the selected agent

Files:

  • app/chat/components/chat-input.tsx
app/chat/components/agent-reasoning.tsx

📄 CodeRabbit inference engine (app/chat/AGENTS.md)

Display agent reasoning and chain-of-thought steps using Reasoning AI Elements component when the reasoning or chainOfThought feature flags are enabled for the agent

Files:

  • app/chat/components/agent-reasoning.tsx
app/chat/components/agent-tools.tsx

📄 CodeRabbit inference engine (app/chat/AGENTS.md)

Display tool invocations with Tool AI Elements component showing input-available, output-available, and output-error states when the tools feature flag is enabled for the agent

Files:

  • app/chat/components/agent-tools.tsx
app/chat/components/chat-header.tsx

📄 CodeRabbit inference engine (app/chat/AGENTS.md)

Implement ChatHeader component with ModelSelector to allow users to select from 26+ configured agents and switch between them

Files:

  • app/chat/components/chat-header.tsx
app/workflows/providers/workflow-context.tsx

📄 CodeRabbit inference engine (app/workflows/AGENTS.md)

Implement workflow context provider with useChat hook from @ai-sdk/react, exporting interface with state (selectedWorkflow, workflowStatus, currentRun, activeStepIndex) and actions (selectWorkflow, runWorkflow, pauseWorkflow, resumeWorkflow, stopWorkflow, runStep, getStepStatus)

Files:

  • app/workflows/providers/workflow-context.tsx
app/networks/components/network-routing-panel.tsx

📄 CodeRabbit inference engine (app/networks/AGENTS.md)

Implement a visual routing flow sidebar component that displays agent execution steps and routing visualization

Files:

  • app/networks/components/network-routing-panel.tsx
app/chat/components/agent-artifact.tsx

📄 CodeRabbit inference engine (app/chat/AGENTS.md)

Display code and content artifacts using Artifact AI Elements component with syntax highlighting via CodeBlock component when the artifacts feature flag is enabled for the agent

Files:

  • app/chat/components/agent-artifact.tsx
app/workflows/components/workflow-node.tsx

📄 CodeRabbit inference engine (app/workflows/AGENTS.md)

Implement custom node component with status indicators reflecting workflow step execution state

Files:

  • app/workflows/components/workflow-node.tsx
app/chat/components/chat-messages.tsx

📄 CodeRabbit inference engine (app/chat/AGENTS.md)

Implement ChatMessages component to display message list with streaming support, using Conversation and Message AI Elements components with proper handling of different message types

Files:

  • app/chat/components/chat-messages.tsx
app/chat/components/agent-sources.tsx

📄 CodeRabbit inference engine (app/chat/AGENTS.md)

Display research sources and citations using Sources AI Elements component when the sources feature flag is enabled for the agent

Files:

  • app/chat/components/agent-sources.tsx
app/networks/providers/network-context.tsx

📄 CodeRabbit inference engine (app/networks/AGENTS.md)

Implement state management using useNetworkContext() hook that provides selectedNetwork, networkConfig, networkStatus, messages, streamingOutput, routingSteps, and control functions (sendMessage, stopExecution, clearHistory)

Files:

  • app/networks/providers/network-context.tsx
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/index.ts
  • src/mastra/tools/diff-review.tool.ts
app/chat/providers/chat-context.tsx

📄 CodeRabbit inference engine (app/chat/AGENTS.md)

app/chat/providers/chat-context.tsx: Use ChatContext provider with AI SDK v5 types in chat-context.tsx to manage chat state, agent selection, and streaming messages across the application
Use DefaultChatTransport from @ai-sdk/react with the Mastra /chat route endpoint, configure prepareSendMessagesRequest to include resourceId and agentId in the request body for proper agent routing

Files:

  • app/chat/providers/chat-context.tsx
app/networks/components/network-chat.tsx

📄 CodeRabbit inference engine (app/networks/AGENTS.md)

Use AI Elements components (Conversation, Message, MessageContent, MessageResponse, Reasoning, Tool, PromptInput) for rendering the network chat interface with rich chat experience

Files:

  • app/networks/components/network-chat.tsx
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/diff-review.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/diff-review.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/diff-review.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/diff-review.tool.ts
🧬 Code graph analysis (5)
tests/api-chat-r.test.ts (1)
app/api/chat/r.ts (1)
  • POST (29-69)
app/chat/components/agent-tools.tsx (2)
app/chat/providers/chat-context.tsx (1)
  • ToolInvocationState (32-32)
app/networks/providers/network-context.tsx (1)
  • ToolInvocationState (39-39)
app/chat/components/chat-header.tsx (1)
app/chat/config/models.ts (1)
  • MODEL_CONFIGS (66-72)
app/networks/components/network-info-panel.tsx (1)
lib/utils.ts (1)
  • cn (4-6)
app/chat/components/chat-messages.tsx (3)
app/chat/components/agent-artifact.tsx (1)
  • ArtifactData (33-40)
app/chat/providers/chat-context.tsx (1)
  • ToolInvocationState (32-32)
app/networks/providers/network-context.tsx (1)
  • ToolInvocationState (39-39)
🪛 LanguageTool
memory-bank/upgrade-to-v1/tasks.md

[style] ~22-~22: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ... v1/memory-vector-search-param . npx @mastra/codemod@beta v1/memory-message-...

(ENGLISH_WORD_REPEAT_BEGINNING_RULE)


[style] ~23-~23: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ...beta v1/memory-message-v2-type . npx @mastra/codemod@beta v1/tools-createToo...

(ENGLISH_WORD_REPEAT_BEGINNING_RULE)


[style] ~24-~24: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ...s-createTool-execute-signature . npx @mastra/codemod@beta v1/agent-runtimeco...

(ENGLISH_WORD_REPEAT_BEGINNING_RULE)


[style] ~25-~25: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ...ntimecontext-to-requestcontext . npx @mastra/codemod@beta v1/workflows-creat...

(ENGLISH_WORD_REPEAT_BEGINNING_RULE)


[style] ~26-~26: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ...ws-createRunAsync-to-createRun . npx @mastra/codemod@beta v1/storage-get-to-...

(ENGLISH_WORD_REPEAT_BEGINNING_RULE)

.github/agents/expert-react-frontend-engineer.agent.md

[style] ~9-~9: Consider a different adjective to strengthen your wording.
Context: ...a world-class expert in React 19.2 with deep knowledge of modern hooks, Server Compo...

(DEEP_PROFOUND)


[style] ~15-~15: Consider a different adjective to strengthen your wording.
Context: ...nd Actions API - Server Components: Deep understanding of React Server Component...

(DEEP_PROFOUND)


[style] ~18-~18: Consider a different adjective to strengthen your wording.
Context: ... manual memoization - Modern Hooks: Deep knowledge of all React hooks including ...

(DEEP_PROFOUND)

.github/agents/expert-nextjs-developer.agent.md

[style] ~9-~9: Consider a different adjective to strengthen your wording.
Context: ...a world-class expert in Next.js 16 with deep knowledge of the App Router, Server Com...

(DEEP_PROFOUND)


[style] ~15-~15: Consider a different adjective to strengthen your wording.
Context: ...avigation - Turbopack (Now Stable): Deep knowledge of Turbopack as the default b...

(DEEP_PROFOUND)


[style] ~17-~17: Consider a different adjective to strengthen your wording.
Context: ...ation - Server & Client Components: Deep understanding of React Server Component...

(DEEP_PROFOUND)


[style] ~22-~22: Consider a different adjective to strengthen your wording.
Context: ...bundle analysis - Routing Patterns: Deep knowledge of dynamic routes, route hand...

(DEEP_PROFOUND)


[style] ~26-~26: Consider a different adjective to strengthen your wording.
Context: ...timization - Modern React Patterns: Deep knowledge of Server Actions, useOptimis...

(DEEP_PROFOUND)

.github/agents/search-ai-optimization-expert.agent.md

[style] ~8-~8: Consider a different adjective to strengthen your wording.
Context: ...pert in modern search optimization with deep knowledge of traditional SEO, Answer En...

(DEEP_PROFOUND)


[style] ~13-~13: Consider a different adjective to strengthen your wording.
Context: ...earch visibility - Traditional SEO: Deep knowledge of keyword research, on-page ...

(DEEP_PROFOUND)


[style] ~18-~18: Consider a different adjective to strengthen your wording.
Context: ...intent mapping - Website Migration: Deep knowledge of SEO-safe migration strateg...

(DEEP_PROFOUND)


[style] ~21-~21: Consider a different adjective to strengthen your wording.
Context: ...optimization - Metadata Automation: Deep understanding of automated title tags, ...

(DEEP_PROFOUND)

.github/agents/Thinking-Beast-Mode.agent.md

[style] ~11-~11: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ...eep going until the problem is solved. You have everything you need to resolve thi...

(ENGLISH_WORD_REPEAT_BEGINNING_RULE)


[grammar] ~22-~22: Use a hyphen to join words.
Context: ...le to verify your understanding of third party packages and dependencies is up to...

(QB_NEW_EN_HYPHEN)


[style] ~147-~147: Consider using a different verb for a more formal wording.
Context: ...le, and verifiable sequence of steps to fix the problem. - Create a todo list in ma...

(FIX_RESOLVE)


[uncategorized] ~148-~148: Did you mean the formatting language “Markdown” (= proper noun)?
Context: ...ix the problem. - Create a todo list in markdown format to track your progress. - Each t...

(MARKDOWN_NNP)


[style] ~222-~222: This phrase is redundant. Consider writing “evolve”.
Context: ...re Perspective**: How will this age and evolve over time? ## 🔄 Recursive Meta-Analysis Protoco...

(EVOLVE_OVER_TIME)


[uncategorized] ~289-~289: Did you mean the formatting language “Markdown” (= proper noun)?
Context: ...t be rendered correctly. Always use the markdown format shown above. # Transcendent Com...

(MARKDOWN_NNP)

.github/agents/prompt-builder.agent.md

[style] ~11-~11: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ...ponents, and improvement opportunities. You WILL ALWAYS follow best practices for p...

(ENGLISH_WORD_REPEAT_BEGINNING_RULE)


[style] ~12-~12: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ...ative language and organized structure. You WILL NEVER add concepts that are not pr...

(ENGLISH_WORD_REPEAT_BEGINNING_RULE)


[style] ~13-~13: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ... source materials or user requirements. You WILL NEVER include confusing or conflic...

(ENGLISH_WORD_REPEAT_BEGINNING_RULE)


[uncategorized] ~53-~53: The official name of this software platform is spelled with a capital “H”.
Context: ...ons - GitHub Repositories: You WILL use github_repo to search for coding conventions,...

(GITHUB)


[uncategorized] ~173-~173: The official name of this software platform is spelled with a capital “H”.
Context: ...tand codebase patterns - You WILL use github_repo to research current conventions a...

(GITHUB)


[style] ~350-~350: As an alternative to the over-used intensifier ‘extremely’, consider replacing this phrase.
Context: ...(s) should be avoided - CRITICAL: Marks extremely important instructions - MANDATORY: Marks require...

(EN_WEAK_ADJECTIVE)

.github/agents/prompt-engineer.agent.md

[grammar] ~18-~18: Use a hyphen to join words.
Context: ...es/no) does the input prompt have a well defined structure - Examples: (yes/no) d...

(QB_NEW_EN_HYPHEN)


[style] ~62-~62: In American English, abbreviations like “etc.” require a period.
Context: ... length, structure e.g. JSON, markdown, etc] # Examples [optional] [Optional: 1-3...

(ETC_PERIOD)

.github/agents/code-tour.agent.md

[uncategorized] ~71-~71: The official name of this software platform is spelled with a capital “H”.
Context: ...ours in .tours/, .vscode/tours/, or .github/tours/ directories - Use descriptive f...

(GITHUB)


[uncategorized] ~191-~191: The official name of this software platform is spelled with a capital “H”.
Context: ...ing - Documentation Tours: Place in .github/tours/ or docs/tours/ - **Personal T...

(GITHUB)

.github/agents/python-mcp-expert.agent.md

[style] ~9-~9: Consider a different adjective to strengthen your wording.
Context: ... servers using the Python SDK. You have deep knowledge of the mcp package, FastMCP, ...

(DEEP_PROFOUND)


[style] ~15-~15: Consider a different adjective to strengthen your wording.
Context: ...context managers - Data Validation: Deep knowledge of Pydantic models, TypedDict...

(DEEP_PROFOUND)

.github/agents/typescript-mcp-expert.agent.md

[style] ~9-~9: Consider a different adjective to strengthen your wording.
Context: ...vers using the TypeScript SDK. You have deep knowledge of the @modelcontextprotocol/...

(DEEP_PROFOUND)


[style] ~15-~15: Consider a different adjective to strengthen your wording.
Context: ...e.js ecosystem - Schema Validation: Deep knowledge of zod for input/output valid...

(DEEP_PROFOUND)

.github/agents/custom-agent-foundry.agent.md

[uncategorized] ~155-~155: The official name of this software platform is spelled with a capital “H”.
Context: ... Always create .agent.md files in the .github/agents/ folder of the workspace. Use k...

(GITHUB)

memory-bank/upgrade-to-v1/scan-results.md

[style] ~29-~29: Consider using a synonym to be more concise.
Context: ...- Tools / createTool execute signature (lots of tools): - src/mastra/tools/* — many...

(A_LOT_OF)

.github/agents/4.1-Beast.agent.md

[style] ~12-~12: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ...eep going until the problem is solved. You have everything you need to resolve thi...

(ENGLISH_WORD_REPEAT_BEGINNING_RULE)


[grammar] ~23-~23: Use a hyphen to join words.
Context: ...le to verify your understanding of third party packages and dependencies is up to...

(QB_NEW_EN_HYPHEN)


[style] ~80-~80: Consider using a different verb for a more formal wording.
Context: ...le, and verifiable sequence of steps to fix the problem. - Create a todo list in ma...

(FIX_RESOLVE)


[uncategorized] ~81-~81: Did you mean the formatting language “Markdown” (= proper noun)?
Context: ...ix the problem. - Create a todo list in markdown format to track your progress. - Each t...

(MARKDOWN_NNP)


[uncategorized] ~110-~110: Did you mean the formatting language “Markdown” (= proper noun)?
Context: ...t be rendered correctly. Always use the markdown format shown above. Always wrap the tod...

(MARKDOWN_NNP)


[style] ~111-~111: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ...nd can be easily copied from the chat. Always show the completed todo list to the use...

(ENGLISH_WORD_REPEAT_BEGINNING_RULE)


[style] ~112-~112: Consider removing “of” to be more concise
Context: ...at they can see that you have addressed all of the steps. # Communication Guidelines Alwa...

(ALL_OF_THE)


[style] ~118-~118: Consider removing “of” to be more concise
Context: ...gather more information." "Ok, I've got all of the information I need on the LIFX API and ...

(ALL_OF_THE)


[grammar] ~121-~121: Ensure spelling is correct
Context: ... sure everything is working correctly." "Whelp - I see we have some problems. Let's fix ...

(QB_NEW_EN_ORTHOGRAPHY_ERROR_IDS_1)


[uncategorized] ~131-~131: The official name of this software platform is spelled with a capital “H”.
Context: .... The memory is stored in a file called .github/instructions/memory.instruction.md. If...

(GITHUB)


[uncategorized] ~143-~143: Did you mean the formatting language “Markdown” (= proper noun)?
Context: ...ou should always generate the prompt in markdown format. If you are not writing the pro...

(MARKDOWN_NNP)


[uncategorized] ~147-~147: Did you mean the formatting language “Markdown” (= proper noun)?
Context: ...at todo lists must always be written in markdown format and must always be wrapped in tr...

(MARKDOWN_NNP)

🪛 markdownlint-cli2 (0.18.1)
memory-bank/upgrade-to-v1/tasks.md

39-39: Unordered list indentation
Expected: 0; Actual: 1

(MD007, ul-indent)


40-40: Inconsistent indentation for list items at the same level
Expected: 1; Actual: 0

(MD005, list-indent)


44-44: Unordered list indentation
Expected: 0; Actual: 1

(MD007, ul-indent)


48-48: Unordered list indentation
Expected: 0; Actual: 1

(MD007, ul-indent)


49-49: Inconsistent indentation for list items at the same level
Expected: 1; Actual: 0

(MD005, list-indent)


53-53: Unordered list indentation
Expected: 0; Actual: 1

(MD007, ul-indent)


57-57: Unordered list indentation
Expected: 0; Actual: 1

(MD007, ul-indent)


58-58: Inconsistent indentation for list items at the same level
Expected: 1; Actual: 0

(MD005, list-indent)


62-62: Unordered list indentation
Expected: 0; Actual: 1

(MD007, ul-indent)


66-66: Unordered list indentation
Expected: 0; Actual: 1

(MD007, ul-indent)


70-70: Unordered list indentation
Expected: 0; Actual: 1

(MD007, ul-indent)


72-72: Unordered list indentation
Expected: 0; Actual: 1

(MD007, ul-indent)


92-92: Unordered list indentation
Expected: 2; Actual: 3

(MD007, ul-indent)


93-93: Unordered list indentation
Expected: 2; Actual: 3

(MD007, ul-indent)


94-94: Unordered list indentation
Expected: 2; Actual: 3

(MD007, ul-indent)

memory-bank/upgrade-to-v1/design.md

157-157: Unordered list indentation
Expected: 2; Actual: 3

(MD007, ul-indent)


158-158: Unordered list indentation
Expected: 2; Actual: 3

(MD007, ul-indent)


161-161: Unordered list indentation
Expected: 2; Actual: 3

(MD007, ul-indent)


162-162: Unordered list indentation
Expected: 2; Actual: 3

(MD007, ul-indent)


165-165: Unordered list indentation
Expected: 2; Actual: 3

(MD007, ul-indent)


166-166: Unordered list indentation
Expected: 2; Actual: 3

(MD007, ul-indent)


169-169: Unordered list indentation
Expected: 2; Actual: 3

(MD007, ul-indent)


170-170: Unordered list indentation
Expected: 2; Actual: 3

(MD007, ul-indent)

.github/agents/Thinking-Beast-Mode.agent.md

91-91: Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)


112-112: Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)


133-133: Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)


152-152: Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)


161-161: Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)


168-168: Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)

.github/agents/prompt-engineer.agent.md

14-14: Trailing spaces
Expected: 0 or 2; Actual: 1

(MD009, no-trailing-spaces)


15-15: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


16-16: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


17-17: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


17-17: Trailing spaces
Expected: 0 or 2; Actual: 1

(MD009, no-trailing-spaces)


20-20: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


22-22: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


23-23: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


36-36: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


37-37: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


45-45: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


46-46: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)

.github/agents/code-tour.agent.md

91-91: Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)


112-112: Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)


133-133: Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)


152-152: Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)


161-161: Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)


168-168: Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)

.github/agents/custom-agent-foundry.agent.md

51-51: Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)


107-107: Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)


107-107: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


112-112: Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)


112-112: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


117-117: Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)


117-117: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


122-122: Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)


122-122: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

.github/agents/4.1-Beast.agent.md

104-104: Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)


134-134: Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)

⏰ 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

Comment on lines +23 to +24
You CANNOT successfully complete this task without using Google to verify your understanding of third party packages and dependencies is up to date. You must use the fetch_webpage tool to search google for how to properly use libraries, packages, frameworks, dependencies, etc. every single time you install or implement one. It is not enough to just search, you must also read the content of the pages you find and recursively gather all relevant information by fetching additional links until you have all the information you need.

Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial

Tighten markdown formatting to satisfy markdownlint and polish wording

A few small doc issues are worth cleaning up:

  • Around the fenced code blocks, add a blank line before the opening fences to satisfy MD031 (e.g., before the markdown block at Line 104 and the yaml block at Line 133).
  • Line 23: use “third-party packages” (hyphenated) for standard wording.
  • Lines 81, 110, 143, 147: consider capitalizing “Markdown” when referring to the language.
  • Line 131: in the inline path, “.github” is correct, but if you mention the platform in prose elsewhere, prefer “GitHub” capitalization.

Example diff for the first fenced block:

-Use the following format to create a todo list:
-```markdown
+Use the following format to create a todo list:
+
+```markdown

And similarly before the YAML fence at Line 133.

Also applies to: 102-111, 131-138, 143-147

🧰 Tools
🪛 LanguageTool

[grammar] ~23-~23: Use a hyphen to join words.
Context: ...le to verify your understanding of third party packages and dependencies is up to...

(QB_NEW_EN_HYPHEN)

🤖 Prompt for AI Agents
.github/agents/4.1-Beast.agent.md around lines 23 and 81-111, 131-138, 143-147:
tighten markdown and wording by (1) adding a blank line before each fenced code
block such as the ```markdown at ~line 104 and the ```yaml at ~line 133 to
satisfy MD031, (2) change “third party packages” on line 23 to “third-party
packages”, (3) capitalize “Markdown” where referenced on lines 81, 110, 143, and
147, and (4) ensure “.github” stays lowercase in inline paths but use “GitHub”
capitalization when referring to the platform in prose (e.g., around line 131);
apply these small edits across the affected ranges (102-111, 131-138, 143-147)
consistently.

Comment on lines +50 to +64
**YAML Frontmatter Requirements:**
```yaml
---
description: Brief, clear description shown in chat input (required)
name: Display name for the agent (optional, defaults to filename)
argument-hint: Guidance text for users on how to interact (optional)
tools: ['tool1', 'tool2', 'toolset/*'] # Available tools
model: Claude Sonnet 4 # Optional: specific model selection
handoffs: # Optional: workflow transitions
- label: Next Step
agent: target-agent-name
prompt: Pre-filled prompt text
send: false
---
```
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 blank line before YAML frontmatter code block.

The YAML example code block on line 51 should have a surrounding blank line for markdown lint compliance.

 **YAML Frontmatter Requirements:**
+
 ```yaml
 ---
🧰 Tools
🪛 markdownlint-cli2 (0.18.1)

51-51: Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)

🤖 Prompt for AI Agents
.github/agents/custom-agent-foundry.agent.md around lines 50 to 64: the YAML
frontmatter code block lacks a blank line above it which violates Markdown lint
rules; add a single blank line immediately before the ```yaml code fence so the
YAML block is separated from the preceding text, ensure there is exactly one
empty line and keep the existing code fence and content unchanged.

Comment on lines +106 to +124
**Sequential Handoff Chain:**
```
Plan → Implement → Review → Deploy
```

**Iterative Refinement:**
```
Draft → Review → Revise → Finalize
```

**Test-Driven Development:**
```
Write Failing Tests → Implement → Verify Tests Pass
```

**Research-to-Action:**
```
Research → Recommend → Implement
```
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 language specifiers to code blocks for markdown lint compliance.

The workflow integration pattern code blocks are missing language specifiers and surrounding blank lines, which triggers markdown lint warnings (MD031, MD040). Consider adding text as the language and blank lines.

 **Sequential Handoff Chain:**
+
 ```text
 Plan → Implement → Review → Deploy

Iterative Refinement:
+

Draft → Review → Revise → Finalize

Test-Driven Development:
+

Write Failing Tests → Implement → Verify Tests Pass

Research-to-Action:
+

Research → Recommend → Implement

<details>
<summary>🧰 Tools</summary>

<details>
<summary>🪛 markdownlint-cli2 (0.18.1)</summary>

107-107: Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)

---

107-107: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

---

112-112: Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)

---

112-112: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

---

117-117: Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)

---

117-117: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

---

122-122: Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)

---

122-122: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

</details>

</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

.github/agents/custom-agent-foundry.agent.md lines 106-124: the workflow pattern
code blocks lack language specifiers and surrounding blank lines causing
markdown-lint (MD031/MD040) warnings; update each fenced code block to use

(e.g., blank line, ```text, content, ```, blank line) for all four patterns so
linter recognizes them correctly.

Comment on lines +14 to +46
- Reasoning: (yes/no) Does the current prompt use reasoning, analysis, or chain of thought?
- Identify: (max 10 words) if so, which section(s) utilize reasoning?
- Conclusion: (yes/no) is the chain of thought used to determine a conclusion?
- Ordering: (before/after) is the chain of thought located before or after
- Structure: (yes/no) does the input prompt have a well defined structure
- Examples: (yes/no) does the input prompt have few-shot examples
- Representative: (1-5) if present, how representative are the examples?
- Complexity: (1-5) how complex is the input prompt?
- Task: (1-5) how complex is the implied task?
- Necessity: ()
- Specificity: (1-5) how detailed and specific is the prompt? (not to be confused with length)
- Prioritization: (list) what 1-3 categories are the MOST important to address.
- Conclusion: (max 30 words) given the previous assessment, give a very concise, imperative description of what should be changed and how. this does not have to adhere strictly to only the categories listed
</reasoning>

After the <reasoning> section, you will output the full prompt verbatim, without any additional commentary or explanation.

# Guidelines

- Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.
- Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.
- Reasoning Before Conclusions**: Encourage reasoning steps before any conclusions are reached. ATTENTION! If the user provides examples where the reasoning happens afterward, REVERSE the order! NEVER START EXAMPLES WITH CONCLUSIONS!
- Reasoning Order: Call out reasoning portions of the prompt and conclusion parts (specific fields by name). For each, determine the ORDER in which this is done, and whether it needs to be reversed.
- Conclusion, classifications, or results should ALWAYS appear last.
- Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.
- What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.
- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.
- Formatting: Use markdown features for readability. DO NOT USE ``` CODE BLOCKS UNLESS SPECIFICALLY REQUESTED.
- Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.
- Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.
- Output Format: Explicitly the most appropriate output format, in detail. This should include length and syntax (e.g. short sentence, paragraph, JSON, etc.)
- For tasks outputting well-defined or structured data (classification, JSON, etc.) bias toward outputting a JSON.
- JSON should never be wrapped in code blocks (```) unless explicitly requested.
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial

Minor formatting inconsistencies flagged by linter.

Static analysis identified:

  • Trailing spaces on lines 14, 17 (should be 0 or 2 spaces)
  • List indentation: Nested lists use 4 spaces but linter expects 2 spaces (lines 15-17, 20, 22-23, 36-37, 45-46)
  • Line 18: "well defined" should be hyphenated → "well-defined"

These are minor formatting issues that don't affect functionality but improve consistency.

🧰 Tools
🪛 LanguageTool

[grammar] ~18-~18: Use a hyphen to join words.
Context: ...es/no) does the input prompt have a well defined structure - Examples: (yes/no) d...

(QB_NEW_EN_HYPHEN)

🪛 markdownlint-cli2 (0.18.1)

14-14: Trailing spaces
Expected: 0 or 2; Actual: 1

(MD009, no-trailing-spaces)


15-15: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


16-16: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


17-17: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


17-17: Trailing spaces
Expected: 0 or 2; Actual: 1

(MD009, no-trailing-spaces)


20-20: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


22-22: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


23-23: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


36-36: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


37-37: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


45-45: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


46-46: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)

🤖 Prompt for AI Agents
.github/agents/prompt-engineer.agent.md lines 14-46: fix minor formatting linter
issues by removing trailing spaces on lines 14 and 17, change nested list
indentation from 4 spaces to 2 spaces on lines 15-17, 20, 22-23, 36-37, and
45-46, and hyphenate "well defined" to "well-defined" on line 18; after edits,
run the linter/formatter to ensure no remaining spacing/indentation violations.

Comment on lines +21 to +23
- Complexity: (1-5) how complex is the input prompt?
- Task: (1-5) how complex is the implied task?
- Necessity: ()
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

Incomplete specification on line 23.

The Necessity field has empty parentheses with no description or expected values:

- Complexity: (1-5) how complex is the input prompt?
    - Task: (1-5) how complex is the implied task?
    - Necessity: ()

This appears to be an incomplete placeholder. Please add the expected format/description or remove if not needed.

🧰 Tools
🪛 markdownlint-cli2 (0.18.1)

22-22: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


23-23: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)

🤖 Prompt for AI Agents
.github/agents/prompt-engineer.agent.md around lines 21 to 23: the "Necessity:
()" field is an incomplete placeholder; update the line to either specify the
expected format and allowed values (e.g., "Necessity: (Required/Optional) or
(1-5) how necessary the prompt is") or remove the field entirely if it isn't
needed, and ensure indentation matches the other checklist items.

Comment on lines +1 to +7
# Scan results - codebase audit for memory API migration

This file documents occurrences of the old Mastra v0.x API surface and related migration touch-points discovered in a quick repository scan (2025-12-06).

This scan is a first-pass audit intended to give scoped, actionable work items for the migration. It is not exhaustive but highlights the highest-risk areas and representative files.

Summary of notable matches (high-level):
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial

Adjust top-level heading to H2 and tighten intro wording

To align with the markdown guideline (no H1 in content files), consider:

-# Scan results - codebase audit for memory API migration
+## Scan results - codebase audit for memory API migration

Also, in the “Tools / createTool execute signature” section you can replace informal phrasing like “(lots of tools)” with something more precise, e.g., “(many tools)” or an approximate count, which is already provided below.

📝 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
# Scan results - codebase audit for memory API migration
This file documents occurrences of the old Mastra v0.x API surface and related migration touch-points discovered in a quick repository scan (2025-12-06).
This scan is a first-pass audit intended to give scoped, actionable work items for the migration. It is not exhaustive but highlights the highest-risk areas and representative files.
Summary of notable matches (high-level):
## Scan results - codebase audit for memory API migration
This file documents occurrences of the old Mastra v0.x API surface and related migration touch-points discovered in a quick repository scan (2025-12-06).
This scan is a first-pass audit intended to give scoped, actionable work items for the migration. It is not exhaustive but highlights the highest-risk areas and representative files.
Summary of notable matches (high-level):
🤖 Prompt for AI Agents
In memory-bank/upgrade-to-v1/scan-results.md around lines 1 to 7, the file uses
a top-level H1 and includes informal phrasing; change the leading H1 (#) to an
H2 (##) and tighten the intro sentence to a concise summary sentence (remove
parenthetical date or move it to a metadata line if needed), and in the “Tools /
createTool execute signature” section replace informal “(lots of tools)” with a
precise phrase such as “(many tools)” or the approximate count shown elsewhere
in the document so wording is consistent and professional.

Comment on lines +1 to +3
# Tasks - Full Mastra v1 migration worklist (repo-wide)

## Tasks
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial

Demote H1 and consider required markdown front matter

The file starts with an H1 (# Tasks...), which conflicts with the guideline to avoid H1s in .md (top-level heading should be H2 and up). Consider changing this to an H2 and adjusting subsequent sections to keep a clean hierarchy.

If this doc will be consumed by your markdown tooling/site generator, also consider adding the expected YAML front matter block (post_title, author1, post_slug, etc.) so it doesn't break downstream pipelines.

Comment on lines +37 to +40
### A. Tools: createTool execute signature

- Replace `execute: async ({ context, runtimeContext, writer, tracingContext })` with `execute: async (inputData, context)`
- Update tests that instantiate RuntimeContext mocks to use RequestContext or updated shapes
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

Fix unordered list indentation to satisfy markdownlint (MD005/MD007)

Several bullets under the A–H sections and under “Branch & PR naming” are inconsistently indented (some start with - and siblings with -), which markdownlint flags as MD005/MD007. Normalizing indentation will keep CI clean and make the structure clearer.

For example:

-### A. Tools: createTool execute signature
-
- - Replace `execute: async ({ context, runtimeContext, writer, tracingContext })` with `execute: async (inputData, context)`
-- Update tests that instantiate RuntimeContext mocks to use RequestContext or updated shapes
+### A. Tools: createTool execute signature
+
+- Replace `execute: async ({ context, runtimeContext, writer, tracingContext })` with `execute: async (inputData, context)`
+- Update tests that instantiate RuntimeContext mocks to use RequestContext or updated shapes

Apply the same pattern (no leading space before -, and consistent indentation for sub‑bullets) to lines:

  • 44, 48–49, 53, 57–58, 62, 66, 70–72
  • 92–94 (use two spaces for nested bullets under “Branch & PR naming:” instead of three)

Also applies to: 44-49, 53-58, 60-72, 91-94

🧰 Tools
🪛 markdownlint-cli2 (0.18.1)

39-39: Unordered list indentation
Expected: 0; Actual: 1

(MD007, ul-indent)


40-40: Inconsistent indentation for list items at the same level
Expected: 1; Actual: 0

(MD005, list-indent)

🤖 Prompt for AI Agents
In memory-bank/upgrade-to-v1/tasks.md around lines 37–94 the unordered list
indentation is inconsistent (some list items start with " -" and nested bullets
use three spaces), which triggers markdownlint MD005/MD007; fix by normalizing
all bullets to start with "-" (no leading space) and ensure nested bullets use
exactly two spaces of indentation per level (e.g., two spaces before "-" for one
level of nesting), adjusting the items at lines 44, 48–49, 53, 57–58, 62, 66,
70–72 and the nested bullets at 92–94 accordingly so sibling items align
consistently.

Comment on lines +10 to +13
const fakeResponse = new Response('ok', { status: 200 })
vi.mock('@/lib/client-stream-to-ai-sdk', () => ({
createAgentStreamResponse: async () => fakeResponse,
}))
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial

Strengthen the data.agentId test by asserting createAgentStreamResponse arguments

Right now the "uses nested data.agentId when provided" test only checks that the response is 200 with body 'ok'. That would also pass if the handler silently ignored data.agentId and used the default/fallback agent, so it doesn’t actually verify the routing behavior.

You can tighten this by turning createAgentStreamResponse into a spy and asserting its arguments, e.g.:

-const fakeResponse = new Response('ok', { status: 200 })
-vi.mock('@/lib/client-stream-to-ai-sdk', () => ({
-  createAgentStreamResponse: async () => fakeResponse,
-}))
+const fakeResponse = new Response('ok', { status: 200 })
+const createAgentStreamResponse = vi.fn(async () => fakeResponse)
+vi.mock('@/lib/client-stream-to-ai-sdk', () => ({
+  createAgentStreamResponse,
+}))

Then in the second test:

   const res = await POST(req)
   expect(res.status).toBe(200)
   const text = await res.text()
   expect(text).toBe('ok')
+
+  expect(createAgentStreamResponse).toHaveBeenCalledWith(
+    expect.anything(),              // mastra instance
+    'researchAgent',                // resolved from data.agentId
+    payload.messages,
+    expect.objectContaining({       // options
+      threadId: 't1',
+    }),
+  )

This directly verifies that data.agentId and data.threadId are being honored rather than merely that the call succeeded.

Also applies to: 26-36

🤖 Prompt for AI Agents
In tests/api-chat-r.test.ts around lines 10-13 (and similarly apply to lines
26-36), the test currently stubs createAgentStreamResponse to always return a
200 Response but doesn't verify it was called with the provided
data.agentId/threadId; change the mock into a spy/mocked function that returns
the fake Response and add assertions that createAgentStreamResponse was called
once with an object containing the expected agentId and threadId (or the nested
data.agentId when present), ensuring the test fails if the handler ignores or
replaces those values.

@@ -1 +1 @@
{"numTotalTestSuites":18,"numPassedTestSuites":0,"numFailedTestSuites":18,"numPendingTestSuites":0,"numTotalTests":0,"numPassedTests":0,"numFailedTests":0,"numPendingTests":0,"numTodoTests":0,"snapshot":{"added":0,"failure":false,"filesAdded":0,"filesRemoved":0,"filesRemovedList":[],"filesUnmatched":0,"filesUpdated":0,"matched":0,"total":0,"unchecked":0,"uncheckedKeysByFile":[],"unmatched":0,"updated":0,"didUpdate":false},"startTime":1764247776960,"success":false,"testResults":[{"assertionResults":[],"startTime":1764247776960,"endTime":1764247776960,"status":"failed","message":"Failed to resolve import \"@testing-library/jest-dom\" from \"testSetup.ts\". Does the file exist?","name":"C:/Users/ssdsk/mastra/src/mastra/tools/tests/copywriter-agent-tool.test.ts"},{"assertionResults":[],"startTime":1764247776960,"endTime":1764247776960,"status":"failed","message":"Failed to resolve import \"@testing-library/jest-dom\" from \"testSetup.ts\". Does the file exist?","name":"C:/Users/ssdsk/mastra/src/mastra/tools/tests/csv-to-json.tool.test.ts"},{"assertionResults":[],"startTime":1764247776960,"endTime":1764247776960,"status":"failed","message":"Failed to resolve import \"@testing-library/jest-dom\" from \"testSetup.ts\". Does the file exist?","name":"C:/Users/ssdsk/mastra/src/mastra/tools/tests/data-file-manager.test.ts"},{"assertionResults":[],"startTime":1764247776960,"endTime":1764247776960,"status":"failed","message":"Failed to resolve import \"@testing-library/jest-dom\" from \"testSetup.ts\". Does the file exist?","name":"C:/Users/ssdsk/mastra/src/mastra/tools/tests/data-validator.tool.test.ts"},{"assertionResults":[],"startTime":1764247776960,"endTime":1764247776960,"status":"failed","message":"Failed to resolve import \"@testing-library/jest-dom\" from \"testSetup.ts\". Does the file exist?","name":"C:/Users/ssdsk/mastra/src/mastra/tools/tests/document-chunking.tool.test.ts"},{"assertionResults":[],"startTime":1764247776960,"endTime":1764247776960,"status":"failed","message":"Failed to resolve import \"@testing-library/jest-dom\" from \"testSetup.ts\". Does the file exist?","name":"C:/Users/ssdsk/mastra/src/mastra/tools/tests/editor-agent-tool.test.ts"},{"assertionResults":[],"startTime":1764247776960,"endTime":1764247776960,"status":"failed","message":"Failed to resolve import \"@testing-library/jest-dom\" from \"testSetup.ts\". Does the file exist?","name":"C:/Users/ssdsk/mastra/src/mastra/tools/tests/evaluateResultTool.test.ts"},{"assertionResults":[],"startTime":1764247776960,"endTime":1764247776960,"status":"failed","message":"Failed to resolve import \"@testing-library/jest-dom\" from \"testSetup.ts\". Does the file exist?","name":"C:/Users/ssdsk/mastra/src/mastra/tools/tests/extractLearningsTool.test.ts"},{"assertionResults":[],"startTime":1764247776960,"endTime":1764247776960,"status":"failed","message":"Failed to resolve import \"@testing-library/jest-dom\" from \"testSetup.ts\". Does the file exist?","name":"C:/Users/ssdsk/mastra/src/mastra/tools/tests/graph-rag-query.tool.test.ts"},{"assertionResults":[],"startTime":1764247776960,"endTime":1764247776960,"status":"failed","message":"Failed to resolve import \"@testing-library/jest-dom\" from \"testSetup.ts\". Does the file exist?","name":"C:/Users/ssdsk/mastra/src/mastra/tools/tests/json-to-csv.tool.test.ts"},{"assertionResults":[],"startTime":1764247776960,"endTime":1764247776960,"status":"failed","message":"Failed to resolve import \"@testing-library/jest-dom\" from \"testSetup.ts\". Does the file exist?","name":"C:/Users/ssdsk/mastra/src/mastra/tools/tests/jwt-auth.tool.test.ts"},{"assertionResults":[],"startTime":1764247776960,"endTime":1764247776960,"status":"failed","message":"Failed to resolve import \"@testing-library/jest-dom\" from \"testSetup.ts\". Does the file exist?","name":"C:/Users/ssdsk/mastra/src/mastra/tools/tests/serpapi-academic-local.tool.test.ts"},{"assertionResults":[],"startTime":1764247776960,"endTime":1764247776960,"status":"failed","message":"Failed to resolve import \"@testing-library/jest-dom\" from \"testSetup.ts\". Does the file exist?","name":"C:/Users/ssdsk/mastra/src/mastra/tools/tests/serpapi-news-trends.tool.test.ts"},{"assertionResults":[],"startTime":1764247776960,"endTime":1764247776960,"status":"failed","message":"Failed to resolve import \"@testing-library/jest-dom\" from \"testSetup.ts\". Does the file exist?","name":"C:/Users/ssdsk/mastra/src/mastra/tools/tests/serpapi-search.tool.test.ts"},{"assertionResults":[],"startTime":1764247776960,"endTime":1764247776960,"status":"failed","message":"Failed to resolve import \"@testing-library/jest-dom\" from \"testSetup.ts\". Does the file exist?","name":"C:/Users/ssdsk/mastra/src/mastra/tools/tests/serpapi-shopping.tool.test.ts"},{"assertionResults":[],"startTime":1764247776960,"endTime":1764247776960,"status":"failed","message":"Failed to resolve import \"@testing-library/jest-dom\" from \"testSetup.ts\". Does the file exist?","name":"C:/Users/ssdsk/mastra/src/mastra/tools/tests/vector-query.tool.test.ts"},{"assertionResults":[],"startTime":1764247776960,"endTime":1764247776960,"status":"failed","message":"Failed to resolve import \"@testing-library/jest-dom\" from \"testSetup.ts\". Does the file exist?","name":"C:/Users/ssdsk/mastra/src/mastra/tools/tests/weather-tool.test.ts"},{"assertionResults":[],"startTime":1764247776960,"endTime":1764247776960,"status":"failed","message":"Failed to resolve import \"@testing-library/jest-dom\" from \"testSetup.ts\". Does the file exist?","name":"C:/Users/ssdsk/mastra/src/mastra/tools/tests/web-scraper-tool.test.ts"}]} No newline at end of file
{"numTotalTestSuites":2,"numPassedTestSuites":2,"numFailedTestSuites":0,"numPendingTestSuites":0,"numTotalTests":2,"numPassedTests":0,"numFailedTests":0,"numPendingTests":2,"numTodoTests":0,"snapshot":{"added":0,"failure":false,"filesAdded":0,"filesRemoved":0,"filesRemovedList":[],"filesUnmatched":0,"filesUpdated":0,"matched":0,"total":0,"unchecked":0,"uncheckedKeysByFile":[],"unmatched":0,"updated":0,"didUpdate":false},"startTime":1765040377556,"success":true,"testResults":[{"assertionResults":[{"ancestorTitles":["app/api/chat/r - POST"],"fullName":"app/api/chat/r - POST returns 400 when messages missing","status":"skipped","title":"returns 400 when messages missing","failureMessages":[],"meta":{}},{"ancestorTitles":["app/api/chat/r - POST"],"fullName":"app/api/chat/r - POST uses nested data.agentId when provided","status":"skipped","title":"uses nested data.agentId when provided","failureMessages":[],"meta":{}}],"startTime":1765040377556,"endTime":1765040377556,"status":"passed","message":"","name":"C:/Users/ssdsk/AgentStack/tests/api-chat-r.test.ts"}]} No newline at end of file
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

New chat route tests are currently skipped in recorded results

The stored Jest results show numTotalTests: 2 but numPassedTests: 0, numPendingTests: 2, and each assertion has status: "skipped". That means the new app/api/chat/r - POST tests are not actually running in this snapshot, even though success is true.

To ensure the new behavior is really covered:

  • Unskip the tests (remove .skip / pending declarations) and re‑run Jest, or
  • Avoid committing this generated test-results.json altogether if CI is the source of truth.

@greptile-apps
Copy link

greptile-apps bot commented Dec 6, 2025

Greptile Overview

Greptile Summary

This PR improves code quality by implementing stricter null checks and boolean expressions across the codebase, adds 12 new agent documentation files, updates dependencies, and enhances the chat API compatibility layer.

Major Changes:

  • Enhanced null safety by applying Boolean() wrappers and explicit checks following new ESLint rules (strict-boolean-expressions, prefer-nullish-coalescing)
  • Added backward compatibility for network-style and chat-style client requests in /api/chat/r
  • Updated memory configuration for network routes with expanded options (lastMessages: 500, workingMemory, savePerStep)
  • Added 12 new agent documentation files including TypeScript MCP Expert, Python MCP Expert, and various specialized agents
  • Updated AI SDK dependencies to v2.0.108 and reorganized dev dependencies

Issues Found:

  • Critical: Regex escaping errors in network-chat.tsx that will fail to match URLs correctly (lines 419, 422)
  • Critical: Unhandled switch cases throw runtime errors instead of returning null (lines 519-521, routing-panel line 26)
  • Test coverage added for chat API route compatibility

The refactoring improves type safety and follows ESLint configuration, but introduces runtime error risks in unhandled switch cases that need immediate attention.

Confidence Score: 3/5

  • This PR has logical errors in regex patterns and unhandled switch cases that will cause runtime crashes
  • Score reflects critical bugs: incorrect regex escaping will break URL parsing, and throw statements in switch cases will crash the app when those message types are encountered. The null safety improvements are good, but the runtime error risks outweigh the benefits
  • Pay close attention to app/networks/components/network-chat.tsx (regex bugs and throw statements) and app/networks/components/network-routing-panel.tsx (throw statement in switch)

Important Files Changed

File Analysis

Filename Score Overview
app/api/chat/r.ts 4/5 Added compatibility layer for network-style and chat-style client requests with proper fallbacks for agentId, threadId, and resourceId
app/chat/providers/chat-context.tsx 4/5 Improved null safety with explicit boolean checks and updated request formatting to match network provider pattern
app/networks/components/network-chat.tsx 3/5 Applied strict null checks with Boolean() wrappers and curly braces for early returns, added explicit error throws for unhandled cases
app/chat/helpers/tool-part-transform.ts 4/5 Enhanced null safety with explicit Boolean checks and curly braces for all early returns
eslint.config.cjs 5/5 Configured strict TypeScript ESLint rules including strict-boolean-expressions, prefer-nullish-coalescing, and switch-exhaustiveness-check
src/mastra/index.ts 4/5 Enhanced network routes with expanded memory options (lastMessages: 500, workingMemory, threads), added savePerStep, and improved runtime context type safety
app/networks/components/network-routing-panel.tsx 3/5 Added null safety checks and explicit error throw for unhandled pending case in StepStatusIcon switch

Sequence Diagram

sequenceDiagram
    participant Client as Chat/Network Client
    participant API as /api/chat/r
    participant Mastra as Mastra Core
    participant Agent as Selected Agent
    participant Memory as Memory System

    Note over Client,Memory: Chat Flow with Enhanced Compatibility

    Client->>API: POST /api/chat/r<br/>{messages, data: {agentId, threadId}}
    
    Note over API: Extract agentId from<br/>body.agentId ?? body.data.agentId
    
    API->>Mastra: getAgents()
    Mastra-->>API: Available agents list
    
    alt Invalid agentId
        API-->>Client: 400 Error (Invalid agentId)
    else Valid agentId
        Note over API: Extract threadId, resourceId, memory<br/>from top-level or nested data
        
        API->>Mastra: createAgentStreamResponse(agentId, messages, options)
        
        Mastra->>Memory: Initialize with memory config<br/>{thread, resource, options}
        Note over Memory: lastMessages: 500<br/>semanticRecall: true<br/>workingMemory enabled
        
        Memory-->>Mastra: Context loaded
        
        Mastra->>Agent: Execute with tools & context
        
        loop Streaming Response
            Agent->>Agent: Process with tools
            Agent-->>Mastra: Stream chunks (text-delta, reasoning-delta, tool-call, tool-result)
            Mastra-->>API: Stream response
            API-->>Client: SSE stream
        end
        
        Agent->>Memory: Save step results<br/>(savePerStep: true)
        Memory-->>Agent: Persisted
        
        Agent-->>Mastra: Complete
        Mastra-->>API: Finish chunk with usage
        API-->>Client: Stream complete
    end

    Note over Client,Memory: Network Flow with Routing

    Client->>API: POST /api/chat/r<br/>{messages, data: {networkId}}
    
    API->>Mastra: Route to network
    
    Mastra->>Mastra: Determine routing<br/>based on input
    
    loop Network Execution
        Mastra->>Agent: Execute agent in network
        Agent-->>Mastra: Agent result
        Note over Mastra: Track routing steps<br/>for visualization
    end
    
    Mastra-->>API: Stream complete
    API-->>Client: Final response
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.

59 files reviewed, 4 comments

Edit Code Review Agent Settings | Greptile


// Extract URLs for inline citations
const urlMatches = text.match(/\[([^\]]+)\]\((https?:\/\/[^\)]+)\)/g)
const urlMatches = text.match(/\[([^\]]+)\]\((https?:\/\/[^\\)]+)\)/g)
Copy link

Choose a reason for hiding this comment

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

logic: regex escaping issue - [^\\)]+ will match literal backslash followed by ), not just ). Should be [^)]+

Suggested change
const urlMatches = text.match(/\[([^\]]+)\]\((https?:\/\/[^\\)]+)\)/g)
const urlMatches = text.match(/\[([^\]]+)\]\((https?:\/\/[^)]+)\)/g)
Prompt To Fix With AI
This is a comment left during a code review.
Path: app/networks/components/network-chat.tsx
Line: 419:419

Comment:
**logic:** regex escaping issue - `[^\\)]+` will match literal backslash followed by `)`, not just `)`. Should be `[^)]+`

```suggestion
            const urlMatches = text.match(/\[([^\]]+)\]\((https?:\/\/[^)]+)\)/g)
```

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

const textMatch = match.match(/\[([^\]]+)\]/)
const urlMatch = match.match(/\((https?:\/\/[^\)]+)\)/)
const textMatch = /\[([^\]]+)\]/.exec(match)
const urlMatch = /\((https?:\/\/[^\\)]+)\)/.exec(match)
Copy link

Choose a reason for hiding this comment

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

logic: regex escaping issue - same as line 419, [^\\)]+ should be [^)]+

Suggested change
const urlMatch = /\((https?:\/\/[^\\)]+)\)/.exec(match)
const urlMatch = /\((https?:\/\/[^)]+)\)/.exec(match)
Prompt To Fix With AI
This is a comment left during a code review.
Path: app/networks/components/network-chat.tsx
Line: 422:422

Comment:
**logic:** regex escaping issue - same as line 419, `[^\\)]+` should be `[^)]+`

```suggestion
              const urlMatch = /\((https?:\/\/[^)]+)\)/.exec(match)
```

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

Comment on lines +519 to +521
case "step-start": { throw new Error('Not implemented yet: "step-start" case') }
case "dynamic-tool": { throw new Error('Not implemented yet: "dynamic-tool" case') }
case "source-document": { throw new Error('Not implemented yet: "source-document" case') }
Copy link

Choose a reason for hiding this comment

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

logic: throwing errors for unimplemented cases will crash the app at runtime. These cases should return null or be removed from the switch if they're intentionally unhandled

Suggested change
case "step-start": { throw new Error('Not implemented yet: "step-start" case') }
case "dynamic-tool": { throw new Error('Not implemented yet: "dynamic-tool" case') }
case "source-document": { throw new Error('Not implemented yet: "source-document" case') }
case "step-start":
case "dynamic-tool":
case "source-document":
return null
Prompt To Fix With AI
This is a comment left during a code review.
Path: app/networks/components/network-chat.tsx
Line: 519:521

Comment:
**logic:** throwing errors for unimplemented cases will crash the app at runtime. These cases should return `null` or be removed from the switch if they're intentionally unhandled

```suggestion
          case "step-start":
          case "dynamic-tool":
          case "source-document":
            return null
```

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

return <Loader2Icon className="size-4 animate-spin text-blue-500" />
case "error":
return <XCircleIcon className="size-4 text-red-500" />
case "pending": { throw new Error('Not implemented yet: "pending" case') }
Copy link

Choose a reason for hiding this comment

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

logic: throwing error for pending case will crash at runtime. Should return appropriate icon or remove case

Suggested change
case "pending": { throw new Error('Not implemented yet: "pending" case') }
case "pending":
return <CircleIcon className="size-4 text-muted-foreground" />
Prompt To Fix With AI
This is a comment left during a code review.
Path: app/networks/components/network-routing-panel.tsx
Line: 26:26

Comment:
**logic:** throwing error for pending case will crash at runtime. Should return appropriate icon or remove case

```suggestion
    case "pending":
      return <CircleIcon className="size-4 text-muted-foreground" />
```

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

…SQL stores

- Removed optional WorkOS configuration from .env.example.
- Initialized MongoDB store and created a vector index for embeddings in mongodb.ts.
- Initialized PostgreSQL store and logged index details in pg-storage.ts.
- Updated memory configuration to use HNSW index type in mongodb.ts.
- Adjusted import statement for ExtractParams to use type import in upstashMemory.ts.
- Added CORS configuration to mastra index for better API access control.
- Added authentication logic using Supabase in auth.ts.
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: 6

Caution

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

⚠️ Outside diff range comments (9)
src/mastra/config/mongodb.ts (4)

67-88: Misleading comments contradict the actual configuration.

Several comments are inconsistent with the code:

  1. Line 67: States "Using PgVector with flat" but this is MongoDBVector with HNSW.
  2. Line 82: Comment says "flat index type" but type: 'hnsw' is set.
-    vector: mongoVector, // Using PgVector with flat for 3072 dimension embeddings (gemini-embedding-001)
+    vector: mongoVector, // Using MongoDBVector with HNSW for high-dimensional embeddings
     embedder: google.textEmbedding('gemini-embedding-001'),
     ...
             indexConfig: {
-                type: 'hnsw', // flat index type (supports dimensions > 4000, unlike HNSW limit of 2000)
+                type: 'hnsw', // HNSW index for efficient approximate nearest neighbor search
                 metric: 'cosine', // Distance metric for normalized embeddings

105-132: Logged configuration doesn't match actual Memory configuration.

The log statement reports incorrect configuration:

  • Line 105: Says "PgVector support" but using MongoDBVector
  • Lines 117-121: Logs type: 'flat' with ivf: { lists: 4000 } but actual config (lines 82-87) uses type: 'hnsw' with m: 16, efConstruction: 200

This inconsistency will cause confusion when debugging or auditing the system.

Update the log to reflect the actual configuration:

-log.info('Mongos and Memory initialized with PgVector support', {
+log.info('MongoDB and Memory initialized with MongoDBVector support', {
     ...
             indexConfig: {
-                type: 'flat',
+                type: 'hnsw',
                 metric: 'cosine',
-                ivf: { lists: 4000 }, // Adjust list count based on your needs
+                hnsw: { m: 16, efConstruction: 200 },
             }

98-100: Potential logic inversion in generateTitle condition.

The condition process.env.THREAD_GENERATE_TITLE !== 'true' sets generateTitle to false when the environment variable is 'true'. This seems inverted—typically you'd want:

  • THREAD_GENERATE_TITLE=truegenerateTitle: true
  • THREAD_GENERATE_TITLE=false (or unset) → generateTitle: false

If the intent is to enable title generation when the env var is set to 'true':

         threads: {
-            generateTitle: process.env.THREAD_GENERATE_TITLE !== 'true',
+            generateTitle: process.env.THREAD_GENERATE_TITLE === 'true',
         },

Note: The same inverted logic appears at line 129 in the log statement.


566-573: Validation could be enhanced but acceptable for current use.

The validateMongoDBFilter function provides basic validation. Consider adding checks for common MongoDB query injection patterns if filters are constructed from user input.

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

34-48: Enhance regex pattern to handle more JSON formats.

The maskSensitiveMessageData utility correctly masks JSON-like sensitive fields, but the regex pattern only matches double-quoted values. Consider enhancing it to handle single quotes, unquoted values, and nested structures.

Apply this diff to handle more formats:

     for (const field of sensitiveFields) {
-        // Match field:"value" or field: "value" or "field": "value" patterns
-        const regex = new RegExp(`("${field}"\\s*:\\s*)"[^"]*"`, 'gi');
-        maskedContent = maskedContent.replace(regex, `$1"[MASKED]"`);
+        // Match field:"value", field:'value', and field: value patterns
+        const doubleQuoteRegex = new RegExp(`("${field}"\\s*:\\s*)"[^"]*"`, 'gi');
+        const singleQuoteRegex = new RegExp(`('${field}'\\s*:\\s*)'[^']*'`, 'gi');
+        maskedContent = maskedContent.replace(doubleQuoteRegex, `$1"[MASKED]"`);
+        maskedContent = maskedContent.replace(singleQuoteRegex, `$1'[MASKED]'`);
     }

131-131: Critical: Inverted logic for generateTitle.

The condition process.env.THREAD_GENERATE_TITLE !== 'true' produces inverted behavior:

  • When THREAD_GENERATE_TITLE='true'generateTitle becomes false
  • When THREAD_GENERATE_TITLE='false' or unset → generateTitle becomes true

Apply this diff to fix the logic:

         threads: {
-            generateTitle: process.env.THREAD_GENERATE_TITLE !== 'true',
+            generateTitle: process.env.THREAD_GENERATE_TITLE === 'true',
         },

Note: Line 161 in the logging block has the same issue and should also be corrected.


106-109: Incorrect index configuration mixing flat with IVF.

The type: 'flat' index configuration includes an ivf: {lists: 4000} parameter, which is incompatible. The ivf parameter is only applicable to IVFFlat index type, not flat.

Apply this diff to fix the index configuration:

             indexConfig: {
                 type: 'flat', // flat index type (supports dimensions > 4000, unlike HNSW limit of 2000)
                 metric: 'cosine', // Distance metric for normalized embeddings
-                ivf: {lists: 4000},
             }

If you need IVF indexing for better performance with large datasets, change the type:

             indexConfig: {
-                type: 'flat', // flat index type (supports dimensions > 4000, unlike HNSW limit of 2000)
+                type: 'ivfflat',
                 metric: 'cosine',
                 ivf: {lists: 4000},
             }

79-86: Fix embedding model and dimension inconsistencies in comments.

The comments reference a non-existent gemini-embedding-002 model and contain conflicting dimension information:

  • Line 79: "1568 dimension embeddings (gemini-embedding-002)" — gemini-embedding-002 does not exist in Google's official API; the actual model is gemini-embedding-001
  • Line 79 also claims 1568 dimensions, which is not a standard dimension for Google's embedding models
  • Line 179: Correctly uses gemini-embedding-001 with 3072 dimensions, which is the default and correct configuration

Google's gemini-embedding-001 supports configurable output dimensionality up to 3072 (the default), with commonly used values being 3072, 1536, or 768. Update the comments to accurately reflect the model name and verify the intended dimension value (1568 does not appear to be a standard supported dimension).


342-399: Remove unsafe type assertion and properly construct UIMessage object.

The formatStorageMessages function uses as UIMessage to bypass type checking (line 398), which the function's own comment acknowledges as incomplete ("would need proper conversion in real implementation"). The constructed messageData object does not strictly match the UIMessage type from the 'ai' package—it uses a generic parts array structure instead of properly typed message parts or a content property.

Replace the type assertion with proper construction that matches the UIMessage interface from 'ai' v5.0.108, either by adding a content property alongside parts or by ensuring the parts array uses the correct UIMessage part types.

♻️ Duplicate comments (1)
src/mastra/index.ts (1)

520-520: Removal of includeTextStreamParts may break streaming behavior.

The removal of includeTextStreamParts: true from these workflow routes will change the streaming response format. Clients expecting text stream parts in the workflow response may no longer receive them.

Verify that downstream consumers of these workflow endpoints can handle the updated response format:

#!/bin/bash
# Description: Find usages of repoIngestionWorkflow and specGenerationWorkflow streaming responses

# Search for workflow consumers
rg -n --type=ts --type=tsx -C3 'repoIngestionWorkflow|specGenerationWorkflow'

# Search for code handling text stream parts
rg -n --type=ts --type=tsx -C3 'textStreamParts|includeTextStreamParts'

Also applies to: 525-525

📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8b7b374 and 832d8a7.

📒 Files selected for processing (6)
  • .env.example (0 hunks)
  • lib/auth.ts (1 hunks)
  • src/mastra/config/mongodb.ts (3 hunks)
  • src/mastra/config/pg-storage.ts (2 hunks)
  • src/mastra/config/upstashMemory.ts (1 hunks)
  • src/mastra/index.ts (11 hunks)
💤 Files with no reviewable changes (1)
  • .env.example
🧰 Additional context used
📓 Path-based instructions (7)
**/*.{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:

  • lib/auth.ts
  • src/mastra/config/upstashMemory.ts
  • src/mastra/index.ts
  • src/mastra/config/mongodb.ts
  • src/mastra/config/pg-storage.ts
**/*.{js,ts}

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

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

Files:

  • lib/auth.ts
  • src/mastra/config/upstashMemory.ts
  • src/mastra/index.ts
  • src/mastra/config/mongodb.ts
  • src/mastra/config/pg-storage.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

Files:

  • lib/auth.ts
  • src/mastra/config/upstashMemory.ts
  • src/mastra/index.ts
  • src/mastra/config/mongodb.ts
  • src/mastra/config/pg-storage.ts
src/mastra/config/upstashMemory.ts

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

Upstash Redis memory configuration in upstashMemory.ts should provide an alternative memory provider for the system

Files:

  • src/mastra/config/upstashMemory.ts
src/mastra/config/**/*.ts

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

All external service initialization in the config directory must be environment-driven, with sensitive credentials loaded from environment variables and never hardcoded

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/upstashMemory.ts
  • src/mastra/config/mongodb.ts
  • src/mastra/config/pg-storage.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/config/upstashMemory.ts
  • src/mastra/index.ts
  • src/mastra/config/mongodb.ts
  • src/mastra/config/pg-storage.ts
src/mastra/config/pg-storage.ts

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

PostgreSQL storage configuration in pg-storage.ts should initialize PgVector for 3072-dimensional embeddings and support semantic recall, memory management, and thread storage

Files:

  • src/mastra/config/pg-storage.ts
🧬 Code graph analysis (1)
src/mastra/config/pg-storage.ts (1)
src/mastra/config/logger.ts (1)
  • log (14-18)
⏰ 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). (1)
  • GitHub Check: Codacy Security Scan
🔇 Additional comments (12)
src/mastra/config/upstashMemory.ts (3)

220-226: Environment variables loaded correctly; verify deployment configuration.

Credentials are properly sourced from environment variables with fallback placeholders. Ensure all required environment variables (UPSTASH_REDIS_REST_URL, UPSTASH_REDIS_REST_TOKEN, UPSTASH_VECTOR_REST_URL, UPSTASH_VECTOR_REST_TOKEN) are configured in production before deployment.


13-13: Type-only import correctly applied for ExtractParams.

The change to import ExtractParams as type-only is correct. ExtractParams is used exclusively as a type annotation in the extractChunkMetadata function parameter (line 858) and never at runtime. This follows TypeScript best practices and prevents unnecessary module inclusion in the bundle. The file also properly manages sensitive credentials through environment variables with placeholder defaults, adhering to configuration guidelines.


612-612: The eslint-disable comment at line 612 is properly justified and follows linting best practices.

The explicit @typescript-eslint/no-explicit-any disable comment includes a clear justification ("Using 'any' for UpstashVectorFilter compatibility") and is correctly scoped to only the necessary variable assignment. The comment demonstrates awareness of the linting rule and provides valid reasoning for the exception, which is appropriate for library type compatibility constraints.

src/mastra/config/mongodb.ts (5)

19-27: LGTM: Environment-driven configuration.

Configuration properly uses environment variables with sensible defaults. Sensitive credentials like MONGODB_URI are loaded from the environment as required by the coding guidelines.


187-295: LGTM: Well-structured document processing with proper error handling.

The processDocument function correctly:

  • Uses try-catch blocks for async operations per coding guidelines
  • Implements tracing/observability with span creation
  • Handles errors by logging and re-throwing
  • Returns clean data structures

300-387: LGTM: Proper vector storage with comprehensive error handling and tracing.

The storeDocumentEmbeddings function has good practices:

  • Consistent error handling pattern with try-catch
  • Proper span lifecycle management (creation, end, error)
  • Timing metrics for observability

392-494: LGTM: Query function with robust error handling.

The querySimilarDocuments function properly:

  • Handles the optional filter parameter
  • Ensures metadata is always defined (line 466)
  • Maintains consistent error handling and tracing patterns

509-551: LGTM: RAG tools properly configured with environment-driven parameters.

Both mongoGraphTool and mongoQueryTool use:

  • Consistent config from MONGODB_CONFIG
  • Environment variables for tunable parameters
  • Clear, descriptive IDs and descriptions
src/mastra/index.ts (2)

538-538: Enhanced memory configuration looks good.

The addition of lastMessages: 500 and threads: { generateTitle: true } provides better context management and automatic thread titling across all network routes. The configuration is consistent across routes.

Note: Ensure this aligns with the memory configuration in pg-storage.ts (which sets lastMessages to 500 via environment variable with the same default).

Also applies to: 561-561, 584-584, 606-606, 627-627


655-661: Excellent defensive body parsing.

The enhanced type guards properly validate that both body and body.data are objects before attempting to iterate their entries. This prevents runtime errors from malformed requests and follows best practices for input validation.

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

21-31: Good masking utility for sensitive stream data.

The createMaskedStream utility properly chains maskStreamTags to mask multiple sensitive XML-like tags in async streams. This aligns with the coding guideline: "Never commit API keys or secrets to the repository; use maskSensitiveMessageData() helper."

Consider expanding the default sensitiveTags to include additional fields like 'apiKey', 'bearer', and 'authorization' for more comprehensive coverage.


214-339: Excellent embedding generation implementation with comprehensive observability.

The generateEmbeddings function demonstrates production-grade quality with:

  • Proper tracing span lifecycle management
  • Comprehensive error handling with span error recording
  • Detailed telemetry configuration
  • Performance monitoring (processing time tracking)
  • Proper logging at all stages

The implementation follows observability best practices and properly integrates with the Mastra tracing infrastructure.

Comment on lines +1 to +10
import { createClient } from "@supabase/supabase-js";

const supabase = createClient("<supabase-url>", "<supabase-key>");

const authTokenResponse = await supabase.auth.signInWithPassword({
email: "<user's email>",
password: "<user's password>",
});

const accessToken = authTokenResponse.data?.session?.access_token;
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:

find . -type f -name "*.ts" -o -name "*.tsx" -o -name "*.js" -o -name "*.jsx" | head -20

Repository: ssdeanx/AgentStack

Length of output: 691


🏁 Script executed:

cat -n lib/auth.ts

Repository: ssdeanx/AgentStack

Length of output: 453


🏁 Script executed:

find . -type f -name "*supabase*" -o -path "*/config/*" -type f | grep -E "\.(ts|tsx|js|jsx)$"

Repository: ssdeanx/AgentStack

Length of output: 1272


🏁 Script executed:

rg "maskSensitiveMessageData" --type ts --type tsx -A 2 -B 2

Repository: ssdeanx/AgentStack

Length of output: 89


🏁 Script executed:

rg "createClient.*supabase" -A 3 -B 1 --type ts --type tsx

Repository: ssdeanx/AgentStack

Length of output: 89


🏁 Script executed:

rg "process\.env\." --type ts --type tsx | head -20

Repository: ssdeanx/AgentStack

Length of output: 89


🏁 Script executed:

cat -n src/mastra/config/pg-storage.ts | head -50

Repository: ssdeanx/AgentStack

Length of output: 2365


🏁 Script executed:

find . -name ".env*" -o -name "*.env*"

Repository: ssdeanx/AgentStack

Length of output: 76


🏁 Script executed:

grep -r "process\.env" --include="*.ts" --include="*.js" | head -10

Repository: ssdeanx/AgentStack

Length of output: 870


🏁 Script executed:

ls -la lib/

Repository: ssdeanx/AgentStack

Length of output: 548


🏁 Script executed:

cat -n .env.example

Repository: ssdeanx/AgentStack

Length of output: 2548


🏁 Script executed:

grep -r "supabase" --include="*.ts" --include="*.js" -i

Repository: ssdeanx/AgentStack

Length of output: 463


Remove hard‑coded secrets and credentials; refactor auth to use environment variables and explicit error handling

The snippet contains critical security and design issues:

  • Hard‑coded Supabase URL, key, and user credentials directly in source code
  • Top‑level await performs authentication as a module side effect on import
  • No error handling for the authentication call
  • Derived accessToken is not exported or used anywhere

Move configuration to environment variables (SUPABASE_URL and SUPABASE_KEY), pass credentials at call‑time rather than hard‑coding them, add explicit error handling, and export a reusable async helper function instead of running auth on module load:

-import { createClient } from "@supabase/supabase-js";
-
-const supabase = createClient("<supabase-url>", "<supabase-key>");
-
-const authTokenResponse = await supabase.auth.signInWithPassword({
-  email: "<user's email>",
-  password: "<user's password>",
-});
-
-const accessToken = authTokenResponse.data?.session?.access_token;
+import { createClient } from "@supabase/supabase-js";
+
+const supabaseUrl = process.env.SUPABASE_URL;
+const supabaseKey = process.env.SUPABASE_KEY;
+
+if (!supabaseUrl || !supabaseKey) {
+  throw new Error("Missing Supabase environment variables");
+}
+
+export const supabase = createClient(supabaseUrl, supabaseKey);
+
+export async function signInWithEmailPassword(
+  email: string,
+  password: string,
+) {
+  try {
+    const { data, error } = await supabase.auth.signInWithPassword({
+      email,
+      password,
+    });
+
+    if (error) {
+      throw error;
+    }
+
+    return data.session?.access_token ?? null;
+  } catch (err) {
+    // Use maskSensitiveMessageData helper when logging auth errors
+    throw err;
+  }
+}

Call signInWithEmailPassword from the appropriate server route or action with real credentials obtained at runtime.

📝 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
import { createClient } from "@supabase/supabase-js";
const supabase = createClient("<supabase-url>", "<supabase-key>");
const authTokenResponse = await supabase.auth.signInWithPassword({
email: "<user's email>",
password: "<user's password>",
});
const accessToken = authTokenResponse.data?.session?.access_token;
import { createClient } from "@supabase/supabase-js";
const supabaseUrl = process.env.SUPABASE_URL;
const supabaseKey = process.env.SUPABASE_KEY;
if (!supabaseUrl || !supabaseKey) {
throw new Error("Missing Supabase environment variables");
}
export const supabase = createClient(supabaseUrl, supabaseKey);
export async function signInWithEmailPassword(
email: string,
password: string,
) {
try {
const { data, error } = await supabase.auth.signInWithPassword({
email,
password,
});
if (error) {
throw error;
}
return data.session?.access_token ?? null;
} catch (err) {
// Use maskSensitiveMessageData helper when logging auth errors
throw err;
}
}
🤖 Prompt for AI Agents
In lib/auth.ts lines 1-10: remove hard-coded Supabase URL/key and credentials,
eliminate the top-level await side-effect, and replace with an exported async
helper that creates the client from process.env.SUPABASE_URL and
process.env.SUPABASE_KEY and accepts email/password as parameters; call
signInWithPassword inside that function with try/catch to return the session or
throw/return a clear error so callers handle failures, and do not perform
authentication at module import or expose secrets in source.

Comment on lines +33 to +41

await mongoStore.init();
//const allIndexes = await mongoStore.listIndexes();
//console.log(allIndexes);
//log.info('MongoDB Store initialized with MongoDBVector support, all indexes:', {
// indexCount: allIndexes.length,
// indexes: allIndexes,
//});

Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Top-level await blocks module loading; remove commented-out debug code.

Two concerns here:

  1. Top-level await: await mongoStore.init() executes during module import, which blocks the module from loading until the MongoDB connection completes. This can cause startup delays or failures if MongoDB is unavailable, and makes error handling difficult.

  2. Dead code: The commented-out debug logging (lines 35-40) should be removed before merging to main.

Consider deferring initialization to an explicit startup function:

-await mongoStore.init();
-//const allIndexes = await mongoStore.listIndexes();
-//console.log(allIndexes);
-//log.info('MongoDB Store initialized with MongoDBVector support, all indexes:', {
-//    indexCount: allIndexes.length,
-//    indexes: allIndexes,
-//});
-
+let isStoreInitialized = false;
+
+export async function initializeMongoStore(): Promise<void> {
+  if (isStoreInitialized) return;
+  await mongoStore.init();
+  isStoreInitialized = true;
+  log.info('MongoDB Store initialized');
+}

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

🤖 Prompt for AI Agents
In src/mastra/config/mongodb.ts around lines 33 to 41, remove the top-level
await and the commented-out debug logging: delete the lines calling await
mongoStore.init() at module import and remove the commented listIndexes/log.info
block; instead export (or add) an explicit async initializeMongoStore() function
that performs mongoStore.init() with try/catch and proper logging so
initialization is invoked from the app startup sequence (not during module
import) and errors can be handled gracefully.

Comment on lines +51 to +55
// Create a vector index for embeddings
await mongoVector.createIndex({
indexName: "ultra",
dimension: 1536,
});
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Hardcoded index name and dimension; top-level await without error handling.

  1. The index name "ultra" and dimension 1536 are hardcoded while MONGODB_CONFIG already defines these values (collectionName, embeddingDimension). This creates inconsistency.

  2. Top-level await without try-catch will crash the module import if index creation fails.

  3. There's already an initializeVectorIndex() function at line 159 that handles this properly with error handling.

Consider removing the duplicate top-level initialization and use the existing function:

-// Create a vector index for embeddings
-await mongoVector.createIndex({
-  indexName: "ultra",
-  dimension: 1536,
-});
+// Index should be created via initializeVectorIndex() during application startup

Or if eager initialization is required, use consistent config values:

-  indexName: "ultra",
-  dimension: 1536,
+  indexName: MONGODB_CONFIG.collectionName,
+  dimension: MONGODB_CONFIG.embeddingDimension,

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

🤖 Prompt for AI Agents
In src/mastra/config/mongodb.ts around lines 51 to 55: there is a duplicate
top-level await that creates a vector index with hardcoded indexName "ultra" and
dimension 1536 and it lacks error handling; remove this duplicate top-level
initialization and instead call the existing initializeVectorIndex() function
(which already uses MONGODB_CONFIG.collectionName and
MONGODB_CONFIG.embeddingDimension and has try/catch) or, if you truly need eager
initialization at import time, replace the hardcoded values with
MONGODB_CONFIG.collectionName and MONGODB_CONFIG.embeddingDimension and wrap the
await in a try/catch so any failure is logged/handled instead of crashing module
import.

Comment on lines +71 to +77
await pgStore.init();
const allIndexes = await pgStore.listIndexes();
console.log(allIndexes);
log.info('PostgreSQL Store initialized with PgVector support, all indexes:', {
indexCount: allIndexes.length,
indexes: allIndexes,
});
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

Critical: Top-level await blocks module loading.

Using top-level await for pgStore.init() creates a blocking async dependency that:

  • Will cause module loading to fail if initialization fails
  • Makes the entire application dependent on successful database connection at startup
  • May not work reliably across all module systems
  • Uses console.log instead of the configured logger

Apply this diff to use a proper initialization pattern:

-await pgStore.init();
-const allIndexes = await pgStore.listIndexes();
-console.log(allIndexes);
-log.info('PostgreSQL Store initialized with PgVector support, all indexes:', {
-    indexCount: allIndexes.length,
-    indexes: allIndexes,
-});
+// Initialize storage asynchronously - call this from your application startup
+export async function initializePgStorage() {
+    try {
+        await pgStore.init();
+        const allIndexes = await pgStore.listIndexes();
+        log.info('PostgreSQL Store initialized with PgVector support, all indexes:', {
+            indexCount: allIndexes.length,
+            indexes: allIndexes,
+        });
+        return { success: true, indexes: allIndexes };
+    } catch (error) {
+        log.error('Failed to initialize PostgreSQL storage:', error);
+        throw error;
+    }
+}

Then call initializePgStorage() from your application's startup routine (e.g., in instrumentation.ts or main server file).

📝 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
await pgStore.init();
const allIndexes = await pgStore.listIndexes();
console.log(allIndexes);
log.info('PostgreSQL Store initialized with PgVector support, all indexes:', {
indexCount: allIndexes.length,
indexes: allIndexes,
});
// Initialize storage asynchronously - call this from your application startup
export async function initializePgStorage() {
try {
await pgStore.init();
const allIndexes = await pgStore.listIndexes();
log.info('PostgreSQL Store initialized with PgVector support, all indexes:', {
indexCount: allIndexes.length,
indexes: allIndexes,
});
return { success: true, indexes: allIndexes };
} catch (error) {
log.error('Failed to initialize PostgreSQL storage:', error);
throw error;
}
}
🤖 Prompt for AI Agents
In src/mastra/config/pg-storage.ts around lines 71-77, the file currently
performs top-level await (await pgStore.init()) and a console.log which blocks
module loading and couples import to DB availability; replace this with an
exported async function initializePgStorage() that performs pgStore.init(),
awaits pgStore.listIndexes(), logs via the configured log object (not
console.log), catches and surfaces initialization errors without running at
module import time, and ensure callers invoke initializePgStorage() from the
application startup routine (e.g., instrumentation.ts or main server) rather
than importing this module to trigger init.

recordOutputs: true,
},
includeRawChunks: true,
savePerStep: 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/index.ts | sed -n '540,560p'

Repository: ssdeanx/AgentStack

Length of output: 735


🏁 Script executed:

cat -n src/mastra/index.ts | sed -n '560,580p'

Repository: ssdeanx/AgentStack

Length of output: 834


🏁 Script executed:

cat -n src/mastra/index.ts | sed -n '625,650p'

Repository: ssdeanx/AgentStack

Length of output: 1060


🏁 Script executed:

# Check the complete network definitions to understand structure
wc -l src/mastra/index.ts

Repository: ssdeanx/AgentStack

Length of output: 85


🏁 Script executed:

# Search for all network definitions and savePerStep usage
rg -n 'export const.*Network|savePerStep' src/mastra/index.ts

Repository: ssdeanx/AgentStack

Length of output: 160


🏁 Script executed:

# Look for any comments explaining the savePerStep strategy
rg -B5 -A2 'savePerStep' src/mastra/index.ts

Repository: ssdeanx/AgentStack

Length of output: 637


🏁 Script executed:

# Get context around each savePerStep to identify which network each belongs to
cat -n src/mastra/index.ts | sed -n '535,555p'

Repository: ssdeanx/AgentStack

Length of output: 812


🏁 Script executed:

cat -n src/mastra/index.ts | sed -n '545,575p'

Repository: ssdeanx/AgentStack

Length of output: 1134


🏁 Script executed:

cat -n src/mastra/index.ts | sed -n '610,640p'

Repository: ssdeanx/AgentStack

Length of output: 1112


🏁 Script executed:

# Find all networkRoute calls to determine total number of networks
rg -n 'networkRoute\(\{' src/mastra/index.ts

Repository: ssdeanx/AgentStack

Length of output: 190


🏁 Script executed:

# Check the full section to see all networks and their savePerStep status
cat -n src/mastra/index.ts | sed -n '480,670p'

Repository: ssdeanx/AgentStack

Length of output: 6966


Apply savePerStep: true consistently across all five network routes, or document why certain networks exclude it.

The code applies savePerStep: true to agentNetwork, dataPipelineNetwork, and codingTeamNetwork, but omits it from reportGenerationNetwork and researchPipelineNetwork. Since all networks share identical memory, maxSteps, and telemetry configurations, this selective application appears inconsistent. Either extend savePerStep: true to all networks for uniform step persistence, or add comments explaining the rationale for the two exceptions.

🤖 Prompt for AI Agents
In src/mastra/index.ts around line 547, the configuration sets savePerStep: true
for agentNetwork, dataPipelineNetwork, and codingTeamNetwork but omits it for
reportGenerationNetwork and researchPipelineNetwork; make this consistent by
adding savePerStep: true to the two missing network configs
(reportGenerationNetwork and researchPipelineNetwork) so all five networks have
identical memory/maxSteps/telemetry/savePerStep settings, or alternatively add a
short comment above each of the two networks explaining the intentional reason
for excluding savePerStep if there is a specific rationale.

Comment on lines +640 to +645
cors: {
origin: ["*"], // Allow specific origins or '*' for all
allowMethods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allowHeaders: ["Content-Type", "Authorization"],
credentials: false,
},
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

Critical: Wildcard CORS origin exposes API to all domains.

The CORS configuration with origin: ["*"] allows any domain to make requests to your API endpoints. This is a significant security risk, even with credentials: false, as it:

  • Exposes your API to potential abuse from any website
  • Makes CSRF protection more difficult
  • Could leak sensitive data through cross-origin requests

Apply this diff to use environment-driven, specific origins:

     cors: {
-      origin: ["*"], // Allow specific origins or '*' for all
+      origin: process.env.CORS_ALLOWED_ORIGINS?.split(',') ?? ["http://localhost:3000"],
       allowMethods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
       allowHeaders: ["Content-Type", "Authorization"],
       credentials: false,
     },

Then set CORS_ALLOWED_ORIGINS=https://yourdomain.com,https://app.yourdomain.com in your environment variables.

As per coding guidelines: "All external service initialization in the config directory must be environment-driven, with sensitive credentials loaded from environment variables."

📝 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
cors: {
origin: ["*"], // Allow specific origins or '*' for all
allowMethods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allowHeaders: ["Content-Type", "Authorization"],
credentials: false,
},
cors: {
origin: process.env.CORS_ALLOWED_ORIGINS?.split(',') ?? ["http://localhost:3000"],
allowMethods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allowHeaders: ["Content-Type", "Authorization"],
credentials: false,
},
🤖 Prompt for AI Agents
In src/mastra/index.ts around lines 640 to 645, the CORS config currently uses a
wildcard origin ["*"], which is unsafe; change it to read allowed origins from
an environment variable (e.g. CORS_ALLOWED_ORIGINS) and parse it into an array
of specific origins (splitting on commas and trimming whitespace), then set
cors.origin to that array (with a safe default such as [] or localhost-only),
keep credentials false if appropriate, and ensure the environment variable is
documented/required in your deployment env (e.g.
CORS_ALLOWED_ORIGINS=https://yourdomain.com,https://app.yourdomain.com).

@ssdeanx ssdeanx closed this Dec 6, 2025
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